问:
The Meaning of @override in Android Studio
I am completely new to Android Studio and I want to know the purpose of the @Override statement in Android Studio.

答:
@Override is a Java annotation. It tells the compiler that the following method overrides a method of its superclass. For instance, say you implement a Person class.

```<code>public class Person {
   public final String firstName;
   public final String lastName;

   //some methods

   @Override public boolean equals(Object other) {
      ...
   }
}
</code>```

The person class has an equals() method. The equals method is already defined in Person's superclass Object. Therefore the above implementation of equals() is a redefinition of equals() for Persons. That is to say, Person overrides equals().

It is legal to override methods without explicitly annotating it. So what is the @Override annotation good for? What if you accidentally tried to override equals() that way:

```<code>public boolean equals(Person other) {
   ...
}
</code>```

The above case has a bug. You meant to override equals() but you didn't. Why? because the real equals() gets an Object as a parameter and your equals() gets a Person as a parameter. The compiler is not going to tell you about the bug because the compiler doesn't know you wanted to override. As far as the compiler can tell, you actually meant to overload equals(). But if you tried to override equals using the @Override annotation:

```<code>@Override public boolean equals(Person other) {
   ...
}
</code>```

Now the compiler knows that you have an error. You wanted to override but you didn't. So the reason to use the @Override annotation is to explicitly declare method overriding.

Body:
@Override is a Java annotation. It tells the compiler that the following method overrides a method of its superclass. For instance, say you implement a Person class.

public class Person {
   public final String firstName;
   public final String lastName;

   //some methods

   @Override public boolean equals(Object other) {
      ...
   }
}

The person class has an equals() method. The equals method is already defined in Person's superclass Object. Therefore the above implementation of equals() is a redefinition of equals() for Persons. That is to say, Person overrides equals().

It is legal to override methods without explicitly annotating it. So what is the @Override annotation good for? What if you accidentally tried to override equals() that way:

public boolean equals(Person other) {
   ...
}

The above case has a bug. You meant to override equals() but you didn't. Why? because the real equals() gets an Object as a parameter and your equals() gets a Person as a parameter. The compiler is not going to tell you about the bug because the compiler doesn't know you wanted to override. As far as the compiler can tell, you actually meant to overload equals(). But if you tried to override equals using the @Override annotation:

@Override public boolean equals(Person other) {
   ...
}

Now the compiler knows that you have an error. You wanted to override but you didn't. So the reason to use the @Override annotation is to explicitly declare method overriding.


来源: stackexchange

问:
radeditor contenteditable anchor tags not selected in ie11
Am using radeditor. User will be inserting links (anchor tags) into it. And the anchor tags will have contenteditable="false" just so the link text is not changeable. But, the problem is when I click on the link the entire link text is supposed to show as selected.

This is working fine on IE7 and in compatibility mode with higher version browsers.
But, in standard mode of IE 8, 9, 10 and 11 it does not.

This gives an impression that its purely related to browser engine. But, I would like to know if there is any alternative approach for this issue to show the links as selected.

Appreciate any suggestions.
Thanks.

答:
I couldn't bring the same appearance like the first screenshot. But, I was able to select the element as a whole using some custom script which is fine for the end user in my case. Below is the script if some is looking for.</p>

```<code>function OnClientLoad(editor, args) {
    editor.attachEventHandler("onmouseup", function (e) {
        var selectedElm = e.srcElement;
        if (selectedElm.tagName && selectedElm.tagName.toLowerCase() == 'a') {
            editor.selectElement(selectedElm);
            if (e.preventDefault) {
                e.preventDefault();
            }
        }
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I couldn't bring the same appearance like the first screenshot. But, I was able to select the element as a whole using some custom script which is fine for the end user in my case. Below is the script if some is looking for.

function OnClientLoad(editor, args) {
    editor.attachEventHandler("onmouseup", function (e) {
        var selectedElm = e.srcElement;
        if (selectedElm.tagName && selectedElm.tagName.toLowerCase() == 'a') {
            editor.selectElement(selectedElm);
            if (e.preventDefault) {
                e.preventDefault();
            }
        }
    });
}


问:
view bag message not working properly on button click success using asp.net mvc?
When i click on save button then success alert message is displayed, but i require only save function successful then only success alert message should be displayed.

In my code i written success alert message in button on click so it is not working properly. how to call id="bn-success" in view bag message on success.

```<code><input type="submit" name="actionType" id="bn-success" value="Save" class="btn btn-rounded btn-inline btn-success" />
</code>```

Controller:

```<code>[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Domain(Domain domain)
        {
            try
            {
                int refID = Convert.ToInt32(Session["RefID"]);
                if (ModelState.IsValid && refID > 0)
                {
                    userType type = new userType();
                    int id = type.AddDomain(domain, refID);
                    if (id != 0)
                    {
                        ViewBag.Message = "Domain added successfully";
                    }
                }
                return View();
            }
            catch
            {
                return View();
            }

        }
</code>```

Alert message:

```<code> $('#bn-success').on('click', function() {
        $.notify({
            icon: 'font-icon font-icon-check-circle',
            title: '<strong>Heads up!</strong>',
            message: @ViewBag.Message
        },{
            type: 'success'
        });
    });
</code>```

答:
'@ViewBag.Message'

$('#bn-success').on('click', function() {
    $.notify({
        icon: 'font-icon font-icon-check-circle',
        title: 'Heads up!',
        message: '@ViewBag.Message'
    },{
        type: 'success'
    });
});
```

Body:
When i click on save button then success alert message is displayed, but i require only save function successful then only success alert message should be displayed.

In my code i written success alert message in button on click so it is not working properly. how to call id="bn-success" in view bag message on success.

<input type="submit" name="actionType" id="bn-success" value="Save" class="btn btn-rounded btn-inline btn-success" />

Controller:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Domain(Domain domain)
        {
            try
            {
                int refID = Convert.ToInt32(Session["RefID"]);
                if (ModelState.IsValid && refID > 0)
                {
                    userType type = new userType();
                    int id = type.AddDomain(domain, refID);
                    if (id != 0)
                    {
                        ViewBag.Message = "Domain added successfully";
                    }
                }
                return View();
            }
            catch
            {
                return View();
            }

        }

Alert message:

 $('#bn-success').on('click', function() {
        $.notify({
            icon: 'font-icon font-icon-check-circle',
            title: 'Heads up!',
            message: @ViewBag.Message
        },{
            type: 'success'
        });
    });

Body:
'@ViewBag.Message'

$('#bn-success').on('click', function() {
    $.notify({
        icon: 'font-icon font-icon-check-circle',
        title: '<strong>Heads up!</strong>',
        message: '@ViewBag.Message'
    },{
        type: 'success'
    });
});


问:
ListView in Widgets not displaying elements
I have a ListView inside a RelativeLayout inside a Widget.
There is a RemoteViewsFactory that is hooked up to it.
WidgetAdapterService -> The RemoteViewService that is hooked up to the ListView.
NewAppWidget -> The Main widget class.

The widget does not display any elements.

NetworkUtils contains a list of arrays that contain data previously and I've checked that it gives correct results when I set the first element of the array to a TextView.

I'm unsure as to why the ListView itself isn't displaying any elements.

NewAppWidget.java

```<code>          package devapp.com.bakingappudacity;

    import android.app.PendingIntent;
    import android.appwidget.AppWidgetManager;
    import android.appwidget.AppWidgetProvider;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.ListView;
    import android.widget.RemoteViews;
    import android.widget.Toast;

    import devapp.com.bakingappudacity.utils.NetworkUtils;
    import devapp.com.bakingappudacity.utils.WidgetAdapterService;

    /**
    * Implementation of App Widget functionality.
     */
    public class NewAppWidget extends AppWidgetProvider {

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int[] appWidgetId) {

    CharSequence widgetText = context.getString(R.string.appwidget_text);
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    Intent intent = new Intent(context, WidgetAdapterService.class);

    views.setRemoteAdapter(R.id.widget_list_view,intent);

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);

}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) {

            // Create an Intent to launch ExampleActivity
            //Intent intent = new Intent(context, MainActivity.class);
            //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
            //Intent intent = new Intent(context, WidgetAdapterService.class);
            //views.setRemoteAdapter(R.id.widget_list_view,intent);

            Intent intent = new Intent(context, WidgetAdapterService.class);

            views.setRemoteAdapter(R.id.widget_list_view,intent);

            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views);

    }
}

@Override
public void onEnabled(Context context) {
    // Enter relevant functionality for when the first widget is created

    AppWidgetManager appManager = AppWidgetManager.getInstance(context);
    ComponentName thisWidget = new ComponentName(context, NewAppWidget.class);

    updateAppWidget(context,appManager,appManager.getAppWidgetIds(thisWidget));

}

@Override
public void onDisabled(Context context) {
    // Enter relevant functionality for when the last widget is disabled
}
 }
</code>```

WidgetAdapterService.java

```<code>         package devapp.com.bakingappudacity.utils;

      import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import android.widget.Toast;

 import devapp.com.bakingappudacity.R;

public class WidgetAdapterService extends RemoteViewsService{

@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
    return new WidgetAdapter(this.getApplicationContext());
}
 }

class WidgetAdapter implements RemoteViewsService.RemoteViewsFactory {

private Context context;

WidgetAdapter(Context mContext){

    context = mContext;

}

@Override
public void onCreate() {

}

@Override
public void onDataSetChanged() {

}

@Override
public void onDestroy() {

}

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

@Override
public RemoteViews getViewAt(int position) {

    RemoteViews item = new RemoteViews(context.getPackageName(), R.layout.widget_list_item);
    item.setTextViewText(R.id.recipe_list_item_text_view,NetworkUtils.RECIPE_NAMES.get(position));

    return item;
}

@Override
public RemoteViews getLoadingView() {
    return null;
}

@Override
public int getViewTypeCount() {
    return 1;
}

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

@Override
public boolean hasStableIds() {
    return true;
}
    }
</code>```

new_app_widget.xml

```<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09C"
android:padding="@dimen/widget_margin">

<ListView
    android:id="@+id/widget_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>
</code>```

widget_list_item.xml

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

<TextView
    android:id="@+id/widget_list_view_item_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textColor="#000000"
    android:gravity="center"
    tools:text="TextView" />
</code>```

答:
Turns out I was missing the permission android.permission.BIND_REMOTEVIEWS
in the manifest when registering the service. </p>

Body:
I have a ListView inside a RelativeLayout inside a Widget.
There is a RemoteViewsFactory that is hooked up to it.
WidgetAdapterService -> The RemoteViewService that is hooked up to the ListView.
NewAppWidget -> The Main widget class.

The widget does not display any elements.

NetworkUtils contains a list of arrays that contain data previously and I've checked that it gives correct results when I set the first element of the array to a TextView.

I'm unsure as to why the ListView itself isn't displaying any elements.

NewAppWidget.java

          package devapp.com.bakingappudacity;

    import android.app.PendingIntent;
    import android.appwidget.AppWidgetManager;
    import android.appwidget.AppWidgetProvider;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.ListView;
    import android.widget.RemoteViews;
    import android.widget.Toast;

    import devapp.com.bakingappudacity.utils.NetworkUtils;
    import devapp.com.bakingappudacity.utils.WidgetAdapterService;

    /**
    * Implementation of App Widget functionality.
     */
    public class NewAppWidget extends AppWidgetProvider {

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int[] appWidgetId) {

    CharSequence widgetText = context.getString(R.string.appwidget_text);
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);

    Intent intent = new Intent(context, WidgetAdapterService.class);

    views.setRemoteAdapter(R.id.widget_list_view,intent);

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);

}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) {

            // Create an Intent to launch ExampleActivity
            //Intent intent = new Intent(context, MainActivity.class);
            //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
            //Intent intent = new Intent(context, WidgetAdapterService.class);
            //views.setRemoteAdapter(R.id.widget_list_view,intent);

            Intent intent = new Intent(context, WidgetAdapterService.class);

            views.setRemoteAdapter(R.id.widget_list_view,intent);

            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views);

    }
}

@Override
public void onEnabled(Context context) {
    // Enter relevant functionality for when the first widget is created

    AppWidgetManager appManager = AppWidgetManager.getInstance(context);
    ComponentName thisWidget = new ComponentName(context, NewAppWidget.class);

    updateAppWidget(context,appManager,appManager.getAppWidgetIds(thisWidget));

}

@Override
public void onDisabled(Context context) {
    // Enter relevant functionality for when the last widget is disabled
}
 }

WidgetAdapterService.java

         package devapp.com.bakingappudacity.utils;

      import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import android.widget.Toast;

 import devapp.com.bakingappudacity.R;

public class WidgetAdapterService extends RemoteViewsService{

@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
    return new WidgetAdapter(this.getApplicationContext());
}
 }

class WidgetAdapter implements RemoteViewsService.RemoteViewsFactory {

private Context context;

WidgetAdapter(Context mContext){

    context = mContext;

}

@Override
public void onCreate() {

}

@Override
public void onDataSetChanged() {

}

@Override
public void onDestroy() {

}

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

@Override
public RemoteViews getViewAt(int position) {

    RemoteViews item = new RemoteViews(context.getPackageName(), R.layout.widget_list_item);
    item.setTextViewText(R.id.recipe_list_item_text_view,NetworkUtils.RECIPE_NAMES.get(position));

    return item;
}

@Override
public RemoteViews getLoadingView() {
    return null;
}

@Override
public int getViewTypeCount() {
    return 1;
}

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

@Override
public boolean hasStableIds() {
    return true;
}
    }

new_app_widget.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#09C"
android:padding="@dimen/widget_margin">

<ListView
    android:id="@+id/widget_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

widget_list_item.xml

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

<TextView
    android:id="@+id/widget_list_view_item_text_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textColor="#000000"
    android:gravity="center"
    tools:text="TextView" />


问:
error: Error: No resource found that matches the given name: attr 'buttonBarButtonStyle'
I write a theme in styles.xml file like below

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
 <!-- Root styles that vary by API level -->
<style name="FrameworkRoot.Theme" parent="Theme.Sherlock.Light.DarkActionBar">
    <!-- API 11+ (compatibility) -->
    <item name="buttonBarStyle">@style/Compat.ButtonBar</item>
    <item name="buttonBarButtonStyle">@style/Compat.ButtonBarButton</item>
    <item name="indeterminateProgressStyle">@style/Compat.IndeterminateProgress</item>
    <!-- API 14+ (compatibility) -->
    <item name="listPreferredItemPaddingLeft">@dimen/compat_list_preferred_item_padding_left</item>
    <item name="listPreferredItemPaddingRight">@dimen/compat_list_preferred_item_padding_right</item>
    <item name="listPreferredItemHeightSmall">@dimen/compat_list_preferred_item_height_small</item>
</style>
</code>```

but get the error: Error: No resource found that matches the given name: attr 'buttonBarStyle'.

I get the code from the google io2012. Both mine and its'  all base

```<code>    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />
</code>```

I can compile the google io2012's source code but not mine. so strange.
is anybody know why? or have the same question?

答:
I was getting same error....deleted the folders at

C:\Users\.android\build-cache\Hash Number of Folders E.g. 4eaccf0d162ec009b115c7e0ff4f542f8d2a663b\

and it worked like a charm....

Body:
I write a theme in styles.xml file like below

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

but get the error: Error: No resource found that matches the given name: attr 'buttonBarStyle'.

I get the code from the google io2012. Both mine and its'  all base

    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

I can compile the google io2012's source code but not mine. so strange.
is anybody know why? or have the same question?


问:
Connecting to a Database with Java
I'm very confused about how to connect my Java application to a database, any database. I'm not sure where to start. Could anybody provide for me a simple example that might help me along?</p>

答: Aside of jdbc, You can connect using ibatis (or mybatis) and Hibernate. Ibatis is quite simple (but sometimes tricky to configure) but it do the trick.ibatis example</p>

ContentLicense: CC BY-SA 2.5

Title: Connecting to a Database with Java


问:
Getting cart products link and image in shortcode in WooCommerce
I have this code which lists the products added to cart via shortcode. However, these are only the titles. I need help in getting the products URL so the titles are hyperlinks to each product. Also, I would like to display the image of the product in front of the title. Thanks for your help and your time.

Code I currently have:

```<code>// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
 foreach( $cart as $cart_item ){
$product = wc_get_product( $cart_item['product_id'] );
   $cart_items .= '– '.$cart_item['data']->get_title().'<br>';
 }
 return $cart_items;
}
add_shortcode( 'bag_products', 'get_cart_products' );
</code>```

答:
This will output a list you can then style as you like.  The function get_image() returns the 'shop_thumbnail' size by default.</p>

```<code>function get_cart_products() {

    $bag_products = '<ul>';

    foreach( WC()->cart->get_cart() as $cart_item ){
        $product = wc_get_product( $cart_item['product_id'] );
        $bag_products .= '<li>'. $product->get_image() .'<a href="' . $product->get_permalink() . '">' . $product->get_title() . '</a></li>';
    }

    $bag_products .= '</ul>';

    return $bag_products;
}

add_shortcode( 'bag_products', 'get_cart_products' );
</code>```

Body:
I have this code which lists the products added to cart via shortcode. However, these are only the titles. I need help in getting the products URL so the titles are hyperlinks to each product. Also, I would like to display the image of the product in front of the title. Thanks for your help and your time.

Code I currently have:

// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
 foreach( $cart as $cart_item ){
$product = wc_get_product( $cart_item['product_id'] );
   $cart_items .= '– '.$cart_item['data']->get_title().'
';
 }
 return $cart_items;
}
add_shortcode( 'bag_products', 'get_cart_products' );

Body:
This will output a list you can then style as you like.  The function get_image() returns the 'shop_thumbnail' size by default.

function get_cart_products() {

    $bag_products = '<ul>';

    foreach( WC()->cart->get_cart() as $cart_item ){
        $product = wc_get_product( $cart_item['product_id'] );
        $bag_products .= '<li>'. $product->get_image() .'<a href="' . $product->get_permalink() . '">' . $product->get_title() . '</a></li>';
    }

    $bag_products .= '</ul>';

    return $bag_products;
}

add_shortcode( 'bag_products', 'get_cart_products' );


问:
Arbitrary characters for forward-word/backward-word in Emacs
How to add an arbitrary character (hyphen, for example) to forward/backward-word functionality, so Emacs would handle words like "k-vector" as a single word. The same question about double-click on the word.</p>

答:
Add following to your .emacs file to make hyphen included in words for every major mode:

```<code>(add-hook 'after-change-major-mode-hook
  (lambda ()
    (modify-syntax-entry ?- "w")))
</code>```

Body:
Add following to your .emacs file to make hyphen included in words for every major mode:

(add-hook 'after-change-major-mode-hook
  (lambda ()
    (modify-syntax-entry ?- "w")))


问:
AdMob Interstitial stopped working
The Interstitial ad was working properly and after two days of testing it stopped working. I have the error: Possible Unhandled Promise Rejection (id: 0): Error: Request Error: No ad to show from all configured ad networks. This error is only for the Interstitial ad. I have AdMobBanner but it's working perfectly fine. For both I use the test ids from https://developers.google.com/admob/ios/test-ads. I have tried to create different app but it's the same. Also have tried with real ad but again not working. It's not working on both platform - iOS & Android. My AdMob account is not banned or showing any warning messages. I am using https://github.com/sbugert/react-native-admob with the following code:

```<code>AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/4411468910');
AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]);
AdMobInterstitial.requestAd().then(() => AdMobInterstitial.showAd());
</code>```

As I said it was working for two days.

答:
```<code>Try,
if (AdMobInterstitial.isLoaded() || AdMobInterstitial.isLoading()) {
  AdMobInterstitial.showAd()
}
</code>```

Add Above line add and check.

remove AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]); this line and check.

check both scenario.

Title: AdMob Interstitial stopped working

Body:
The Interstitial ad was working properly and after two days of testing it stopped working. I have the error: Possible Unhandled Promise Rejection (id: 0): Error: Request Error: No ad to show from all configured ad networks. This error is only for the Interstitial ad. I have AdMobBanner but it's working perfectly fine. For both I use the test ids from https://developers.google.com/admob/ios/test-ads. I have tried to create different app but it's the same. Also have tried with real ad but again not working. It's not working on both platform - iOS & Android. My AdMob account is not banned or showing any warning messages. I am using https://github.com/sbugert/react-native-admob with the following code:

AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/4411468910');
AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]);
AdMobInterstitial.requestAd().then(() => AdMobInterstitial.showAd());

As I said it was working for two days.

Body:
Try,
if (AdMobInterstitial.isLoaded() || AdMobInterstitial.isLoading()) {
  AdMobInterstitial.showAd()
}

Add Above line add and check.

remove AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]); this line and check.

check both scenario.


问:
Failed to insert multiple tags on Laravel
I want to insert a Post record with multiple tags so here's my code in Post@store:

```<code>$post = Post::create(array(
            'title' => $request->title,
            'body' => $request->body,
            'user_id' => Auth::id(),
        ));

        if($post && $request->tags)
        {
            $tagNames = explode(',', $request->tags);
            $tagIds = [];
            foreach($tagNames as $tagName)
            {
                $tag = Tag::firstOrCreate(['name'=>$tagName]);
                if($tag)
                {
                    $tagIds[] = $tag->id;
                }
            }

            $post->tags()->attach($tagIds);
        }
</code>```

but it give me an errors "Call to a member function attach() on null". when i'm checked in mysql the tags is already in there but i can't find any entry on my post_tag tables. here's my post model:

```<code>class Post extends Model
{
    protected $fillable = ['user_id','title','slug','body','tags','category_id','featured'];

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function tags()
    {
        $this->hasMany('App\Tag');
    }
}
</code>```

答:
You need to return the call the hasMany in your Post model.

```<code>public function tags()
{
    return $this->hasMany('App\Tag');
}
</code>```

Update

You should use belongsToMany not hasMany.

Body:
I want to insert a Post record with multiple tags so here's my code in Post@store:

$post = Post::create(array(
            'title' => $request->title,
            'body' => $request->body,
            'user_id' => Auth::id(),
        ));

        if($post && $request->tags)
        {
            $tagNames = explode(',', $request->tags);
            $tagIds = [];
            foreach($tagNames as $tagName)
            {
                $tag = Tag::firstOrCreate(['name'=>$tagName]);
                if($tag)
                {
                    $tagIds[] = $tag->id;
                }
            }

            $post->tags()->attach($tagIds);
        }

but it give me an errors "Call to a member function attach() on null". when i'm checked in mysql the tags is already in there but i can't find any entry on my post_tag tables. here's my post model:

class Post extends Model
{
    protected $fillable = ['user_id','title','slug','body','tags','category_id','featured'];

    public function category()
    {
        return $this->belongsTo('App\Category');
    }

    public function tags()
    {
        $this->hasMany('App\Tag');
    }
}

Body:
You need to return the call the hasMany in your Post model.

public function tags()
{
    return $this->hasMany('App\Tag');
}

Update

You should use belongsToMany not hasMany.


问:
Android SDK location should not contain whitespace, as this cause problems with NDK tools
Recently I have installed the last version of Android Studio (Android Studio 2.1), keeping the old 1.2 version  previously installed. Now i have Android Studio 2.1 and Android Studio 1.2. In Android Studio 1.2 when I click on SDK Manager it works properly, but in Andorid Studio 2.1 this problem appears:

how can I fix keeping the two versions of Android studio? Thanks

答:
There is another way:

Open up CMD (as Administrator)

Type: mklink /J C:\Program-Files "C:\Program Files" (Or in my case mklink /J C:\Program-Files-(x86) "C:\Program Files (x86)")

Hit enter

Magic happens! (Check your C drive)

Now you can point to C:\Program-Files (C:\Program-Files-(x86)).


问:
How to share a photo correctly on php and URL solution - Webproject
I have a question about a web project I'm on it.

The situation:
There is a log-in system -> after log-in there is a lot of photos.

1) I enter with my credentials -> login.php to index.php

2) I see my profile and then I want to share it with twitter(for example..).

3) The thing I share it is the URL which is "page.com/index.php#&album=1&id=1"

The problem is the URL, if I share will be useless because if the other user have an account, will show his photo and not mine.

I try to find a solution, I do not know how the other sites do to share photos without this problem.

Hope u can help me and sorry if my english not the best.

答:
I would do this by generating a UUID for each individual photo stored alongside the photos, and using that in the URL instead of the two IDs, so your URLs would look something like:

```<code>http://example.com/photos/123e4567-e89b-12d3-a456-426655440000
</code>```

You can then share this URL to anyone, and add the logic in to the server to decide whether or not the photo should be visible to whoever is requesting it.

If you want a more memorable or easy to type UUID, there are lots of libraries that will create them for you in different formats.

The main benefit of this is simplicity, you just have that one UUID for that one photo, and it doesn't matter how your design changes (for example, if you remove albums), you have a very good chance of being able to keep the URLs the same, or at least, to continue supporting the original URL if you do need to change the format on the future.

Another big benefit is that whatever you use as a UUID will (should) be hard to guess, so you remove a potential route in for an attacker, who otherwise might be able to iterate over IDs, and have confidence that he's created a genuine URL.

Body:
I would do this by generating a UUID for each individual photo stored alongside the photos, and using that in the URL instead of the two IDs, so your URLs would look something like:

http://example.com/photos/123e4567-e89b-12d3-a456-426655440000

You can then share this URL to anyone, and add the logic in to the server to decide whether or not the photo should be visible to whoever is requesting it.

If you want a more memorable or easy to type UUID, there are lots of libraries that will create them for you in different formats.

The main benefit of this is simplicity, you just have that one UUID for that one photo, and it doesn't matter how your design changes (for example, if you remove albums), you have a very good chance of being able to keep the URLs the same, or at least, to continue supporting the original URL if you do need to change the format on the future.

Another big benefit is that whatever you use as a UUID will (should) be hard to guess, so you remove a potential route in for an attacker, who otherwise might be able to iterate over IDs, and have confidence that he's created a genuine URL.


问:
How to change map style in mapbox without changing the geoJson inserted
I have tried changing map styles like streets to satellite, dark, bright etc at runtime using radio boxes. But when i load a geojson file to the map, it is showing only on the current map style selected. When i change the map style, the geoJson file is gone. Is there any way that, i could retain the geoJson file in all map styles, even when i change the styles?

var map;
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FkaXF1ZSIsImEiOiJjajlrc3V0bjkxaGxlMzNzMjBwdmZ3NmF1In0.KOe_ASpXmNUF_TmN6h2CHw';
map = new mapboxgl.Map({
  container: 'map', // container element id
  style: 'mapbox://styles/mapbox/light-v9',
  center: [90.899, 26.372], // initial map center in [lon, lat]
  zoom: 7
});

var layerList = document.getElementById('menu');
var inputs = layerList.getElementsByTagName('input');

function switchLayer(layer) {
  var layerId = layer.target.id;
  map.setStyle('mapbox://styles/mapbox/' + layerId + '-v9');
}

for (var i = 0; i < inputs.length; i++) {
  inputs[i].onclick = switchLayer;
}

function loadRails() {
  mapboxgl.accessToken = 'pk.eyJ1Ijoic2FkaXF1ZSIsImEiOiJjajlrc3V0bjkxaGxlMzNzMjBwdmZ3NmF1In0.KOe_ASpXmNUF_TmN6h2CHw';

  map.addLayer({
    id: 'collisions',
    type: 'line',
    source: {
      type: 'geojson',
      data: 'testRails.geojson' // replace this with the url of your own geojson
    }
  }, 'admin-2-boundaries-dispute');

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <title>Change a map's style</title>
  <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.1/mapbox-gl.js'></script>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.1/mapbox-gl.css' rel='stylesheet' />
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>
</head>

<body>

  <br><div id='map'></div><br>
  <button style="position:relative;" onclick="loadRails()">load geoJson</button>
  <div id='menu' style="position:relative;">
    <input id='basic' type='radio' name='rtoggle' value='basic' checked='checked'>
    <label for='basic'>basic</label>
    <input id='streets' type='radio' name='rtoggle' value='streets'>
    <label for='streets'>streets</label>
    <input id='bright' type='radio' name='rtoggle' value='bright'>
    <label for='bright'>bright</label>
    <input id='light' type='radio' name='rtoggle' value='light'>
    <label for='light'>light</label>
    <input id='dark' type='radio' name='rtoggle' value='dark'>
    <label for='dark'>dark</label>
    <input id='satellite' type='radio' name='rtoggle' value='satellite'>
    <label for='satellite'>satellite</label>
  </div>

</body>

</html></code>```

答:
This is will documented over here and here. It seems to be working as designed.

I think, although it sounds counter-intuitive, it would be better to redraw. I quote the poster here

I've since removed class level style layers and sources variables and am reloading data on every style change in mapViewDidFinishLoadingMap. While inconvenient, at least it's stable this way. Sorry for the noise. Looking forward to this feature.

Body:
I have tried changing map styles like streets to satellite, dark, bright etc at runtime using radio boxes. But when i load a geojson file to the map, it is showing only on the current map style selected. When i change the map style, the geoJson file is gone. Is there any way that, i could retain the geoJson file in all map styles, even when i change the styles?

var map;
mapboxgl.accessToken = 'pk.eyJ1Ijoic2FkaXF1ZSIsImEiOiJjajlrc3V0bjkxaGxlMzNzMjBwdmZ3NmF1In0.KOe_ASpXmNUF_TmN6h2CHw';
map = new mapboxgl.Map({
  container: 'map', // container element id
  style: 'mapbox://styles/mapbox/light-v9',
  center: [90.899, 26.372], // initial map center in [lon, lat]
  zoom: 7
});

var layerList = document.getElementById('menu');
var inputs = layerList.getElementsByTagName('input');

function switchLayer(layer) {
  var layerId = layer.target.id;
  map.setStyle('mapbox://styles/mapbox/' + layerId + '-v9');
}

for (var i = 0; i < inputs.length; i++) {
  inputs[i].onclick = switchLayer;
}

function loadRails() {
  mapboxgl.accessToken = 'pk.eyJ1Ijoic2FkaXF1ZSIsImEiOiJjajlrc3V0bjkxaGxlMzNzMjBwdmZ3NmF1In0.KOe_ASpXmNUF_TmN6h2CHw';

  map.addLayer({
    id: 'collisions',
    type: 'line',
    source: {
      type: 'geojson',
      data: 'testRails.geojson' // replace this with the url of your own geojson
    }
  }, 'admin-2-boundaries-dispute');

}

  <title>Change a map's style</title>

  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.42.1/mapbox-gl.css' rel='stylesheet' />

  <button style="position:relative;" onclick="loadRails()">load geoJson</button>

    <input id='basic' type='radio' name='rtoggle' value='basic' checked='checked'>
    basic
    <input id='streets' type='radio' name='rtoggle' value='streets'>
    streets
    <input id='bright' type='radio' name='rtoggle' value='bright'>
    bright
    <input id='light' type='radio' name='rtoggle' value='light'>
    light
    <input id='dark' type='radio' name='rtoggle' value='dark'>
    dark
    <input id='satellite' type='radio' name='rtoggle' value='satellite'>
    satellite


问:
File upload going into POST instead of FILE
I am trying to upload a file onto a server. Whenever I submit, the php global array $_FILES is empty. My file keeps going into $_POST.

```<code>        <form action="process.php" method="POST">
            <div class="form-group"></div>
            <div class="form-group">
                <input type="file" name="uploaded_file">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-danger">Upload</button>
            </div>
        </form>
</code>```

process.php

```<code><?php
var_dump($_FILES['uploaded_file']);
var_dump($_POST['uploaded_file']);
</code>```

答:
You should use enctype="multipart/form-data" like this

```<code><form action="process.php" method="POST" enctype="multipart/form-data">
            <div class="form-group"></div>
            <div class="form-group">
                <input type="file" name="uploaded_file">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-danger">Upload</button>
            </div>
</form>
</code>```

Body:
I am trying to upload a file onto a server. Whenever I submit, the php global array $_FILES is empty. My file keeps going into $_POST.

        <form action="process.php" method="POST">

                <input type="file" name="uploaded_file">

                <button type="submit" class="btn btn-danger">Upload</button>

        </form>

process.php

<?php
var_dump($_FILES['uploaded_file']);
var_dump($_POST['uploaded_file']);

Body:
You should use enctype="multipart/form-data" like this

<form action="process.php" method="POST" enctype="multipart/form-data">
            <div class="form-group"></div>
            <div class="form-group">
                <input type="file" name="uploaded_file">
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-danger">Upload</button>
            </div>
</form>


答:
You'll have to instantiate the map again with the new style.</p>

```<code>// Initially
var map = new mapboxgl.Map({
  // Whatever options
  style: 'some-style'
});

// On style change, remove map and re-initialize
map.remove();
map = new mapboxgl.Map({
  // Options,
  style: 'some-other-style'
});
</code>```

Title: How to change map style in mapbox without changing the geoJson inserted

Body:
You'll have to instantiate the map again with the new style.

// Initially
var map = new mapboxgl.Map({
  // Whatever options
  style: 'some-style'
});

// On style change, remove map and re-initialize
map.remove();
map = new mapboxgl.Map({
  // Options,
  style: 'some-other-style'
});


问:
pygame mouse event not registered properly
Here is my code, very simple:

```<code>import pygame

def run_game():

    pygame.init()

    screen = pygame.display.set_mode((1200,800))

    while True:

        screen.fill((55,55,55))

        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                print(pygame.mouse.get_pos())

            elif event.type == pygame.MOUSEMOTION:
                print(pygame.mouse.get_pos())

        pygame.display.flip()

run_game()
</code>```

When I click on one position, it shows the (x,y) coordinate. When I click on position one, it shows (x1,y1), then SOMETIMES after I change my mouse to position 2, and click on it, it still shows (x1,y1) instead of the correct coordinate. When this happens, if I don't move my mouse and keep click on position 2, it will keep showing (x1,y1) until I change mouse to somewhere else. Can someone explains to me why is that happened? Thanks.

答: You can add a print statement before mouse motion and mouse down so that you can easily differentiate between both.</p>

Body:
Here is my code, very simple:

import pygame

def run_game():

    pygame.init()

    screen = pygame.display.set_mode((1200,800))

    while True:

        screen.fill((55,55,55))

        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                print(pygame.mouse.get_pos())

            elif event.type == pygame.MOUSEMOTION:
                print(pygame.mouse.get_pos())

        pygame.display.flip()

run_game()

When I click on one position, it shows the (x,y) coordinate. When I click on position one, it shows (x1,y1), then SOMETIMES after I change my mouse to position 2, and click on it, it still shows (x1,y1) instead of the correct coordinate. When this happens, if I don't move my mouse and keep click on position 2, it will keep showing (x1,y1) until I change mouse to somewhere else. Can someone explains to me why is that happened? Thanks.


问:
Sent mail does not show mail trail with custom outlook message form
I have created a Custom Outlook(Outlook 2010) form using default Mail message form, here i have separate Compose and Read page. The Compose page has TO, CC, Subject, Message and additional custom UI elements; Status(a dropdown box) and Ticket(Text Box) and Read page has Labels From, CC, Subject, Message, Status and Ticket. These custom elements are bind to user defined fields rStatus and rticket.

Assigned custom form in Actions tab for Reply, Reply to ALL, Forward and published in my own Inbox and sent folder

On Running following case

Open Custom form in New Items drop down

Set values in TO(with my own email id), Subject, Status, Ticket and some text in Message Body including the signature.

Send this custom message form

Open received message in Inbox, i can see from, subject, status, ticket and message body as sent in point 2 & 3.

Reply this message by changing Status, Ticket and append some more text in the message body in the top.

Send this custom message form

Open received message, here i can see from, subject, updated status and Ticket, while the Message body is empty.

If I open the message in sent folder after pt 6, the message body is empty there as well.

My form has no scripts and send form def with item is unchecked

Thanks

Kiran

答: It was a bug that was solved in latest patches for microsoft, after updating I can see the message body in step 7 and 8.</p>


问:
How can I retrieve all users from firebase to a fragment?
I have created a Recycler view in my fragment_add_friends.xml like below

```<code><android.support.v7.widget.RecyclerView
android:id="@+id/all_user_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</code>```

and I created all_user_display_layout.xml file for display each user like below

```<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="wrap_content"
    android:orientation="vertical">

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

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/all_user_image">

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

            <TextView
                android:id="@+id/all_user_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="full name"/>

            <TextView
                android:id="@+id/all_user_status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="user status"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

In my AddFriendsFragment.java I got the recycler view like below in my on create view method

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_add_friends, container, false);

        all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
        all_user_list.setHasFixedSize(true);
        all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));

        return v;
    }
</code>```

and I have created a helper class that have Strings name, status,
  image and there getters setters and constructor and empty construcor because I have to retrieve those data and xml file those things in is all_user_display_layout.xml

and I got the database reference like below

```<code>databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
</code>```

and I create the onViewCreated method like below

```<code>@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }
</code>```

after that what are the things that I have to do to get data from
  fireabse to recycler view

please help me im new to these stuff

答:
Remove these lines from onCreateView

```<code> all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
 all_user_list.setHasFixedSize(true);
 all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));
</code>```

Add the following code in onViewCreated

```<code>@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    FirebaseRecyclerViewAdapter<<Your-Helper-Class>, ViewHolder> adapter;
     ref = new Firebase("https://<yourapp>.firebaseio.com");

     RecyclerView recycler = (RecyclerView) findViewById(R.id.all_user_list);
     recycler.setHasFixedSize(true);
     recycler.setLayoutManager(new LinearLayoutManager(getActivity()));

     adapter = new FirebaseRecyclerViewAdapter<<Your-Helper-Class>, ViewHolder>(<Your-Helper-Class>.class, android.R.layout.all_user_display_layout.xml, ViewHolder.class, mRef) {
         public void populateViewHolder(ViewHolder viewHolder, <Your-Helper-Class> helper) {
            Picasso.with(context).load(helper.getImage()).into(viewHolder.image);
             viewHolder.name.setText(helper.getName());
             viewHolder.status.setText(helper.getStatus());
         }
     };
     recycler.setAdapter(mAdapter);
    }

    private static class ViewHolder extends RecyclerView.ViewHolder {
        CircleImageView image;
         TextView name;
         TextView status;

         public ChatMessageViewHolder(View itemView) {
             super(itemView);
             image = (TextView)itemView.findViewById(android.R.id.all_user_image);
             name = (TextView)itemView.findViewById(android.R.id.all_user_name);
             status = (TextView) itemView.findViewById(android.R.id.all_user_status);
         }
     }
</code>```

Also use Picasso for loading image in imageview. Add these lines in your build.gradle.

compile 'com.squareup.picasso:picasso:2.5.2'

Body:
I have created a Recycler view in my fragment_add_friends.xml like below

<android.support.v7.widget.RecyclerView
android:id="@+id/all_user_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />

and I created all_user_display_layout.xml file for display each user like below

<?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="wrap_content"
    android:orientation="vertical">

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

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/all_user_image">

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

            <TextView
                android:id="@+id/all_user_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="full name"/>

            <TextView
                android:id="@+id/all_user_status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="user status"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

In my AddFriendsFragment.java I got the recycler view like below in my on create view method

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

        all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
        all_user_list.setHasFixedSize(true);
        all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));

        return v;
    }

and I have created a helper class that have Strings name, status,
  image and there getters setters and constructor and empty construcor because I have to retrieve those data and xml file those things in is all_user_display_layout.xml

and I got the database reference like below

databaseReference = FirebaseDatabase.getInstance().getReference().child("users");

and I create the onViewCreated method like below

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

after that what are the things that I have to do to get data from
  fireabse to recycler view

please help me im new to these stuff

Body:
Remove these lines from onCreateView

 all_user_list = (RecyclerView) v.findViewById(R.id.all_user_list);
 all_user_list.setHasFixedSize(true);
 all_user_list.setLayoutManager(new LinearLayoutManager(getActivity()));

Add the following code in onViewCreated

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    FirebaseRecyclerViewAdapter<<Your-Helper-Class>, ViewHolder> adapter;
     ref = new Firebase("https://<yourapp>.firebaseio.com");

     RecyclerView recycler = (RecyclerView) findViewById(R.id.all_user_list);
     recycler.setHasFixedSize(true);
     recycler.setLayoutManager(new LinearLayoutManager(getActivity()));

     adapter = new FirebaseRecyclerViewAdapter<<Your-Helper-Class>, ViewHolder>(<Your-Helper-Class>.class, android.R.layout.all_user_display_layout.xml, ViewHolder.class, mRef) {
         public void populateViewHolder(ViewHolder viewHolder, <Your-Helper-Class> helper) {
            Picasso.with(context).load(helper.getImage()).into(viewHolder.image);
             viewHolder.name.setText(helper.getName());
             viewHolder.status.setText(helper.getStatus());
         }
     };
     recycler.setAdapter(mAdapter);
    }

    private static class ViewHolder extends RecyclerView.ViewHolder {
        CircleImageView image;
         TextView name;
         TextView status;

         public ChatMessageViewHolder(View itemView) {
             super(itemView);
             image = (TextView)itemView.findViewById(android.R.id.all_user_image);
             name = (TextView)itemView.findViewById(android.R.id.all_user_name);
             status = (TextView) itemView.findViewById(android.R.id.all_user_status);
         }
     }

Also use Picasso for loading image in imageview. Add these lines in your build.gradle.

compile 'com.squareup.picasso:picasso:2.5.2'


答:
add enctype="multipart/form-data" into html
like:

```<code><!DOCTYPE html>
 <html>
 <body>

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</code>```

Title: File upload going into POST instead of FILE

Body:
add enctype="multipart/form-data" into html
like:

<!DOCTYPE html>
 <html>
 <body>

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>


问:
Put or patch for new update action Rails
I want to add a new update(new_update) action in my user model of rails which will update a single column in the model. which rest api method  I should use in routes file. Should I use put or patch or both. </p>

```<code>resources: users do
  member do
    put 'new_update'
    patch 'new_update'
end
</code>```

答:
If you want to match 100% with the HTTP verb definition.

PUT is supposed to overwrite your targeted resource entirely with the content in the request(all field non present in the request should be set to removed/nullified).

PATCH is supposed to only modify the fields sent in the request.

That being said, most of the time people don't make the difference and use either of them (a lot of people don't even know that there is a PATCH verb) is use PUT with the same behavior as PATCH (since the use case for PUT is quite rare on imo).

Body:
I want to add a new update(new_update) action in my user model of rails which will update a single column in the model. which rest api method  I should use in routes file. Should I use put or patch or both.

resources: users do
  member do
    put 'new_update'
    patch 'new_update'
end


问:
Adding controls (trackbars, multiline textboxes and labels) to a form under different DPIs - C#
My application loads information from a file which then creates x amount of controls on y amounts of tabpages in a form.

My problem is that when the user has a different DPI to the standard Windows 96, the controls added overlap each other. The initial controls on the form are fine.

How can I set the controls to be modified to the 96 DPI instead of whatever the users machine is running at?

If this is very difficult, is there a way to see what the users DPI is? I can then throw a warning saying that you should use 96DPI etc etc.

Thank you for any help or advise you can give me!

答:
Just to answer my own question I wrote this and put it in my Form load event:</p>

```<code>        Graphics formGraphics = this.CreateGraphics();
        if ((formGraphics.DpiX != 96) || (formGraphics.DpiY != 96))
        {
            MessageBox.Show("You are attempting to run this application in an unknown DPI. This application has been designed for Normal size (96 DPI), you may experience some display issues if you continue to use your current settings. Please change your Display settings back to normal size through your control panel to ensure you don't experience any problems. Thank you.",
            "Warning",
            MessageBoxButtons.OK,
            MessageBoxIcon.Exclamation,
            MessageBoxDefaultButton.Button1);
        }
</code>```

Body:
Just to answer my own question I wrote this and put it in my Form load event:

        Graphics formGraphics = this.CreateGraphics();
        if ((formGraphics.DpiX != 96) || (formGraphics.DpiY != 96))
        {
            MessageBox.Show("You are attempting to run this application in an unknown DPI. This application has been designed for Normal size (96 DPI), you may experience some display issues if you continue to use your current settings. Please change your Display settings back to normal size through your control panel to ensure you don't experience any problems. Thank you.",
            "Warning",
            MessageBoxButtons.OK,
            MessageBoxIcon.Exclamation,
            MessageBoxDefaultButton.Button1);
        }


问:
ES6 features Destructuring
by using es6 feature that is destructing , in objects if we made some methods so we can extract that methods also , as property we can , as i try by doing this , please have a look on above code

let person = {
  name: "Ravi",
  favGames: ["cricket", "Badminton", "Tennis"],
  displayFavGames() {
    this.favGames.forEach(game => {
      console.log("My gave game " + game)
    })
  }
}
person.displayFavGames();

let displayData = ({
  name,
  favGames,
  displayFavGames
}) => {
  return `My name is ${name} and my cofavourite games is
                    ${displayFavGames}`;
}

console.log(displayData(person));```

答:
displayFavGames is a function, so you need to call it.

But since it's a property of the object and uses this, you need to call it using property notation: object.displayFavGames(). You can do that if you destructure the argument, because you don't have a variable that refers to the original object. You can get the argument as a single variable, then use destructuring when initializing local variables.

And if you want to substitute the result of that function, it needs to return a string, not use console.log().

let person = {
  name: "Ravi",
  favGames: ["cricket", "Badminton", "Tennis"],
  displayFavGames() {
    return this.favGames.join("\n                    ");
  }
}
person.displayFavGames();

let displayData = (p) => {
  let {
    name,
    favGames,
    displayFavGames
  } = p;
  return `My name is ${name} and my cofavourite games are
                    ${p.displayFavGames()}`;
}

console.log(displayData(person));```

Title: ES6 features Destructuring


问:
SSO and IdentityServer with services that expect SAML and JWT
I'm using IdentityServer4 with OpenID Connect and OAuth2.

I need to enable SSO with some legacy services that support SAML.

Can someone explain (or point me to a good article) explaining how this could be achieved?

Would I need to request a SAML token from IdentityServer for my JWT token that I can pass to the legacy service? Or could I embed the SAML token into the JWT ID token which can then be extracted and passed to the legacy service?

答: You need a SAML2P plugin for IdentityServer4, there's an experimental version at https://leastprivilege.com/2017/10/13/saml2p-identity-provider-support-for-identityserver4/</p>


问:
Adding navmeshAgent causes game to freeze
I have a script which spawns enemies after a delay of time on a terrain that I have created. It works for the first three enemies created but when it adds the navmeshagent the fourth time it freezes the entire game.

```<code>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomSpawn : MonoBehaviour {
public List<GameObject> Spawnables;
public Terrain spawnLand;
public float spawnWait = 1f;
public int numPer = 1;
public bool enableSpawning =true;
float minx,maxx,minz,maxz,waiter = 1f;

// Use this for initialization
void Start () {
    minx = spawnLand.transform.position.x+2;
    maxx = spawnLand.terrainData.size.x + minx-4;
    minz = spawnLand.transform.position.z+2;
    maxz = spawnLand.terrainData.size.z + minz-4;
}
void Update(){
    waiter -= Time.deltaTime;
    if (waiter<=0) {
        waiter = spawnWait;
        if (enableSpawning) {
            Spawn ();
        }
    }
}
void Spawn()
{

    for (int i = 0; i < numPer; i++) {

        Vector3 loc = new Vector3 (Random.Range (minx, maxx), 0, Random.Range (minz, maxz));

        GameObject go = (GameObject)Instantiate (Spawnables[Random.Range (0,Spawnables.Count)],new Vector3(0,0,0),new Quaternion(0,0,0,0));

        NavMeshHit closestHit;
        if( NavMesh.SamplePosition( loc, out closestHit, 500, 1 ) ){
            go.transform.position = closestHit.position;
            go.AddComponent<NavMeshAgent>();
            //TODO
        }
        else{
            Debug.Log("...");
        }
    }
}
}
</code>```

I put it on a time delay using waiter and spawnWait. It seems to always freeze and crash right after creating the fourth object and adding the navmeshagent to it. I have found out that it is probably from a rebake of the scene. Is there any way to stop it from freezeing or rebaking. Or is there a better way to spawn enemies in a set location with navmeshagents?

答: For me your script is working just fine. Try it with just one spawnable object (may be you have null object or going from array bounds). Debug it step by step. Try to put Spawn method into Coroutine process (docs.unity3d.com/Manual/Coroutines.html).</p>

Body:
I have a script which spawns enemies after a delay of time on a terrain that I have created. It works for the first three enemies created but when it adds the navmeshagent the fourth time it freezes the entire game.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomSpawn : MonoBehaviour {
public List<GameObject> Spawnables;
public Terrain spawnLand;
public float spawnWait = 1f;
public int numPer = 1;
public bool enableSpawning =true;
float minx,maxx,minz,maxz,waiter = 1f;

// Use this for initialization
void Start () {
    minx = spawnLand.transform.position.x+2;
    maxx = spawnLand.terrainData.size.x + minx-4;
    minz = spawnLand.transform.position.z+2;
    maxz = spawnLand.terrainData.size.z + minz-4;
}
void Update(){
    waiter -= Time.deltaTime;
    if (waiter<=0) {
        waiter = spawnWait;
        if (enableSpawning) {
            Spawn ();
        }
    }
}
void Spawn()
{

    for (int i = 0; i < numPer; i++) {

        Vector3 loc = new Vector3 (Random.Range (minx, maxx), 0, Random.Range (minz, maxz));

        GameObject go = (GameObject)Instantiate (Spawnables[Random.Range (0,Spawnables.Count)],new Vector3(0,0,0),new Quaternion(0,0,0,0));

        NavMeshHit closestHit;
        if( NavMesh.SamplePosition( loc, out closestHit, 500, 1 ) ){
            go.transform.position = closestHit.position;
            go.AddComponent<NavMeshAgent>();
            //TODO
        }
        else{
            Debug.Log("...");
        }
    }
}
}

I put it on a time delay using waiter and spawnWait. It seems to always freeze and crash right after creating the fourth object and adding the navmeshagent to it. I have found out that it is probably from a rebake of the scene. Is there any way to stop it from freezeing or rebaking. Or is there a better way to spawn enemies in a set location with navmeshagents?


问:
How to send Ajax data in controller
I want to recommend the visitors the hotels near by him based on his current location. My problem is how to get not login user latitude and longitude so that i can recommend him nearby hotel.

home.blade.php

```<code>    <script>
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            console.log(position);
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;

            $.ajax({
                url:'http://localhost:8000/getgeo',
                type:'get',
                data:{latitude:lat,longitude:lng},

//even when  i set some value here data:{latitude:1222323}, i did not get `1222323` in controller

                success:function(data)
                {
                    alert('success');
                }

            });
        });
    }

    </script>
</code>```

I got null in controller
controller:

```<code>public function geo()
{
    return view('home');

}
public function getCoordinate(Request $request)
{
    return $request->latitude;
}
</code>```

Here i am getting latitude and longitude at console in home.blade.php page .But now got in controller

Route:

```<code>Route::get('/geo', 'ProductController@geo');

Route::get('/getgeo', 'ProductController@getCoordinate');
</code>```

答:
Change following points:-</p>

```<code>change ajax url : url:'/getgeo'
And function :-
public function getCoordinate(Request $request)
 {
  if($request->ajax()){
    $data = $request->all();
    echo "```"; print_r($data); // print all data here
  }

 }
 Try to change Route:-
 Route::any('/getgeo', 'ProductController@getCoordinate');
</code>```

Title: How to send Ajax data in controller

Body:
I want to recommend the visitors the hotels near by him based on his current location. My problem is how to get not login user latitude and longitude so that i can recommend him nearby hotel.

home.blade.php

I got null in controller
controller:

public function geo()
{
    return view('home');

}
public function getCoordinate(Request $request)
{
    return $request->latitude;
}

Here i am getting latitude and longitude at console in home.blade.php page .But now got in controller

Route:

Route::get('/geo', 'ProductController@geo');

Route::get('/getgeo', 'ProductController@getCoordinate');

Body:
Change following points:-

change ajax url : url:'/getgeo'
And function :-
public function getCoordinate(Request $request)
 {
  if($request->ajax()){
    $data = $request->all();
    echo "<pre>"; print_r($data); // print all data here
  }

 }
 Try to change Route:-
 Route::any('/getgeo', 'ProductController@getCoordinate');


问:
Is the a way to write a function with this signature?
I've got a function that's doing something currently working with particular datatypes. I was wondering if I could make it a general. Here's a generalised version of it's signature:

```<code>f :: Monad m => ((a -> b) -> c -> d) -> (a -> m b) -> m c -> m d
</code>```

If the above can't be written, perhaps the more restricted version can?

```<code>f2 :: Monad m => ((a -> a) -> b -> b) -> (a -> m a) -> m b -> m b
</code>```

答:
There's a problem. Knowing c doesn't give you any information about which as will be passed to (a -> b). You either need to be able to enumerate the universe of as or be able to inspect the provided a arguments with something like

```<code>(forall f. Functor f => ((a -> f b) -> c -> f d)
</code>```

In which case it becomes almost trivial to implement f.

Instead of trying to implement f in general, you should try to generalize your functions like ((a -> b) -> c -> d) to see if you can replace them with lenses, traversals, or something similar.

Body:
I've got a function that's doing something currently working with particular datatypes. I was wondering if I could make it a general. Here's a generalised version of it's signature:

f :: Monad m => ((a -> b) -> c -> d) -> (a -> m b) -> m c -> m d

If the above can't be written, perhaps the more restricted version can?

f2 :: Monad m => ((a -> a) -> b -> b) -> (a -> m a) -> m b -> m b

Body:
There's a problem. Knowing c doesn't give you any information about which as will be passed to (a -> b). You either need to be able to enumerate the universe of as or be able to inspect the provided a arguments with something like

(forall f. Functor f => ((a -> f b) -> c -> f d)

In which case it becomes almost trivial to implement f.

Instead of trying to implement f in general, you should try to generalize your functions like ((a -> b) -> c -> d) to see if you can replace them with lenses, traversals, or something similar.


问:
Dplyr and multiple t test (keeping the same IV)
I'm using this pretty nice code to perform a multiple t.test keeping the independent variable constant!

```<code>data(mtcars)
library(dplyr)
vars_to_test <- c("disp","hp","drat","wt","qsec")
iv <- "vs"
mtcars %>%
  summarise_each_(
    funs_(
      sprintf("stats::t.test(.[%s == 0], .[%s == 1])$p.value",iv,iv)
    ),
    vars = vars_to_test)
</code>```

Unfortunately, dplyr was updated and I've been facing this report

summarise_each() is deprecated. Use summarise_all(),
  summarise_at() or summarise_if() instead. To map funs over a
  selection of variables, use summarise_at()

When i change the code for _all, at or _if, this function doest not work any more. I'm looking for some advice and thanks much for your support.

Thanks

答:
Instead of creating a string expression with sprintf and then evaluating it, we can use the evaluate the 'vs' converting it to symbol and then evaluate it

```<code>library(dplyr)
mtcars %>%
   summarise_at(vars(vars_to_test), funs(
     try(stats::t.test(.[(!! rlang::sym(iv)) == 0], .[(!! rlang::sym(iv)) == 1])$p.value)
  ))
#          disp           hp       drat           wt         qsec
#1 2.476526e-06 1.819806e-06 0.01285342 0.0007281397 3.522404e-06
</code>```

If we really wanted to parse an expression, use the rlang_parse_expr and rlang::eval_tidy along with sym

```<code>library(rlang)
eval_tidy(parse_expr("mtcars %>% summarise_at(vars(vars_to_test),
                funs(t.test(.[(!!sym(iv))==0],
                                   .[(!!sym(iv))==1])$p.value ))"))
#          disp           hp       drat           wt         qsec
#1 2.476526e-06 1.819806e-06 0.01285342 0.0007281397 3.522404e-06
</code>```

Body:
I'm using this pretty nice code to perform a multiple t.test keeping the independent variable constant!

data(mtcars)
library(dplyr)
vars_to_test <- c("disp","hp","drat","wt","qsec")
iv <- "vs"
mtcars %>%
  summarise_each_(
    funs_(
      sprintf("stats::t.test(.[%s == 0], .[%s == 1])$p.value",iv,iv)
    ),
    vars = vars_to_test)

Unfortunately, dplyr was updated and I've been facing this report

summarise_each() is deprecated. Use summarise_all(),
  summarise_at() or summarise_if() instead. To map funs over a
  selection of variables, use summarise_at()

When i change the code for _all, at or _if, this function doest not work any more. I'm looking for some advice and thanks much for your support.

Thanks

Body:
Instead of creating a string expression with sprintf and then evaluating it, we can use the evaluate the 'vs' converting it to symbol and then evaluate it

library(dplyr)
mtcars %>%
   summarise_at(vars(vars_to_test), funs(
     try(stats::t.test(.[(!! rlang::sym(iv)) == 0], .[(!! rlang::sym(iv)) == 1])$p.value)
  ))
#          disp           hp       drat           wt         qsec
#1 2.476526e-06 1.819806e-06 0.01285342 0.0007281397 3.522404e-06

If we really wanted to parse an expression, use the rlang_parse_expr and rlang::eval_tidy along with sym

library(rlang)
eval_tidy(parse_expr("mtcars %>% summarise_at(vars(vars_to_test),
                funs(t.test(.[(!!sym(iv))==0],
                                   .[(!!sym(iv))==1])$p.value ))"))
#          disp           hp       drat           wt         qsec
#1 2.476526e-06 1.819806e-06 0.01285342 0.0007281397 3.522404e-06


问:
How to center the message inside an alert box in JavaScript?
Suppose I have an alert message like:

 alert("Message");```

When this command is executed, an alert box pops up but the message is aligned to the left of the alert box.

Is there a way to center this message inside the alert box?

答:
If your alert message will be static then add multiple '\t' at the starting of your message.

```<code>alert('\t Quantity should be less than Remaining Quantity! \n \t\t\t Remaining Quantity');
</code>```

Here \n is use for break the message and place on next line

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have an alert message like:

 alert("Message");

When this command is executed, an alert box pops up but the message is aligned to the left of the alert box.

Is there a way to center this message inside the alert box?

Body:
If your alert message will be static then add multiple '\t' at the starting of your message.

alert('\t Quantity should be less than Remaining Quantity! \n \t\t\t Remaining Quantity');

Here \n is use for break the message and place on next line


问:
Can the 'enter' selection for a line graph be animated?
I have a line graph that updates very nicely. Until new data enters the question. At that point the 'update' selection animates down as it should but the new data doesn't.

It's hard to explain what's happening, but a gif is worth a thousand words (watch when it transitions down):

I've wrapped the graph in a class with an update and render method. Here's the render method I wrote.

```<code>render(){
    // Update both Axes
    this.xAxis.transition()
        .call( d3.axisBottom( this.xScale ) );
    this.yAxis.transition()
        .call( this.createYAxis );

    // Exit
    this.line.exit().remove();

    // Enter
    this.line
      .enter().append( 'path' )
        .attr( 'class', 'valueLine' )
        .transition()
        .attr( 'd', this.valueLine );

    // Update
    this.line.transition().attr( 'd', this.valueLine );

    // Allows method chaining
    return this;
}
</code>```

Why doesn't the 'new' data animate in?

答:
Short answer

Yes, but you have to define the starting value for the d attribute.

Long answer

A transition goes from a starting value to a target value. Right now, in your "enter" selection, you have no starting value (that is, before transition()) for the d attribute:

```<code>// Enter
this.line
    .enter().append( 'path' )
    .attr( 'class', 'valueLine' )
    .transition()//no 'd' attribute before this line
    .attr( 'd', this.valueLine );
</code>```

Therefore, the d attribute for that path is null (read more about this in this answer).

Let's see it:

var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path");

console.log(path.attr("d"))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}</code>```

<svg width="600" height="200"></svg>```
</div>
</div>
</p>

<p>Here the same code, setting the <code>d</code> attribute:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path")
  .attr("d", lineGenerator);</code>```

path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="200"></svg></code>```

Back to your question:

You cannot transition the d attribute from null to your string. It's impossible. There are some possible workarounds, though.

One of them is creating a default d attribute before the transition. For instance:

var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path")
  .attr("d", "M0,100 L600,100")
  .transition()
  .duration(2000)
  .attr("d", lineGenerator);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}</code>```

<svg width="600" height="200"></svg>```
</div>
</div>
</p>

<p>But that's a horrible transition! The problem is that the initial <code>d</code> attribute has too few points. Because of that, the string interpolator cannot create the interpolation we wish.</p>

<p>So, we can use a custom function, like this one from Mike Bostock. Here is the demo:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path")
  .attr("d", "M0,100 L600,100")
  .transition()
  .duration(2000)
  .attrTween("d", function(d) {
    return pathTween(lineGenerator(d), 4, this)()
  });

function pathTween(d1, precision, self) {
  return function() {
    var path0 = self,
      path1 = path0.cloneNode(),
      n0 = path0.getTotalLength(),
      n1 = (path1.setAttribute("d", d1), path1).getTotalLength();

    // Uniform sampling of distance based on specified precision.
    var distances = [0],
      i = 0,
      dt = precision / Math.max(n0, n1);
    while ((i += dt) < 1) distances.push(i);
    distances.push(1);

    // Compute point-interpolators at each distance.
    var points = distances.map(function(t) {
      var p0 = path0.getPointAtLength(t * n0),
        p1 = path1.getPointAtLength(t * n1);
      return d3.interpolate([p0.x, p0.y], [p1.x, p1.y]);
    });

    return function(t) {
      return t < 1 ? "M" + points.map(function(p) {
        return p(t);
      }).join("L") : d1;
    };
  };
}</code>```

path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="200"></svg></code>```

Body:
I have a line graph that updates very nicely. Until new data enters the question. At that point the 'update' selection animates down as it should but the new data doesn't.

It's hard to explain what's happening, but a gif is worth a thousand words (watch when it transitions down):

I've wrapped the graph in a class with an update and render method. Here's the render method I wrote.

render(){
    // Update both Axes
    this.xAxis.transition()
        .call( d3.axisBottom( this.xScale ) );
    this.yAxis.transition()
        .call( this.createYAxis );

    // Exit
    this.line.exit().remove();

    // Enter
    this.line
      .enter().append( 'path' )
        .attr( 'class', 'valueLine' )
        .transition()
        .attr( 'd', this.valueLine );

    // Update
    this.line.transition().attr( 'd', this.valueLine );

    // Allows method chaining
    return this;
}

Why doesn't the 'new' data animate in?

Body:
Short answer

Yes, but you have to define the starting value for the d attribute.

Long answer

A transition goes from a starting value to a target value. Right now, in your "enter" selection, you have no starting value (that is, before transition()) for the d attribute:

// Enter
this.line
    .enter().append( 'path' )
    .attr( 'class', 'valueLine' )
    .transition()//no 'd' attribute before this line
    .attr( 'd', this.valueLine );

Therefore, the d attribute for that path is null (read more about this in this answer).

Let's see it:

var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path");

console.log(path.attr("d"))

path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="200"></svg>

Here the same code, setting the d attribute:

var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path")
  .attr("d", lineGenerator);

path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="200"></svg>

Back to your question:

You cannot transition the d attribute from null to your string. It's impossible. There are some possible workarounds, though.

One of them is creating a default d attribute before the transition. For instance:

var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path")
  .attr("d", "M0,100 L600,100")
  .transition()
  .duration(2000)
  .attr("d", lineGenerator);

path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="200"></svg>

But that's a horrible transition! The problem is that the initial d attribute has too few points. Because of that, the string interpolator cannot create the interpolation we wish.

So, we can use a custom function, like this one from Mike Bostock. Here is the demo:

var data = [10, 180, 30, 60, 190, 180, 50, 110, 40, 90, 90];
var svg = d3.select("svg");
var lineGenerator = d3.line()
  .y(function(d) {
    return d
  })
  .x(function(d, i) {
    return i * 60
  });
var path = svg.selectAll(null)
  .data([data])
  .enter()
  .append("path")
  .attr("d", "M0,100 L600,100")
  .transition()
  .duration(2000)
  .attrTween("d", function(d) {
    return pathTween(lineGenerator(d), 4, this)()
  });

function pathTween(d1, precision, self) {
  return function() {
    var path0 = self,
      path1 = path0.cloneNode(),
      n0 = path0.getTotalLength(),
      n1 = (path1.setAttribute("d", d1), path1).getTotalLength();

    // Uniform sampling of distance based on specified precision.
    var distances = [0],
      i = 0,
      dt = precision / Math.max(n0, n1);
    while ((i += dt) < 1) distances.push(i);
    distances.push(1);

    // Compute point-interpolators at each distance.
    var points = distances.map(function(t) {
      var p0 = path0.getPointAtLength(t * n0),
        p1 = path1.getPointAtLength(t * n1);
      return d3.interpolate([p0.x, p0.y], [p1.x, p1.y]);
    });

    return function(t) {
      return t < 1 ? "M" + points.map(function(p) {
        return p(t);
      }).join("L") : d1;
    };
  };
}

path {
  fill: none;
  stroke-width: 2px;
  stroke: teal;
}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="200"></svg>


问:
get number of columns of a particular row in given excel using Java
I want the number of columns of a particular row in excel. How is that possible? I used POI API

but I could get only columns count to 7 .

```<code>    try
            {
                fileInputStream = new FileInputStream(file);
                workbook = new HSSFWorkbook(fileInputStream);
                Sheet sheet = workbook.getSheet("0");

                int numberOfCells = 0;
                Iterator rowIterator = sheet.rowIterator();
                /**
                 * Escape the header row *
                 */
                if (rowIterator.hasNext())
                {
                    Row headerRow = (Row) rowIterator.next();
                    //get the number of cells in the header row
                    numberOfCells = headerRow.getPhysicalNumberOfCells();
                }
                System.out.println("number of cells "+numberOfCells);

}
</code>```

I want the number of columns at a particular row number say 10 .
The excel columns are not same

答:
```<code>/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
    int result = 0;
    Iterator<Row> rowIterator = xssfSheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        List<Cell> cells = new ArrayList<>();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            cells.add(cellIterator.next());
        }
        for (int i = cells.size(); i >= 0; i--) {
            Cell cell = cells.get(i-1);
            if (cell.toString().trim().isEmpty()) {
                cells.remove(i-1);
            } else {
                result = cells.size() > result ? cells.size() : result;
                break;
            }
        }
    }
    return result;
}
</code>```

Body:
I want the number of columns of a particular row in excel. How is that possible? I used POI API

but I could get only columns count to 7 .

    try
            {
                fileInputStream = new FileInputStream(file);
                workbook = new HSSFWorkbook(fileInputStream);
                Sheet sheet = workbook.getSheet("0");

                int numberOfCells = 0;
                Iterator rowIterator = sheet.rowIterator();
                /**
                 * Escape the header row *
                 */
                if (rowIterator.hasNext())
                {
                    Row headerRow = (Row) rowIterator.next();
                    //get the number of cells in the header row
                    numberOfCells = headerRow.getPhysicalNumberOfCells();
                }
                System.out.println("number of cells "+numberOfCells);

}

I want the number of columns at a particular row number say 10 .
The excel columns are not same


问:
How to Make Two Windows Applications Talk to Each Other using C#
Recently I went through a C# course by Bob Tabor in MSDN Channel 9 and I loved it. understood the overview of C#.

I have a stock trading application based on C# (NinjaTrader) and I want it to talk with Excel 2016. By that I mean if I draw a trend line in Ninjatrader on a candlestick chart, I want excel to understand that I drew a trendline and want it to perform a simple task like highlighting some thing or bold a specific cell based on some conditions. I want them to talk to each other in real-time. This is my requirement.

I recently hired a programmer to do this task (he is still working on the project), but I want to do this myself in the coming years as I want to "give myself wings". Having ideas but not knowing what to do to actually accomplish the task is seriously limiting me.

What I understood after going through Bob Tabor's C# course is this. In his video "Understanding Namespaces and Adding References to Assemblies", I need to use a reference to Excel's library. That part I could grasp, but when people talk about COM,Interop...

I'd call myself an Excel power user as I have good experience in developing spreadsheets with close to half-a-million vlookups on binary file format.

Can you please suggest me a course that teaches how to make two applications talk to each other? I need this course to be in C#. Also I'm not sure what next step I should take to improve my c# skills. I searched for c# in 21 days Sams book, but I couldn't find an updated version of it. All other languages had such book but not c#. I want to use my knowledge only for personal use. So, if you could suggest me a course that also helps me to reach a good c# proficiency level.

答: what i understand is that you need an xls/xlsx output from your project. you can implement excel functions on your project by using either office library or thrd party librarys.</p>


问:
Semantics of DataFrame groupby method
I find the behavior of the groupby method on a DataFrame object unexpected.

Let me explain with an example.

```<code>df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
                   'key2': ['one', 'two', 'one', 'two', 'one'],
                   'data1': np.random.randn(5),
                   'data2': np.random.randn(5)})
data1 = df['data1']

data1
# Out[14]:
# 0    1.989430
# 1   -0.250694
# 2   -0.448550
# 3    0.776318
# 4   -1.843558
# Name: data1, dtype: float64
</code>```

data1 does not have the 'key1' column anymore.
So I would expect to get an error if I applied the following operation:

```<code>grouped = data1.groupby(df['key1'])
</code>```

But I don't, and I can further apply the mean method on grouped to get the expected result.

```<code>grouped.mean()
# Out[13]:
# key1
# a   -0.034941
# b    0.163884
# Name: data1, dtype: float64
</code>```

However, the above operation does create a group using the 'key1' column of df.

How can this happen? Does the interpreter store information of the originating DataFrame (df in this case) with the created DataFrame/series (data1 in this case)?

Thank you.

答:
It is only syntactic sugar, check here - selection by columns (Series) separately:

This is mainly syntactic sugar for the alternative and much more verbose

```<code>s = df['data1'].groupby(df['key1']).mean()
print (s)
key1
a    0.565292
b    0.106360
Name: data1, dtype: float64
</code>```

Title: Semantics of DataFrame groupby method

Body:
I find the behavior of the groupby method on a DataFrame object unexpected.

Let me explain with an example.

df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
                   'key2': ['one', 'two', 'one', 'two', 'one'],
                   'data1': np.random.randn(5),
                   'data2': np.random.randn(5)})
data1 = df['data1']

data1
# Out[14]:
# 0    1.989430
# 1   -0.250694
# 2   -0.448550
# 3    0.776318
# 4   -1.843558
# Name: data1, dtype: float64

data1 does not have the 'key1' column anymore.
So I would expect to get an error if I applied the following operation:

grouped = data1.groupby(df['key1'])

But I don't, and I can further apply the mean method on grouped to get the expected result.

grouped.mean()
# Out[13]:
# key1
# a   -0.034941
# b    0.163884
# Name: data1, dtype: float64

However, the above operation does create a group using the 'key1' column of df.

How can this happen? Does the interpreter store information of the originating DataFrame (df in this case) with the created DataFrame/series (data1 in this case)?

Thank you.

Body:
It is only syntactic sugar, check here - selection by columns (Series) separately:

This is mainly syntactic sugar for the alternative and much more verbose

s = df['data1'].groupby(df['key1']).mean()
print (s)
key1
a    0.565292
b    0.106360
Name: data1, dtype: float64


问:
How to round to 2 decimals during calculation in Java
For one calculation I need to round to 2 decimals during the calculation.

Relevant code:

```<code>count = 500;
price = 0.00077
pounds = 150,000
double value = ((350 - count) * price) * (pounds / 100);
</code>```

To get the result I need, (350 - count) * price must round to 2 decimal places before doing the pounds / 100 so how might i round to 2 decimal places during a calculation?

答:
In java you can round it some think like that

```<code>double roundOff = Math.round(a * 100.0) / 100.0;
</code>```

in your case

```<code>Math.round(((350 - count) * price) * 100d) / 100d
</code>```

Body:
For one calculation I need to round to 2 decimals during the calculation.

Relevant code:

count = 500;
price = 0.00077
pounds = 150,000
double value = ((350 - count) * price) * (pounds / 100);

To get the result I need, (350 - count) * price must round to 2 decimal places before doing the pounds / 100 so how might i round to 2 decimal places during a calculation?

Body:
In java you can round it some think like that

double roundOff = Math.round(a * 100.0) / 100.0;

in your case

Math.round(((350 - count) * price) * 100d) / 100d


问:
How to know if my application is in foreground or background, android?
I need to check if my application is running in background or foreground and then perform some operations relatively to it.

I searched a lot and a clear solution is not available.

Make a parent activity in its onPause() and onResume() methods keep some variable to update them accordingly. When you create any new activity inherit your parent activity.
Although this is the best solution I feel to achieve my task, but sometimes if the power button is clicked even though application is in background, it's onResume() is invoked.

Use GETTASKS permission - This solution is also good. But it can only used for debug purpose. Not if you want to put your app on Google Play Store.

Get Running Taks

Any other preferred solution for this?

答:
check app is in forground state or background state

```<code>ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
   List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

   final String packageName = getPackageName();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses)
   {

   if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND && appProcess.processName.equals(packageName))
      {

       //if app in background state this will execute

        Intent intent = getPackageManager().getLaunchIntentForPackage("hinditextonphoto.com.allcomponents");
        startActivity(intent);
        System.out.println("bbbbbbbbbbbbb    background");
      }

       else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName))
       {

       //if app in forground state this will execute
         System.out.println("bbbbbbbbbbbbb    forground");

       }

  }
</code>```

Body:
check app is in forground state or background state

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
   List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();

   final String packageName = getPackageName();
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses)
   {

   if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND && appProcess.processName.equals(packageName))
      {

       //if app in background state this will execute

        Intent intent = getPackageManager().getLaunchIntentForPackage("hinditextonphoto.com.allcomponents");
        startActivity(intent);
        System.out.println("bbbbbbbbbbbbb    background");
      }

       else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName))
       {

       //if app in forground state this will execute
         System.out.println("bbbbbbbbbbbbb    forground");

       }

  }


问:
Do you have any good examples of "architecture for architecture's sake"?
Just listening to this week's podcast and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.

Java often gets a bad press in this respect, and an increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.

My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views).

答: I always thought This Hello World implementation was good, too.</p>

OwnerDisplayName: Nick Pierpoint

LastEditorDisplayName: Nick Pierpoint

OwnerDisplayName: DCookie


问:
Windows API functions
Are they standard code c or c++ code? what are they?</p>

答:
The original Win32 API is C-based.  There are however a substantial number of services within Windows that are COM based.  Good examples are the clipboard, drag+drop, the shell, the user mode driver framework, DirectX.  While it is technically possible to write COM code in C, it is excruciatingly painful to do so.

Realistically you use C++ there.  And a C++ class library to make the original C-based API less painful, especially for GUI code.

Title: Windows API functions