问:
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object cannot find what's wrong
I'm not sure what is wrong with my code. I made sure all the objects implement Serializable. I've already looked at other questions but still can't find a solution. Can someone help me find out what's wrong please? Thank you

Here's what it says in the logcat

```<code>12-04 00:54:15.826 5602-5602/com.b07.joesapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                           Process: com.b07.joesapp, PID: 5602
                                                           java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.b07.joesapp.admin.AdminInterfaceImpl)
                                                               at android.os.Parcel.writeSerializable(Parcel.java:1822)
                                                               at android.os.Parcel.writeValue(Parcel.java:1770)
                                                               at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
                                                               at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
                                                               at android.os.Bundle.writeToParcel(Bundle.java:1232)
                                                               at android.os.Parcel.writeBundle(Parcel.java:878)
                                                               at android.content.Intent.writeToParcel(Intent.java:9595)
                                                               at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4327)
                                                               at android.app.Instrumentation.execStartActivity(Instrumentation.java:1611)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4488)
                                                               at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4446)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
                                                               at android.app.Activity.startActivity(Activity.java:4807)
                                                               at android.app.Activity.startActivity(Activity.java:4775)
                                                               at com.b07.joesapp.adminMenu.AdminActionsController.onClick(AdminActionsController.java:49)
                                                               at android.view.View.performClick(View.java:6294)
                                                               at android.view.View$PerformClick.run(View.java:24770)
                                                               at android.os.Handler.handleCallback(Handler.java:790)
                                                               at android.os.Handler.dispatchMessage(Handler.java:99)
                                                               at android.os.Looper.loop(Looper.java:164)
                                                               at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                            Caused by: java.io.NotSerializableException: com.b07.joesapp.adminMenu.AdminHomePage
                                                               at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1233)
                                                               at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
                                                               at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
                                                               at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
                                                               at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
                                                               at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
                                                               at android.os.Parcel.writeSerializable(Parcel.java:1817)
                                                               at android.os.Parcel.writeValue(Parcel.java:1770)
                                                               at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
                                                               at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
                                                               at android.os.Bundle.writeToParcel(Bundle.java:1232)
                                                               at android.os.Parcel.writeBundle(Parcel.java:878)
                                                               at android.content.Intent.writeToParcel(Intent.java:9595)
                                                               at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4327)
                                                               at android.app.Instrumentation.execStartActivity(Instrumentation.java:1611)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4488)
                                                               at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4446)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
                                                               at android.app.Activity.startActivity(Activity.java:4807)
                                                               at android.app.Activity.startActivity(Activity.java:4775)
                                                               at com.b07.joesapp.adminMenu.AdminActionsController.onClick(AdminActionsController.java:49)
                                                               at android.view.View.performClick(View.java:6294)
                                                               at android.view.View$PerformClick.run(View.java:24770)
                                                               at android.os.Handler.handleCallback(Handler.java:790)
                                                               at android.os.Handler.dispatchMessage(Handler.java:99)
                                                               at android.os.Looper.loop(Looper.java:164)
                                                               at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

And here are my classes.
AdminHomePage

```<code>package com.b07.joesapp.adminMenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;

import com.b07.joesapp.R;
import com.b07.joesapp.admin.VoiceRecognitionAdminController;
import com.b07.users.Admin;

public class AdminHomePage extends AppCompatActivity {

    private Admin admin;
    private Button toAdminActions;
    private Button talkAdminCtrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_home_page);

        // get the admin and the inventory to create an AdminInterfaceImpl object to be passed on
        admin = (Admin) getIntent().getSerializableExtra("adminUser");

        AdminActionsController controller = new AdminActionsController(this, admin);
        toAdminActions = (Button) findViewById(R.id.toAdminActionsBtn);
        toAdminActions.setOnClickListener(controller);

        // this is what happens when the voice control button is clicked
        talkAdminCtrl= (Button) findViewById(R.id.voiceControlAdminActionsBtn);
        VoiceRecognitionAdminController voiceRecognitionAdmin = new VoiceRecognitionAdminController(this, admin);
        talkAdminCtrl.setOnClickListener(voiceRecognitionAdmin);

    }
}
</code>```

AdminActionsController

```<code>package com.b07.joesapp.adminMenu;

import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.b07.database.DatabaseSelectHelper;
import com.b07.exceptions.DatabaseException;
import com.b07.exceptions.interfaceexceptions.UserNotAuthenticatedException;
import com.b07.inventory.Inventory;
import com.b07.joesapp.admin.AdminControls;
import com.b07.joesapp.admin.AdminInterfaceImpl;
import com.b07.users.Admin;

/**
 * Created by shama on 12/1/2017.
 */

public class AdminActionsController implements View.OnClickListener {

    private Context appContext;
    private Admin adminUser;
    private Inventory inventory;
    private AdminInterfaceImpl adminInterface;

    public AdminActionsController(Context context, Admin admin) {
        appContext = context;
        adminUser = admin;
        try {
            DatabaseSelectHelper selectHelper = new DatabaseSelectHelper(appContext);
            inventory = selectHelper.getInventory();
        } catch (DatabaseException e) {
            //will not be handled
        }
        try {
            adminInterface = new AdminInterfaceImpl(adminUser, inventory, appContext);
        } catch (UserNotAuthenticatedException e) {
            // do something if exception is caught
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(appContext, AdminControls.class);
        intent.putExtra("adminInterface",  adminInterface);
        appContext.startActivity(intent);
    }
}
</code>```

Admin

```<code>package com.b07.users;

import android.content.Context;

import java.io.Serializable;

/**
 * Class that represents an admin.
 *
 * @author Linda
 *
 */
public class Admin extends User implements Serializable {

  /**
   * Initializes admin.
   *
   * @param id the id of the admin
   * @param name the name of the admin
   * @param age the age of the admin
   * @param address the address of the admin
   */
  public Admin(int id, String name, int age, String address) {
    //Sets all appropriate variables
    super(id, name, age, address);
  }

  /**
   * Initializes authenticated admin.
   *
   * @param id the id of the admin
   * @param name the name of the admin
   * @param age the age of the admin
   * @param address the address of the admin
   * @param authenticated the authentication of the admin
   */
  public Admin
  (int id, String name, int age, String address, boolean authenticated, Context context) {
    super(id, name, age, address, authenticated);
  }

  /** promoteEmployee removed **/
}
</code>```

Inventory

```<code>/**
 *
 */

package com.b07.inventory;

import com.b07.exceptions.ItemNotFoundException;
import java.io.Serializable;
import java.util.HashMap;

/**
 * Class that represents an inventory.
 * @author Linda
 *
 */
public class InventoryImpl implements Inventory, Serializable {

  // declare variables inside InventoryImpl instance
  int totalItems = 0;
  HashMap<Item, Integer> itemMap = new HashMap<>();

  /**
   * Returns the item map of the inventory.
   * @return itemMap
   */
  @Override
  public HashMap<Item, Integer> getItemMap() {
    return this.itemMap;
  }

  /**
   * Sets the item map of the inventory.
   * @param itemMap the new item map
   */
  @Override
  public void setItemMap(HashMap<Item, Integer> itemMap) {
    this.itemMap = itemMap;
    this.setTotalItems(this.itemMap.size());

  }

  /**
   * Changes the quantity of a given item.
   * @param item the item
   * @param value the quantity changed
   * @throws ItemNotFoundException if item not in inventory
   */
  @Override
  public void updateMap(Item item, Integer value) throws ItemNotFoundException {
    // if the item exists it is added if not an exception is thrown
    if (this.itemMap.containsKey(item)) {
      this.itemMap.put(item, value);
    } else {
      throw new ItemNotFoundException();
    }

  }

  /**
   * Returns the total number of items in the inventory.
   * @return totalItems
   */
  @Override
  public int getTotalItems() {
    return this.totalItems;
  }

  /**
   * Sets the new total number of items in the inventory.
   * @param total the new total
   */
  @Override
  public void setTotalItems(int total) {
    this.totalItems = total;

  }

  /**
   * Checks if the inventory contains the desired item.
   *
   * @param item the desired item
   * @return true if it is in the inventory, false if not
   */
  @Override
  public boolean containsItem(Item item) {
    if (itemMap.containsKey(item)) {
      return true;
    }
    return false;
  }

  /**
   * Returns the quantity of the desired item.
   *
   * @param item the desired item
   * @return quantity the current quantity of item
   * @throws ItemNotFoundException if item is not found in the inventory
   */
  @Override
  public int getItemQuantity(Item item) throws ItemNotFoundException {
    // if the item exists then its quantity is returned otherwise an exception is thrown
    if (this.itemMap.containsKey(item)) {
      return this.itemMap.get(item);
    }
    throw new ItemNotFoundException();
  }

}
</code>```

I'm really stuck here. I've checked over and over again that all objects implement Serializable but I'm still not sure what the problem is. Thanks!

答:
In this method

```<code> public void onClick(View view) {
    Intent intent = new Intent(appContext, AdminControls.class);
    intent.putExtra("adminInterface",  adminInterface);
    appContext.startActivity(intent);
}
</code>```

You pass custom object so try with this

```<code> public void onClick(View view) {
    Bundle bundle = new Bundle();
    bundle.putSerializable("adminInterface", adminInterface);
    Intent intent = new Intent(appContext, AdminControls.class);
    intent.putExtras(bundle);
    appContext.startActivity(intent);
}
</code>```

Body:
I'm not sure what is wrong with my code. I made sure all the objects implement Serializable. I've already looked at other questions but still can't find a solution. Can someone help me find out what's wrong please? Thank you

Here's what it says in the logcat

12-04 00:54:15.826 5602-5602/com.b07.joesapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                           Process: com.b07.joesapp, PID: 5602
                                                           java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.b07.joesapp.admin.AdminInterfaceImpl)
                                                               at android.os.Parcel.writeSerializable(Parcel.java:1822)
                                                               at android.os.Parcel.writeValue(Parcel.java:1770)
                                                               at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
                                                               at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
                                                               at android.os.Bundle.writeToParcel(Bundle.java:1232)
                                                               at android.os.Parcel.writeBundle(Parcel.java:878)
                                                               at android.content.Intent.writeToParcel(Intent.java:9595)
                                                               at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4327)
                                                               at android.app.Instrumentation.execStartActivity(Instrumentation.java:1611)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4488)
                                                               at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4446)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
                                                               at android.app.Activity.startActivity(Activity.java:4807)
                                                               at android.app.Activity.startActivity(Activity.java:4775)
                                                               at com.b07.joesapp.adminMenu.AdminActionsController.onClick(AdminActionsController.java:49)
                                                               at android.view.View.performClick(View.java:6294)
                                                               at android.view.View$PerformClick.run(View.java:24770)
                                                               at android.os.Handler.handleCallback(Handler.java:790)
                                                               at android.os.Handler.dispatchMessage(Handler.java:99)
                                                               at android.os.Looper.loop(Looper.java:164)
                                                               at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                            Caused by: java.io.NotSerializableException: com.b07.joesapp.adminMenu.AdminHomePage
                                                               at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1233)
                                                               at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
                                                               at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
                                                               at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
                                                               at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
                                                               at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
                                                               at android.os.Parcel.writeSerializable(Parcel.java:1817)
                                                               at android.os.Parcel.writeValue(Parcel.java:1770)
                                                               at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
                                                               at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
                                                               at android.os.Bundle.writeToParcel(Bundle.java:1232)
                                                               at android.os.Parcel.writeBundle(Parcel.java:878)
                                                               at android.content.Intent.writeToParcel(Intent.java:9595)
                                                               at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4327)
                                                               at android.app.Instrumentation.execStartActivity(Instrumentation.java:1611)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4488)
                                                               at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                                                               at android.app.Activity.startActivityForResult(Activity.java:4446)
                                                               at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
                                                               at android.app.Activity.startActivity(Activity.java:4807)
                                                               at android.app.Activity.startActivity(Activity.java:4775)
                                                               at com.b07.joesapp.adminMenu.AdminActionsController.onClick(AdminActionsController.java:49)
                                                               at android.view.View.performClick(View.java:6294)
                                                               at android.view.View$PerformClick.run(View.java:24770)
                                                               at android.os.Handler.handleCallback(Handler.java:790)
                                                               at android.os.Handler.dispatchMessage(Handler.java:99)
                                                               at android.os.Looper.loop(Looper.java:164)
                                                               at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

And here are my classes.
AdminHomePage

package com.b07.joesapp.adminMenu;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;

import com.b07.joesapp.R;
import com.b07.joesapp.admin.VoiceRecognitionAdminController;
import com.b07.users.Admin;

public class AdminHomePage extends AppCompatActivity {

    private Admin admin;
    private Button toAdminActions;
    private Button talkAdminCtrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_home_page);

        // get the admin and the inventory to create an AdminInterfaceImpl object to be passed on
        admin = (Admin) getIntent().getSerializableExtra("adminUser");

        AdminActionsController controller = new AdminActionsController(this, admin);
        toAdminActions = (Button) findViewById(R.id.toAdminActionsBtn);
        toAdminActions.setOnClickListener(controller);

        // this is what happens when the voice control button is clicked
        talkAdminCtrl= (Button) findViewById(R.id.voiceControlAdminActionsBtn);
        VoiceRecognitionAdminController voiceRecognitionAdmin = new VoiceRecognitionAdminController(this, admin);
        talkAdminCtrl.setOnClickListener(voiceRecognitionAdmin);

    }
}

AdminActionsController

package com.b07.joesapp.adminMenu;

import android.content.Context;
import android.content.Intent;
import android.view.View;

import com.b07.database.DatabaseSelectHelper;
import com.b07.exceptions.DatabaseException;
import com.b07.exceptions.interfaceexceptions.UserNotAuthenticatedException;
import com.b07.inventory.Inventory;
import com.b07.joesapp.admin.AdminControls;
import com.b07.joesapp.admin.AdminInterfaceImpl;
import com.b07.users.Admin;

/**
 * Created by shama on 12/1/2017.
 */

public class AdminActionsController implements View.OnClickListener {

    private Context appContext;
    private Admin adminUser;
    private Inventory inventory;
    private AdminInterfaceImpl adminInterface;

    public AdminActionsController(Context context, Admin admin) {
        appContext = context;
        adminUser = admin;
        try {
            DatabaseSelectHelper selectHelper = new DatabaseSelectHelper(appContext);
            inventory = selectHelper.getInventory();
        } catch (DatabaseException e) {
            //will not be handled
        }
        try {
            adminInterface = new AdminInterfaceImpl(adminUser, inventory, appContext);
        } catch (UserNotAuthenticatedException e) {
            // do something if exception is caught
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(appContext, AdminControls.class);
        intent.putExtra("adminInterface",  adminInterface);
        appContext.startActivity(intent);
    }
}

Admin

package com.b07.users;

import android.content.Context;

import java.io.Serializable;

/**
 * Class that represents an admin.
 *
 * @author Linda
 *
 */
public class Admin extends User implements Serializable {

  /**
   * Initializes admin.
   *
   * @param id the id of the admin
   * @param name the name of the admin
   * @param age the age of the admin
   * @param address the address of the admin
   */
  public Admin(int id, String name, int age, String address) {
    //Sets all appropriate variables
    super(id, name, age, address);
  }

  /**
   * Initializes authenticated admin.
   *
   * @param id the id of the admin
   * @param name the name of the admin
   * @param age the age of the admin
   * @param address the address of the admin
   * @param authenticated the authentication of the admin
   */
  public Admin
  (int id, String name, int age, String address, boolean authenticated, Context context) {
    super(id, name, age, address, authenticated);
  }

  /** promoteEmployee removed **/
}

Inventory

/**
 *
 */

package com.b07.inventory;

import com.b07.exceptions.ItemNotFoundException;
import java.io.Serializable;
import java.util.HashMap;

/**
 * Class that represents an inventory.
 * @author Linda
 *
 */
public class InventoryImpl implements Inventory, Serializable {

  // declare variables inside InventoryImpl instance
  int totalItems = 0;
  HashMap<Item, Integer> itemMap = new HashMap<>();

  /**
   * Returns the item map of the inventory.
   * @return itemMap
   */
  @Override
  public HashMap<Item, Integer> getItemMap() {
    return this.itemMap;
  }

  /**
   * Sets the item map of the inventory.
   * @param itemMap the new item map
   */
  @Override
  public void setItemMap(HashMap<Item, Integer> itemMap) {
    this.itemMap = itemMap;
    this.setTotalItems(this.itemMap.size());

  }

  /**
   * Changes the quantity of a given item.
   * @param item the item
   * @param value the quantity changed
   * @throws ItemNotFoundException if item not in inventory
   */
  @Override
  public void updateMap(Item item, Integer value) throws ItemNotFoundException {
    // if the item exists it is added if not an exception is thrown
    if (this.itemMap.containsKey(item)) {
      this.itemMap.put(item, value);
    } else {
      throw new ItemNotFoundException();
    }

  }

  /**
   * Returns the total number of items in the inventory.
   * @return totalItems
   */
  @Override
  public int getTotalItems() {
    return this.totalItems;
  }

  /**
   * Sets the new total number of items in the inventory.
   * @param total the new total
   */
  @Override
  public void setTotalItems(int total) {
    this.totalItems = total;

  }

  /**
   * Checks if the inventory contains the desired item.
   *
   * @param item the desired item
   * @return true if it is in the inventory, false if not
   */
  @Override
  public boolean containsItem(Item item) {
    if (itemMap.containsKey(item)) {
      return true;
    }
    return false;
  }

  /**
   * Returns the quantity of the desired item.
   *
   * @param item the desired item
   * @return quantity the current quantity of item
   * @throws ItemNotFoundException if item is not found in the inventory
   */
  @Override
  public int getItemQuantity(Item item) throws ItemNotFoundException {
    // if the item exists then its quantity is returned otherwise an exception is thrown
    if (this.itemMap.containsKey(item)) {
      return this.itemMap.get(item);
    }
    throw new ItemNotFoundException();
  }

}

I'm really stuck here. I've checked over and over again that all objects implement Serializable but I'm still not sure what the problem is. Thanks!

Body:
In this method

 public void onClick(View view) {
    Intent intent = new Intent(appContext, AdminControls.class);
    intent.putExtra("adminInterface",  adminInterface);
    appContext.startActivity(intent);
}

You pass custom object so try with this

 public void onClick(View view) {
    Bundle bundle = new Bundle();
    bundle.putSerializable("adminInterface", adminInterface);
    Intent intent = new Intent(appContext, AdminControls.class);
    intent.putExtras(bundle);
    appContext.startActivity(intent);
}


来源: stackexchange

问:
How to remove the rows while using add more functionality
Here I want to make add more functionality, if I am clicking add more button means I want to make a copy of one row it is working fine, but again I want to remove this row means I don't how to do? if I am clicking remove button I want to remove the selected row, not for all rows, I am a new person of development anyone means please update my snippet

var i=0;
$(document).on("click",".addSharingType",function() {
  i++;

  var htmlText = '';
  htmlText += '

 Sharing Type<select class="form-control seelectcss1 border" name="sharingType[]" required=""><option value="">Select</option><option value="Single Sharing">Single Sharing</option><option value="Two Sharing">Two Sharing</option><option value="Three Sharing">Three Sharing</option><option value="Four Sharing">Four Sharing</option></select>

Rent With Food :
<input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

Rent Without Food
<input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

Advance Amount
<input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

';

  htmlText +='

<button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add</button>  <button type="button" class="btn btn-danger addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> remove</button>

';

  htmlText +='

';
  htmlText +='

';
  $('.sharingType').append(htmlText);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<div class="controls">
  <div class="row">
    <div class="col-md-6 col-sm-4 col-xs-12">
      <label>Sharing Type</label>
      <select class="form-control seelectcss1 border" name="sharingType[]" required="">
        <option value="">Select</option>
        <option value="Single Sharing">Single Sharing</option>
        <option value="Two Sharing">Two Sharing</option>
        <option value="Three Sharing">Three Sharing</option>
        <option value="Four Sharing">Four Sharing</option>
      </select>
    </div>
  </div>

  <div class="row entry">
    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent With Food :</label>
        <br>
        <input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">
        <img src="image/rup.png" id="try"> <div id="word"></div>
        <p class="custom-error amountError" style="display:none">Please Enter Amount</p>
     </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent Without Food </label>
        <br>
        <input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word1"></div>
      </div>
    </div>
    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <label class="control-label">Advance Amount</label>
        <br>
        <input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word2"></div>
      </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"><span class="glyphicon glyphicon-plus"></span> Add Sharing</button>
      </div>
    </div>
  </div>
</div>
<div class="sharingType"></div></code>```

答:
Change remove button class from addSharingType to removeSharingType and then apply this code:-

```<code>$(document).on("click",".removeSharingType",function() {
 $(this).closest('.controls').remove();
});
</code>```

Working example:-

var i=0;
$(document).on("click",".addSharingType",function() {
  i++;

  var htmlText = '';
  htmlText += '

 Sharing Type<select class="form-control seelectcss1 border" name="sharingType[]" required=""><option value="">Select</option><option value="Single Sharing">Single Sharing</option><option value="Two Sharing">Two Sharing</option><option value="Three Sharing">Three Sharing</option><option value="Four Sharing">Four Sharing</option></select>

Rent With Food :
<input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

Rent Without Food
<input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

Advance Amount
<input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

';

  htmlText +='

<button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add</button>  <button type="button" class="btn btn-danger removeSharingType" style="margin-top: 26px;height: 38px;" id="admore"> remove</button>

';

  htmlText +='

';
  htmlText +='

';
  $('.sharingType').append(htmlText);
});

$(document).on("click",".removeSharingType",function() {
  $(this).closest('.controls').remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<div class="controls">
  <div class="row">
    <div class="col-md-6 col-sm-4 col-xs-12">
      <label>Sharing Type</label>
      <select class="form-control seelectcss1 border" name="sharingType[]" required="">
        <option value="">Select</option>
        <option value="Single Sharing">Single Sharing</option>
        <option value="Two Sharing">Two Sharing</option>
        <option value="Three Sharing">Three Sharing</option>
        <option value="Four Sharing">Four Sharing</option>
      </select>
    </div>
  </div>

  <div class="row entry">
    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent With Food :</label>
        <br>
        <input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">
        <img src="image/rup.png" id="try"> <div id="word"></div>
        <p class="custom-error amountError" style="display:none">Please Enter Amount</p>
     </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent Without Food </label>
        <br>
        <input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word1"></div>
      </div>
    </div>
    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <label class="control-label">Advance Amount</label>
        <br>
        <input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word2"></div>
      </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"><span class="glyphicon glyphicon-plus"></span> Add Sharing</button>
      </div>
    </div>
  </div>
</div>
<div class="sharingType"></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Here I want to make add more functionality, if I am clicking add more button means I want to make a copy of one row it is working fine, but again I want to remove this row means I don't how to do? if I am clicking remove button I want to remove the selected row, not for all rows, I am a new person of development anyone means please update my snippet

var i=0;
$(document).on("click",".addSharingType",function() {
  i++;

  var htmlText = '';
  htmlText += '

 Sharing Type<select class="form-control seelectcss1 border" name="sharingType[]" required=""><option value="">Select</option><option value="Single Sharing">Single Sharing</option><option value="Two Sharing">Two Sharing</option><option value="Three Sharing">Three Sharing</option><option value="Four Sharing">Four Sharing</option></select>

Rent With Food :
<input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

Rent Without Food
<input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

Advance Amount
<input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

';

  htmlText +='

<button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add</button>  <button type="button" class="btn btn-danger addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> remove</button>

';

  htmlText +='

';
  htmlText +='

';
  $('.sharingType').append(htmlText);
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

      Sharing Type
      <select class="form-control seelectcss1 border" name="sharingType[]" required="">
        <option value="">Select</option>
        <option value="Single Sharing">Single Sharing</option>
        <option value="Two Sharing">Two Sharing</option>
        <option value="Three Sharing">Three Sharing</option>
        <option value="Four Sharing">Four Sharing</option>
      </select>

        Rent With Food :

        <input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

        Rent Without Food

        <input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

        Advance Amount

        <input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

        <button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add Sharing</button>

Body:
Change remove button class from addSharingType to removeSharingType and then apply this code:-

$(document).on("click",".removeSharingType",function() {
 $(this).closest('.controls').remove();
});

Working example:-

var i=0;
$(document).on("click",".addSharingType",function() {
  i++;

  var htmlText = '';
  htmlText += '<div class="controls"><div class="row"><div class="col-md-6 col-sm-4 col-xs-12"> <label>Sharing Type</label><select class="form-control seelectcss1 border" name="sharingType[]" required=""><option value="">Select</option><option value="Single Sharing">Single Sharing</option><option value="Two Sharing">Two Sharing</option><option value="Three Sharing">Three Sharing</option><option value="Four Sharing">Four Sharing</option></select></div></div><div class="row entry"><div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;"><div class="form-group" id="imm"><label class="control-label">Rent With Food :</label><br><input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)"> <img src="image/rup.png" id="try"> <div id="word"></div><p class="custom-error amountError" style="display:none">Please Enter Amount</p></div></div><div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;"><div class="form-group" id="imm"><label class="control-label">Rent Without Food </label><br><input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)"> <img src="image/rup.png" id="try"><div id="word1"></div></div></div><div class="col-md-3 col-sm-4 col-xs-12"><div class="form-group" id="imm"><label class="control-label">Advance Amount</label><br><input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)"><img src="image/rup.png" id="try"><div id="word2"></div></div></div>';

  htmlText +='<div class="col-md-3 col-sm-4 col-xs-12"><div class="form-group" id="imm"><button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"><span class="glyphicon glyphicon-plus"></span> Add</button>&nbsp;&nbsp;<button type="button" class="btn btn-danger removeSharingType" style="margin-top: 26px;height: 38px;" id="admore"><span class="glyphicon glyphicon-minus"></span> remove</button></div></div>';

  htmlText +='</div></div>';
  htmlText +='</div><br>';
  $('.sharingType').append(htmlText);
});

$(document).on("click",".removeSharingType",function() {
  $(this).closest('.controls').remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<div class="controls">
  <div class="row">
    <div class="col-md-6 col-sm-4 col-xs-12">
      <label>Sharing Type</label>
      <select class="form-control seelectcss1 border" name="sharingType[]" required="">
        <option value="">Select</option>
        <option value="Single Sharing">Single Sharing</option>
        <option value="Two Sharing">Two Sharing</option>
        <option value="Three Sharing">Three Sharing</option>
        <option value="Four Sharing">Four Sharing</option>
      </select>
    </div>
  </div>

  <div class="row entry">
    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent With Food :</label>
        <br>
        <input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">
        <img src="image/rup.png" id="try"> <div id="word"></div>
        <p class="custom-error amountError" style="display:none">Please Enter Amount</p>
     </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent Without Food </label>
        <br>
        <input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word1"></div>
      </div>
    </div>
    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <label class="control-label">Advance Amount</label>
        <br>
        <input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word2"></div>
      </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"><span class="glyphicon glyphicon-plus"></span> Add Sharing</button>
      </div>
    </div>
  </div>
</div>
<div class="sharingType"></div>


问:
Java, Arrays, Methods
The below method calls are giving error while compilation. I'm unable to understand why is it so. I'm passing the same parameters as defined in the method. Kindly help.

ms_div( B[mid_i], mid_i );
ms_div( C[mid_j], mid_j );

Code Starts Below:

```<code>void ms_div(int[] A, int nbr)
        {
            if (nbr > 2)
            {
                int mid_i = A.length / 2;
                int mid_j = A.length - mid_i;
                int[] B = new int[13];
                int[] C = new int[13];

                //create left hand array
                for(int i;i<=mid_i - 1;i++)
                {
                    B[i] = A[i];
                }

                //creating right hand array
                for(int i = 0,j=mid_i;i>= mid_j - 1;i++,j++)
                {
                    C[i] = A[j];
                }

                //Sort Left Hand Array
                if (mid_i >= 2)
                {
                    ms_div( B[mid_i], mid_i );
                }

                //Sort Right Hand Array
                {
                    ms_div( C[mid_j],mid_j );
                }
            }
    }
</code>```

答:
In the recursive steps, you send integers to ms_div. If you send the whole array it will compile.

So instead of

```<code>ms_div( B[mid_i], mid_i );
</code>```

Do this:

```<code>ms_div( B, mid_i );
</code>```

And same this for the ms_div( C[mid_i], mid_i ); call.

Title: Java, Arrays, Methods

Body:
The below method calls are giving error while compilation. I'm unable to understand why is it so. I'm passing the same parameters as defined in the method. Kindly help.

ms_div( B[mid_i], mid_i );
ms_div( C[mid_j], mid_j );

Code Starts Below:

void ms_div(int[] A, int nbr)
        {
            if (nbr > 2)
            {
                int mid_i = A.length / 2;
                int mid_j = A.length - mid_i;
                int[] B = new int[13];
                int[] C = new int[13];

                //create left hand array
                for(int i;i<=mid_i - 1;i++)
                {
                    B[i] = A[i];
                }

                //creating right hand array
                for(int i = 0,j=mid_i;i>= mid_j - 1;i++,j++)
                {
                    C[i] = A[j];
                }

                //Sort Left Hand Array
                if (mid_i >= 2)
                {
                    ms_div( B[mid_i], mid_i );
                }

                //Sort Right Hand Array
                {
                    ms_div( C[mid_j],mid_j );
                }
            }
    }

Body:
In the recursive steps, you send integers to ms_div. If you send the whole array it will compile.

So instead of

ms_div( B[mid_i], mid_i );

Do this:

ms_div( B, mid_i );

And same this for the ms_div( C[mid_i], mid_i ); call.


问:
How we can handle Multiple Type UITableViewCell
I have multiple type cell to show in UITableView.

I have five type of cell in UITableView. all cell show according the different service response data, if service data nil or empty then we will not need to show the cell. so how i can check the number of row and show the cell according the service response.

答:
The question could be better answered if you had provided the response. But for a generic approach, you can use numberOfSections method in combination with numberOfRows method.

Configure the numberOfSections method by the count of your responseData. And further you can assign numberOfRows in each section if there is data available for that section.


问:
Last line in console not overwrite
I want to overwrite the last line in the console for looping a specific row with changes.

For example:
I want to print to console
. then .. then ...

This my code for that:

```<code>int dot = 1;
    while (true)
    {
        switch (dot)
        {
            case 1:
                Console.SetCursorPosition(0, Console.CursorTop-1);
                Console.WriteLine(".");
                dot++;
                Thread.Sleep(500);
                break;
            case 2:
                Console.SetCursorPosition(0, Console.CursorTop -1);
                Console.WriteLine("..");
                dot++;
                Thread.Sleep(500);
                break;
            case 3:
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("...");
                dot = 1;
                Thread.Sleep(500);
                break;
        }
    }
}
</code>```

My problem is that after the first complete round(after it print the "..." in first time) it not print "." the console stay on "..."

I mean:

"." print

remove "." and print ".."

remove ".." and print "..."

now it stay "..." instead remove "..." and print ".".

Someone has idea why?

答:
You're only printing one character when you print a single dot - you're not affecting the rest of the line.

If you just change this:

```<code>Console.WriteLine(".");
</code>```

to

```<code>Console.WriteLine(".  ");
</code>```

then it'll remove any characters written by previous iterations. (That still won't clear anything else on the line though.)

(You may want to change the Console.WriteLine("..") to Console.WriteLine(".. ") for consistency but it won't make a difference as you've already printed the final space in the previous iteration.)

Note that you can remove repetition fairly simply too:

```<code>string[] dots = { ".  ", "..", "..." };
int index = 0;
while (true)
{
    Console.SetCursorPosition(0, Console.CursorTop -1);
    Console.WriteLine(dots[index]);
    index = (index + 1) % 3;
    Thread.Sleep(500);
}
</code>```

Title: Last line in console not overwrite

Body:
I want to overwrite the last line in the console for looping a specific row with changes.

For example:
I want to print to console
. then .. then ...

This my code for that:

int dot = 1;
    while (true)
    {
        switch (dot)
        {
            case 1:
                Console.SetCursorPosition(0, Console.CursorTop-1);
                Console.WriteLine(".");
                dot++;
                Thread.Sleep(500);
                break;
            case 2:
                Console.SetCursorPosition(0, Console.CursorTop -1);
                Console.WriteLine("..");
                dot++;
                Thread.Sleep(500);
                break;
            case 3:
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("...");
                dot = 1;
                Thread.Sleep(500);
                break;
        }
    }
}

My problem is that after the first complete round(after it print the "..." in first time) it not print "." the console stay on "..."

I mean:

"." print

remove "." and print ".."

remove ".." and print "..."

now it stay "..." instead remove "..." and print ".".

Someone has idea why?

Body:
You're only printing one character when you print a single dot - you're not affecting the rest of the line.

If you just change this:

Console.WriteLine(".");

to

Console.WriteLine(".  ");

then it'll remove any characters written by previous iterations. (That still won't clear anything else on the line though.)

(You may want to change the Console.WriteLine("..") to Console.WriteLine(".. ") for consistency but it won't make a difference as you've already printed the final space in the previous iteration.)

Note that you can remove repetition fairly simply too:

string[] dots = { ".  ", "..", "..." };
int index = 0;
while (true)
{
    Console.SetCursorPosition(0, Console.CursorTop -1);
    Console.WriteLine(dots[index]);
    index = (index + 1) % 3;
    Thread.Sleep(500);
}


问:
Javascript showing number with leading zero
I am new to javascript, while i was trying to test an example with below code,
Code:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the following button to call the function</p>
<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p></code>```

i am sending parameter as 'abc' and 010. But  in output I am getting like below,

Output:
abc is 8 years old

答:
Javacript engines interpret leading zeros as octal number literals.It is defined in an appendix of EMCA Spec
010 becomes 8 * 1 = 8.</p>

Body:
I am new to javascript, while i was trying to test an example with below code,
Code:

function sayHello(name, age) {
  document.write (name + " is " + age + " years old.");
}

Click the following button to call the function

<form>
   <input type="button" onclick="sayHello('abc', 010)" value="Say Hello">
</form>

Use different parameters inside the function and then try...

i am sending parameter as 'abc' and 010. But  in output I am getting like below,

Output:
abc is 8 years old


问:
How to remove all items in RecyclerView Adapter with Animation
I want to delete one item if user swipe, and delete all items in RecyclerView if user click deleteAll button, I try to access each viewholder an add a Animation but I don't now how, I add Animation in creation because the adapter give me each view holder in onBindViewHolder, this is my adapter

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
List<String> stringList;
public MyAdapter(Context context, List<String> stringList) {
    this.context = context;
    this.stringList = stringList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context)
            .inflate(R.layout.item,parent,false);

    MyViewHolder viewHolder = new MyViewHolder(view);
    return viewHolder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
    holder.itemView.startAnimation(animation);
    holder.bind(stringList.get(position));
}

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

public void dismiss(int adapterPosition) {
            stringList.remove(adapterPosition);
            this.notifyItemRemoved(adapterPosition);
    }

public void removeItem(int position) {
    this.stringList.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, getItemCount() - position);
}

class MyViewHolder extends RecyclerView.ViewHolder
        implements View.OnClickListener {
    TextView textView;
    String data;
    public MyViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.text);
        itemView.setOnClickListener(this);
    }
    public void bind(String data) {
        this.data = data;
        textView.setText(data);
    }

    @Override
    public void onClick(View view) {
        stringList.remove(data);
        notifyDataSetChanged();
    }

}}
</code>```

my RecyclerView and adapter in main activity and how i handle delete all, but the problem is how I can add Animation

```<code>  adapter = new MyAdapter(this,myList);
    ItemTouchHelper.Callback callback = new SwipeHelper(adapter);
    ItemTouchHelper helper = new ItemTouchHelper(callback);
    recyclerView.setAdapter(adapter);
    helper.attachToRecyclerView(recyclerView);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = myList.size()-1 ; i >= 0 ; i--){
                adapter.removeItem(i);
            }
            //recyclerView.removeItemDecoration();
        }
    });
</code>```

答:
You can use Threads and delay in each loops to remove/restore items one by one. Here's how I have implemented:

MainActivity.java

```<code>clearItemsView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final List<LineItem> lineItemsCopy = new ArrayList<>(lineItems);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<lineItemsCopy.size(); i++) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                salesOrderItemListAdapter.removeItem(0);
                            }
                        });
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            Snackbar snackbar = Snackbar.make(coordinatorLayout, getString(R.string.items_cleared_message), Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.label_undo), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i=0; i<lineItemsCopy.size(); i++) {
                                        final int finalI = i;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                salesOrderItemListAdapter.restoreItem(lineItemsCopy.get(finalI), 0);
                                            }
                                        });
                                        try {
                                            Thread.sleep(500);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }).start();
                        }
                    }).setActionTextColor(Color.YELLOW);
            snackbar.show();
        }
    });
</code>```

RecyclerViewAdapter.java

```<code>    //Only remove & restore functions are shown
    public void removeItem(int position) {
        lineItems.remove(position);
        notifyItemRemoved(position);
    }

    public void restoreItem(LineItem item, int position) {
        lineItems.add(position, item);
        notifyItemInserted(position);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to delete one item if user swipe, and delete all items in RecyclerView if user click deleteAll button, I try to access each viewholder an add a Animation but I don't now how, I add Animation in creation because the adapter give me each view holder in onBindViewHolder, this is my adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
List<String> stringList;
public MyAdapter(Context context, List<String> stringList) {
    this.context = context;
    this.stringList = stringList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context)
            .inflate(R.layout.item,parent,false);

    MyViewHolder viewHolder = new MyViewHolder(view);
    return viewHolder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
    holder.itemView.startAnimation(animation);
    holder.bind(stringList.get(position));
}

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

public void dismiss(int adapterPosition) {
            stringList.remove(adapterPosition);
            this.notifyItemRemoved(adapterPosition);
    }

public void removeItem(int position) {
    this.stringList.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, getItemCount() - position);
}

class MyViewHolder extends RecyclerView.ViewHolder
        implements View.OnClickListener {
    TextView textView;
    String data;
    public MyViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.text);
        itemView.setOnClickListener(this);
    }
    public void bind(String data) {
        this.data = data;
        textView.setText(data);
    }

    @Override
    public void onClick(View view) {
        stringList.remove(data);
        notifyDataSetChanged();
    }

}}

my RecyclerView and adapter in main activity and how i handle delete all, but the problem is how I can add Animation

  adapter = new MyAdapter(this,myList);
    ItemTouchHelper.Callback callback = new SwipeHelper(adapter);
    ItemTouchHelper helper = new ItemTouchHelper(callback);
    recyclerView.setAdapter(adapter);
    helper.attachToRecyclerView(recyclerView);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = myList.size()-1 ; i >= 0 ; i--){
                adapter.removeItem(i);
            }
            //recyclerView.removeItemDecoration();
        }
    });

Body:
You can use Threads and delay in each loops to remove/restore items one by one. Here's how I have implemented:

MainActivity.java

clearItemsView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final List<LineItem> lineItemsCopy = new ArrayList<>(lineItems);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<lineItemsCopy.size(); i++) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                salesOrderItemListAdapter.removeItem(0);
                            }
                        });
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
            Snackbar snackbar = Snackbar.make(coordinatorLayout, getString(R.string.items_cleared_message), Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.label_undo), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i=0; i<lineItemsCopy.size(); i++) {
                                        final int finalI = i;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                salesOrderItemListAdapter.restoreItem(lineItemsCopy.get(finalI), 0);
                                            }
                                        });
                                        try {
                                            Thread.sleep(500);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }).start();
                        }
                    }).setActionTextColor(Color.YELLOW);
            snackbar.show();
        }
    });

RecyclerViewAdapter.java

    //Only remove & restore functions are shown
    public void removeItem(int position) {
        lineItems.remove(position);
        notifyItemRemoved(position);
    }

    public void restoreItem(LineItem item, int position) {
        lineItems.add(position, item);
        notifyItemInserted(position);
    }


问:
Scenarios where automated testing is unhelpful
What are some situations where unit testing and TDD and the like are more trouble than they're worth?

Some things I've come up with are:

When generating test data is tricky: Sometimes, being able to come up with valid, non trivial test data is a challenge in itself.

When the only practical way of verifying correctness of the code is to run it.

When you're testing visual elements of the design.

What are some other cases?

答:
Just some random thoughts on this:

I assume Microsoft does not have a
Unit-Test for it's various ways of
shutting down a computer. Could be
done with Virtuals, but it's
probably not worth it

For Hardware Makers: Ensuring that drivers work for different hardware
is probably done manually, too (hi
there nvidia, you broke my gfx card
;) )

Run-once shell scripts. Just tweak them till they work

But still those are corner cases. I also think they are almost always possible and usually pay you back more in the long run than you invested at the beginning.

OwnerDisplayName: Shalmanese

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Lemmy


问:
Xcode: "iOS Deployment Target" not available in "Debug" configuration
so - for an iPhone project in Xcode (version 3.2.4) the project settings offer settings for "Base SDK" as well as "iOS Deployment Target" - the later of which determines what's the lowest iOS version to be supported.

however - this "iOS Deployment Target" option is shown to me only in the "Release" configuration. When I switch to "Debug" this option disappears and minimum iOS version required seems to be automatically set to the same as Base SDK.

The problem is that my iPhone runs on iOS 3.1.2 (and I want it to stay on this version!) - but the recent Xcode versions don't have Base SDK options for these older versions (lowest available Base SDK is 3.2) - so I need the "iOS Deployment Target" option to make it compatible with my phone.

how can I make this option available in Debug Configuration?

答:
You need to install an older SDK to run anything prior to 3.2, but don't uninstall your latest. Just put the older version in a directory other than /Developer, I use /Xcode personally. Code normally in the new version, then open the older SDK to test your app on your phone.

Most users are 4.0 or above though, so keep that in mind when trying to make your app backwards compatible (stats from major apps on Quora).


问:
KIF output: AX Exchange error: Error Domain=Accessibility Code=0 "Remote service does not respond to _accessibilityMachPort"
When running KIF integration tests on device with iOS 8.1.3 I get lots of diagnostic messages of the following kind as console output:

AX Exchange error: Error Domain=Accessibility Code=0 "Remote service
  does not respond to _accessibilityMachPort" UserInfo=0x1a55de50
  {NSLocalizedDescription=Remote service does not respond to
  _accessibilityMachPort}

This occurs during a call to waitForAccessibilityElement:view:withElementMatchingPredicate:tappable:.

Otherwise testing works as expected, it just seems a bit verbose. So I am wondering: is this kind of diagnostic output a feature or a bug? How can it be explained? What can or should I do about it, if anything?

答: For people working with Xamarin.iOS, disabling Xamarin.Calabash.Start(); // For Test Cloud suspends the non-stop logging


答:
While writing to console you replace characters but on first run there is nothing to replace so you see the change. On second loop you replace first dot with new dot and that does not produce a change on the screen. The simplest way to fix it would be to add spaces after dot to your first strings so that is is 3 characters long:</p>

```<code>".  "
</code>```

Title: Last line in console not overwrite

Body:
While writing to console you replace characters but on first run there is nothing to replace so you see the change. On second loop you replace first dot with new dot and that does not produce a change on the screen. The simplest way to fix it would be to add spaces after dot to your first strings so that is is 3 characters long:

".  "


问:
DataGrid for Android
Hello i want to build an Android application to handle my budget. I have build an budget-app before but that was in WPF and with C#. In WPF there is something called DataGrid that looks something like this

https://www.codeproject.com/KB/WPF/WPFDataGridExamples/datasetgrid.png
(I am not allowed to post images)

And i was wondering if there was something like this in Android, that could display a table of information to the user.

Thank you.

答:
As Leuteris said you can use Grid View.

But you should try to think about new design of your UI - use ideas from desktop clients in mobile application is not a very good idea.

Title: DataGrid for Android


问:
How can I use maven's aggregation and inheritance to collect jars from child modules into parent's tarball
I have a multimodule maven project with following structure:

```<code>root module
            module A
            module B
            module C
                     module C-1
                     module C-2
</code>```

Module C is new in this project. Its goal is to define shared dependencies for sub-modules C-1 and C-2 (that is to be parent to them) and to aggregate jars that modules C-1 and C-2 build into single tar ball in module's C target directory.

This goal is achieved by:

root pom.xml lists modules A, B, and C

module C pom.xmllists modules C-1 and C-2 and declares shared dependencies; it also declares packaging as "pom"

maven-assembly-plugin is used in modules C to find all *.jar files in it's children's target directory and pack them in tgz.

There are couple of problems I face with this implementation. Simple one was self-dependency of C-1 and C-2 - they inherit dependency to itself from C and hence refuse to compile. I addressed that wrapping dependencies into dependencyManagement in C. So looks like it's working.

I also do still have problem with Assembly plugin. When using wildchars in fileset values it preserves the directory structure in resulting tar ball and looks like you can't do anything about it. So having following in bin.xml of module C

```<code>    <fileSet>
        <directory>${project.basedir}</directory>
        <outputDirectory>/</outputDirectory>
        <includes>
            <include>**/*.jar</include>
        </includes>
        <excludes>
            <exclude>**/*-javadoc.jar</exclude>
        </excludes>

    </fileSet>
</code>```

results in tarball having structure

```<code>moduleC-version/moduleC-1/target/moduleC-1-version.jar
moduleC-version/moduleC-2/target/moduleC-2-version.jar
</code>```

when I need just

```<code>moduleC-version/moduleC-1-version.jar
moduleC-version/moduleC-2-version.jar
</code>```

Okey, that's not too important. The main problem is Reactor Build Order. Whatever I do it results in

module A

module B

module C

module C-1

module C-2

And that's a failure since build on module C complains

Failed to create assembly: Error creating assembly archive bin: You must set at least one file. -> [Help 1]

My understanding is that the problem is in the sequence of Reactor Build Order - C-1 and C-2 should be built before C, - but I can't get how to manage it having C a parent to them and keeping on top of the module structure.

答:
If you need to have a distribution like package (zip for example) you have to define a separate module which contains the configuration for it.
Furthermore you need to define each module you would like to be packaged into as a dependency to make sure the build order is done correctly by maven.

The maven-assembly-plugin descriptor you have to use looks like this:

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">

  <id>dist-assembly</id>

  <formats>
      <format>zip</format>
  </formats>

  <includeBaseDirectory>false</includeBaseDirectory>

  <dependencySets>
      <dependencySet>
          <outputDirectory>/</outputDirectory>
          <useProjectArtifact>false</useProjectArtifact>
          <unpack>false</unpack>
          <scope>runtime</scope>
      </dependencySet>
  </dependencySets>
</assembly>
```

<p>The structure of the projects looks more or like this:</p>

```+- pom.xml
+-- mod1
+-- mod2
+-- dist
```

<p>Update:</p>

<p>If you need only the modules you can this as assembly descriptor instead:</p>

<pre class="lang-xml prettyprint-override"><code>  <moduleSets>
    <moduleSet>
      <useAllReactorProjects>true</useAllReactorProjects>
      <binaries>
        <outputDirectory>modules</outputDirectory>
        <unpack>false</unpack>
      </binaries>
    </moduleSet>
</moduleSets>
</code>```

Body:
I have a multimodule maven project with following structure:

root module
            module A
            module B
            module C
                     module C-1
                     module C-2

Module C is new in this project. Its goal is to define shared dependencies for sub-modules C-1 and C-2 (that is to be parent to them) and to aggregate jars that modules C-1 and C-2 build into single tar ball in module's C target directory.

This goal is achieved by:

root pom.xml lists modules A, B, and C

module C pom.xmllists modules C-1 and C-2 and declares shared dependencies; it also declares packaging as "pom"

maven-assembly-plugin is used in modules C to find all *.jar files in it's children's target directory and pack them in tgz.

There are couple of problems I face with this implementation. Simple one was self-dependency of C-1 and C-2 - they inherit dependency to itself from C and hence refuse to compile. I addressed that wrapping dependencies into dependencyManagement in C. So looks like it's working.

I also do still have problem with Assembly plugin. When using wildchars in fileset values it preserves the directory structure in resulting tar ball and looks like you can't do anything about it. So having following in bin.xml of module C

    <fileSet>
        <directory>${project.basedir}</directory>
        <outputDirectory>/</outputDirectory>
        <includes>
            <include>**/*.jar</include>
        </includes>
        <excludes>
            <exclude>**/*-javadoc.jar</exclude>
        </excludes>

    </fileSet>

results in tarball having structure

moduleC-version/moduleC-1/target/moduleC-1-version.jar
moduleC-version/moduleC-2/target/moduleC-2-version.jar

when I need just

moduleC-version/moduleC-1-version.jar
moduleC-version/moduleC-2-version.jar

Okey, that's not too important. The main problem is Reactor Build Order. Whatever I do it results in

module A

module B

module C

module C-1

module C-2

And that's a failure since build on module C complains

Failed to create assembly: Error creating assembly archive bin: You must set at least one file. -> [Help 1]

My understanding is that the problem is in the sequence of Reactor Build Order - C-1 and C-2 should be built before C, - but I can't get how to manage it having C a parent to them and keeping on top of the module structure.

Body:
If you need to have a distribution like package (zip for example) you have to define a separate module which contains the configuration for it.
Furthermore you need to define each module you would like to be packaged into as a dependency to make sure the build order is done correctly by maven.

The maven-assembly-plugin descriptor you have to use looks like this:

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">

  <id>dist-assembly</id>

  <formats>
      <format>zip</format>
  </formats>

  <includeBaseDirectory>false</includeBaseDirectory>

  <dependencySets>
      <dependencySet>
          <outputDirectory>/</outputDirectory>
          <useProjectArtifact>false</useProjectArtifact>
          <unpack>false</unpack>
          <scope>runtime</scope>
      </dependencySet>
  </dependencySets>
</assembly>

The structure of the projects looks more or like this:

+- pom.xml
+-- mod1
+-- mod2
+-- dist

Update:

If you need only the modules you can this as assembly descriptor instead:

  <moduleSets>
    <moduleSet>
      <useAllReactorProjects>true</useAllReactorProjects>
      <binaries>
        <outputDirectory>modules</outputDirectory>
        <unpack>false</unpack>
      </binaries>
    </moduleSet>
</moduleSets>


问:
Convolution of 3D numpy arrays
I've got a code from my supervisor to implement MDCT polyphase analysis and synthesis. Unfortunately, this code includes one very slow function with 2 loops. If somebody can help me to simplify this function and make it faster I will appreciate your help. This is part of the code:</p>

```<code>def polmatmult(A, B):
    """polmatmult(A,B)
    multiplies two polynomial matrices (arrays) A and B, where each matrix entry is a polynomial.
    Those polynomial entries are in the 3rd dimension
    The third dimension can also be interpreted as containing the (2D) coefficient matrices of exponent of z^-1.
    Result is C=A*B;"""

    print("np.shape(A)", np.shape(A))
    print("np.shape(B)", np.shape(B))
    [NAx, NAy, NAz] = np.shape(A);
    [NBx, NBy, NBz] = np.shape(B);

    "Degree +1 of resulting polynomial, with NAz-1 and NBz-1 being the degree of the input  polynomials:"

    Deg = NAz + NBz - 1;
    print("Deg", Deg)
    C = np.zeros((NAx, NBy, Deg));

    "Convolution of matrices:"
    for n in range(0, (Deg)):
        for m in range(0, n + 1):
            if ((n - m) < NAz and m < NBz):
                C[:, :, n] = C[:, :, n] + np.dot(A[:, :, (n - m)], B[:, :, m]);

    return C
</code>```

答:
A little manipulation to allow easier dot products and ufuc_at manipulation to remove the for loops:

```<code>def polmatmult_(A, B):
    print("np.shape(A)", np.shape(A))
    print("np.shape(B)", np.shape(B))
    [NAx, NAy, NAz] = np.shape(A)
    [NBx, NBy, NBz] = np.shape(B)

    Deg = NAz + NBz - 1
    print("Deg", Deg)
    C = np.zeros((Deg, NAx, NBy))

    m, n = np.triu_indices(NBz, 0, Deg)
    m, n = m[n - m < NAz], n[n - m < NAz]
    np.add.at(C, n,  np.moveaxis(A[:, :, (n - m)], -1, 0) @ np.moveaxis(B[:, :, m], -1, 0))

    return np.moveaxis(C, 0, -1)
</code>```

In general, you want your indexing axis (z in ths case) to be the first dimension and not the last.  This lets you use ufunc tricks (like add.at), @ instead of np.dot, and broadcasting.  Thus all the np.moveaxis.

Title: Convolution of 3D numpy arrays

Body:
I've got a code from my supervisor to implement MDCT polyphase analysis and synthesis. Unfortunately, this code includes one very slow function with 2 loops. If somebody can help me to simplify this function and make it faster I will appreciate your help. This is part of the code:

def polmatmult(A, B):
    """polmatmult(A,B)
    multiplies two polynomial matrices (arrays) A and B, where each matrix entry is a polynomial.
    Those polynomial entries are in the 3rd dimension
    The third dimension can also be interpreted as containing the (2D) coefficient matrices of exponent of z^-1.
    Result is C=A*B;"""

    print("np.shape(A)", np.shape(A))
    print("np.shape(B)", np.shape(B))
    [NAx, NAy, NAz] = np.shape(A);
    [NBx, NBy, NBz] = np.shape(B);

    "Degree +1 of resulting polynomial, with NAz-1 and NBz-1 being the degree of the input  polynomials:"

    Deg = NAz + NBz - 1;
    print("Deg", Deg)
    C = np.zeros((NAx, NBy, Deg));

    "Convolution of matrices:"
    for n in range(0, (Deg)):
        for m in range(0, n + 1):
            if ((n - m) < NAz and m < NBz):
                C[:, :, n] = C[:, :, n] + np.dot(A[:, :, (n - m)], B[:, :, m]);

    return C

Body:
A little manipulation to allow easier dot products and ufuc_at manipulation to remove the for loops:

def polmatmult_(A, B):
    print("np.shape(A)", np.shape(A))
    print("np.shape(B)", np.shape(B))
    [NAx, NAy, NAz] = np.shape(A)
    [NBx, NBy, NBz] = np.shape(B)

    Deg = NAz + NBz - 1
    print("Deg", Deg)
    C = np.zeros((Deg, NAx, NBy))

    m, n = np.triu_indices(NBz, 0, Deg)
    m, n = m[n - m < NAz], n[n - m < NAz]
    np.add.at(C, n,  np.moveaxis(A[:, :, (n - m)], -1, 0) @ np.moveaxis(B[:, :, m], -1, 0))

    return np.moveaxis(C, 0, -1)

In general, you want your indexing axis (z in ths case) to be the first dimension and not the last.  This lets you use ufunc tricks (like add.at), @ instead of np.dot, and broadcasting.  Thus all the np.moveaxis.


问:
Convert formatted string to datetime
I have a dataframe with a column that has been formatted as "%w-%U-%Y" (Weekday number-Week number-Year)

I'm currently doing the following to convert it to datetime format:

```<code>for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')
</code>```

Is there a more efficient way of doing this?

答:
You could use the map function:

```<code>df['DWY'] = list(map(lambda x: dt.strptime(x,'%w-%U-%Y'), df['DWY']))
</code>```

I personally like the way list comprehension work better:

```<code>df['DWY'] = [dt.strptime(entry, '%w-%U-%Y') for entry in df['DWY']]
</code>```

Title: Convert formatted string to datetime

Body:
I have a dataframe with a column that has been formatted as "%w-%U-%Y" (Weekday number-Week number-Year)

I'm currently doing the following to convert it to datetime format:

for i in df.index:
    df['DWY'][i] = dt.strptime(df['DWY'][i],'%w-%U-%Y')

Is there a more efficient way of doing this?

Body:
You could use the map function:

df['DWY'] = list(map(lambda x: dt.strptime(x,'%w-%U-%Y'), df['DWY']))

I personally like the way list comprehension work better:

df['DWY'] = [dt.strptime(entry, '%w-%U-%Y') for entry in df['DWY']]


问:
Correct way to use sizeThatFits: and sizeToFit with UILabel?
At the moment I have a label being sized correctly using [aString sizeWithFont:constrainedToSize:lineBreakMode:] but I've introduced rotation into my device and with a flexible width and height this results in my UILabel stretching width ways (because its set relative to the main view) but not then contracting height-wise to compensate for the extra space.

In another question I asked I was told to use sizeToFit and/or sizeThatFits: however I can't find any useful resource on the internet that tells me how to use this appropriately and trials I've done result in irrational behavior.

In a nutshell, lets say I have a structure like this:

```<code>UIView *innerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0)];
[innerView setAutoresizingMask:*flexible width and height*]
[innerView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:innerView];

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, innerView.frame.size.width-20, 0)];
[myLabel setAutoresizingMask:*flexible width and height*]
[myLabel setBackgroundColor:[UIColor blueColor]];
[myLabel setNumberOfLines:0];
[myLabel setLineBreakMode:UILineBreakModeWordWrap];
[innerView addSubview:myLabel];
</code>```

Thats a simplified version (also by way of disclaimer, this isn't my acctual code, I realise these elements will leak and everything else... this is just an example so you can see the structure).

Basically I have those two elements. Now on rotation they will both stretch to fit the new view size. What I need is a way to increase or decrease the height to fit the content dynamically. [aString sizeWithFont...] is only static. So how would I use sizeToFit or sizeThatFits to make this dynamic?

Thank you.

Tom

答:
Have you tried resetting the frame of your labels after the screen rotation?  Check the value of interfaceOrientation in:

```<code>- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
</code>```

Then, set the label's frame accordingly for each view mode inside didRotateFromInterfaceOrientation.

Here's an example of resizing label frames for string length: http://cocoamatic.blogspot.com/2010/08/uilabel-dynamic-sizing-based-on-string.html

Body:
At the moment I have a label being sized correctly using [aString sizeWithFont:constrainedToSize:lineBreakMode:] but I've introduced rotation into my device and with a flexible width and height this results in my UILabel stretching width ways (because its set relative to the main view) but not then contracting height-wise to compensate for the extra space.

In another question I asked I was told to use sizeToFit and/or sizeThatFits: however I can't find any useful resource on the internet that tells me how to use this appropriately and trials I've done result in irrational behavior.

In a nutshell, lets say I have a structure like this:

UIView *innerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0)];
[innerView setAutoresizingMask:*flexible width and height*]
[innerView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:innerView];

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, innerView.frame.size.width-20, 0)];
[myLabel setAutoresizingMask:*flexible width and height*]
[myLabel setBackgroundColor:[UIColor blueColor]];
[myLabel setNumberOfLines:0];
[myLabel setLineBreakMode:UILineBreakModeWordWrap];
[innerView addSubview:myLabel];

Thats a simplified version (also by way of disclaimer, this isn't my acctual code, I realise these elements will leak and everything else... this is just an example so you can see the structure).

Basically I have those two elements. Now on rotation they will both stretch to fit the new view size. What I need is a way to increase or decrease the height to fit the content dynamically. [aString sizeWithFont...] is only static. So how would I use sizeToFit or sizeThatFits to make this dynamic?

Thank you.

Tom

Body:
Have you tried resetting the frame of your labels after the screen rotation?  Check the value of interfaceOrientation in:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

Then, set the label's frame accordingly for each view mode inside didRotateFromInterfaceOrientation.

Here's an example of resizing label frames for string length: http://cocoamatic.blogspot.com/2010/08/uilabel-dynamic-sizing-based-on-string.html


问:
Difference between the move assignment operator and move constructor?
For some time this has been confusing me. And I've not been able to find a satisfactory answer thus far. The question is simple. When does a move assignment operator get called, and when does a move constructor operator get called?

The code examples on cppreference.com yield the following interesting results:

The move assignment operator:

```<code>a2 = std::move(a1); // move-assignment from xvalue
</code>```

The move constructor:

```<code>A a2 = std::move(a1); // move-construct from xvalue
</code>```

So has it do to with which is implemented? And if so which is executed if both are implemented? And why is there the possibility of creating a move assignment operator overload at all, if it's identical anyway.

答:
Move constructor is called during:

initialization: T a = std::move(b); or T a(std::move(b));, where b is of type T;

function argument passing: f(std::move(a));, where a is of type T and f is void f(T t);

Move assignment operation is called during:

function return: return a; inside a function such as T f(), where a is of type T which has a move constructor.

assignment

The following example code illustrates this :

```<code>#include <iostream>
#include <utility>
#include <vector>
#include <string>
using namespace std;
class A {
    public :
    A() { cout << "constructor called" << endl;}
    ~A() { cout << "destructor called" << endl;}
    A(A&&) {cout << "move constructor called"<< endl; return;}
    A& operator=(A&&) {cout << "move assignment operator called"<< endl; return *this;}

};
A fun() {
    A a; // 5. constructor called
    return a; // 6. move assignment operator called
    // 7. destructor called on this local a
}
void foo(A){
    return;
}
int main()
{
    A a; // 1. constructor called
    A b; // 2. constructor called
    A c{std::move(b)}; // 3. move constructor called
    c = std::move(a); // 4. move assignment operator called
    a = fun();
    foo(std::move(c)); // 8. move constructor called

}
</code>```

Output :

```<code>constructor called
constructor called
move constructor called
move assignment operator called
constructor called
move assignment operator called
destructor called
move constructor called
destructor called
destructor called
destructor called
destructor called
</code>```

Body:
For some time this has been confusing me. And I've not been able to find a satisfactory answer thus far. The question is simple. When does a move assignment operator get called, and when does a move constructor operator get called?

The code examples on cppreference.com yield the following interesting results:

The move assignment operator:

a2 = std::move(a1); // move-assignment from xvalue

The move constructor:

A a2 = std::move(a1); // move-construct from xvalue

So has it do to with which is implemented? And if so which is executed if both are implemented? And why is there the possibility of creating a move assignment operator overload at all, if it's identical anyway.

Body:
Move constructor is called during:

initialization: T a = std::move(b); or T a(std::move(b));, where b is of type T;

function argument passing: f(std::move(a));, where a is of type T and f is void f(T t);

Move assignment operation is called during:

function return: return a; inside a function such as T f(), where a is of type T which has a move constructor.

assignment

The following example code illustrates this :

#include <iostream>
#include <utility>
#include <vector>
#include <string>
using namespace std;
class A {
    public :
    A() { cout << "constructor called" << endl;}
    ~A() { cout << "destructor called" << endl;}
    A(A&&) {cout << "move constructor called"<< endl; return;}
    A& operator=(A&&) {cout << "move assignment operator called"<< endl; return *this;}

};
A fun() {
    A a; // 5. constructor called
    return a; // 6. move assignment operator called
    // 7. destructor called on this local a
}
void foo(A){
    return;
}
int main()
{
    A a; // 1. constructor called
    A b; // 2. constructor called
    A c{std::move(b)}; // 3. move constructor called
    c = std::move(a); // 4. move assignment operator called
    a = fun();
    foo(std::move(c)); // 8. move constructor called

}

Output :

constructor called
constructor called
move constructor called
move assignment operator called
constructor called
move assignment operator called
destructor called
move constructor called
destructor called
destructor called
destructor called
destructor called


问:
I am doing CRUD operation by using api.php from github and want to fetch id or name and save into a varibale
```<code>$response = call('GET','http://localhost/ProjectCamera/projectcamera/api.php/state');

$jsonObject = json_decode($response, true);

$jsonObject = php_crud_api_transform($jsonObject);

$output = json_encode($jsonObject, JSON_PRETTY_PRINT);

$state_id = $output->state_id;

print_r($state_id);

?>
</code>```

答:
Since $jsonObject is already an object you don't need to json_encode again with JSON_PRETTY_PRINT instead you should use json_decode($jsonObject) this will convert it to stdClass Object then you can access the state_id property/field.

you can try the below code.

```<code>$response = call('GET','http://localhost/ProjectCamera/projectcamera/api.php/state');

$jsonObject = json_decode($response, true);

$jsonObject = php_crud_api_transform($jsonObject);

//If $jsonObject is an JSON object otherwise
//If php_crud_api_transform is returning the array then you need to used json_encode but without JSON_PRETTY_PRINT

//BY passing true in json_decode second parameter will convert it to array
$output = json_decode(json_encode($jsonObject),true);

//you will get first state id
$state_id = $output['state'][0]['state_id'];

print_r($state_id);
</code>```

Body:
Since $jsonObject is already an object you don't need to json_encode again with JSON_PRETTY_PRINT instead you should use json_decode($jsonObject) this will convert it to stdClass Object then you can access the state_id property/field.

you can try the below code.

$response = call('GET','http://localhost/ProjectCamera/projectcamera/api.php/state');

$jsonObject = json_decode($response, true);

$jsonObject = php_crud_api_transform($jsonObject);

//If $jsonObject is an JSON object otherwise
//If php_crud_api_transform is returning the array then you need to used json_encode but without JSON_PRETTY_PRINT

//BY passing true in json_decode second parameter will convert it to array
$output = json_decode(json_encode($jsonObject),true);

//you will get first state id
$state_id = $output['state'][0]['state_id'];

print_r($state_id);