问:
How to fix java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
I am creating an android application that consists of a serial communication.I am getting an error called java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 please tell me how to fix it

This is my usb driver:

```<code>public class UsbDriver {

    private final Context mApplicationContext;
    private final UsbManager mUsbManager;
    @SuppressWarnings("unused")
    private final UsbConnectionHandler mConnectionHandler;
    private final int VID;
    private final int PID;
    protected static final String ACTION_USB_PERMISSION = "ch.serverbox.android.USB";
    public static int Device_Exception;
    public static UsbDevice Device_Details;
    public static UsbEndpoint Data_In_End_Point = null;
    public static UsbEndpoint Data_Out_End_Point = null;
    public static UsbDeviceConnection USB_Device_Connection;

    public UsbDriver(Activity parentActivity,UsbConnectionHandler connectionHandler, int vid, int pid) {
        mApplicationContext = parentActivity.getApplicationContext();
        mConnectionHandler = connectionHandler;
        mUsbManager = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
        VID = 1027;
        PID = 24577;
        Device_Exception = 0;
    //  init();
        Check_Devices();
    }

    private void Check_Devices() {
        @SuppressWarnings("unused")
        int j=0;
        HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviter = devlist.values().iterator();
        Device_Details = null;
        if (devlist.size() != 0) {
            while (deviter.hasNext()) {
                Device_Details = deviter.next();
                if (Device_Details.getVendorId() == VID && Device_Details.getProductId() == PID){
                    if (!mUsbManager.hasPermission(Device_Details)){
                        onPermissionDenied(Device_Details);
                    } else {
                        UsbDeviceConnection conn = mUsbManager.openDevice(Device_Details);
                        if (!conn.claimInterface(Device_Details.getInterface(1), true)){
                            return;
                        }

                        conn.controlTransfer(0x21, 34, 0, 0, null, 0, 0);
                        conn.controlTransfer(0x21, 32, 0, 0,new byte[] { (byte) 0x80, 0x25 , 0x00, 0x00,0x00, 0x00, 0x08 }, 7, 0);
                        USB_Device_Connection=conn;
                        Data_In_End_Point = null;
                        Data_Out_End_Point = null;

                        UsbInterface usbIf = Device_Details.getInterface(1);
                        for (int i = 0; i < usbIf.getEndpointCount(); i++) {
                            if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                                if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
                                    Data_In_End_Point = usbIf.getEndpoint(i);
                                else
                                    Data_Out_End_Point = usbIf.getEndpoint(i);
                            }
                        }
                        if (Data_In_End_Point == null || Data_Out_End_Point == null)
                            Device_Exception = 2;
                    }
                    break;
                }j++;
            }
            if (Device_Details == null) {
                Device_Exception = 3;
                return;
            }
        }
        else {
            Device_Exception = 1;
            return;
        }
    }

    public void onPermissionDenied(UsbDevice d) {
        UsbManager usbman = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
        PendingIntent pi = PendingIntent.getBroadcast(mApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        mApplicationContext.registerReceiver(mPermissionReceiver,new IntentFilter(ACTION_USB_PERMISSION));
        usbman.requestPermission(d, pi);
    }

    private class PermissionReceiver extends BroadcastReceiver {
        private final IPermissionListener mPermissionListener;

        public PermissionReceiver(IPermissionListener permissionListener){
            mPermissionListener = permissionListener;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            mApplicationContext.unregisterReceiver(this);
            if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
                if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    mPermissionListener.onPermissionDenied((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
                } else {
                    l("Permission granted");
                    UsbDevice dev = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (dev != null){
                        if (dev.getVendorId() == VID && dev.getProductId() == PID) {
                            Check_Devices() ;
                        }
                    }else{
                        e("device not present!");
                    }
                }
            }
        }
    }

    private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(new IPermissionListener() {
        @Override
        public void onPermissionDenied(UsbDevice d) {
            l("Permission denied on " + d.getDeviceId());
        }
    });

    private static interface IPermissionListener {
        void onPermissionDenied(UsbDevice d);
    }

    public final static String TAG = "USBController";

    private void l(Object msg) {
        Log.d(TAG, ">==<" + msg.toString() + " >==<");
    }

    private void e(Object msg) {
        Log.e(TAG, ">==< " + msg.toString() + " >==<");
    }
}
</code>```

This is my usb connection handler

```<code>public interface UsbConnectionHandler {
    void onUsbStopped();
    void onErrorLooperRunningAlready();
    void onDeviceNotFound();
}
</code>```

This is my main activity:

```<code>public class MainActivity extends Activity {
    EditText communication_data;
    Button send;

    public static final int targetVendorID = 1027;
    public static final int targetProductID = 24577;
    public  UsbManager manager;
    public  UsbDeviceConnection usbDeviceConnection;
    public  UsbInterface usbInterfaceFound = null;
    public  UsbEndpoint endpointOut = null;
    public  UsbEndpoint endpointIn = null;
    public  UsbDevice usbdevice,device_details;
    public  UsbEndpoint listusbendpoint;
    private static final int VID = 1027;
    private static final int PID = 24577;
    @SuppressWarnings("unused")
    private static UsbDriver Usb_Driver_class;
    ActionBar actionbar;
    UsbConnectionHandler connectionHandler;
    public static UsbDriver USB_Driver_Child;
    public static boolean Communication_Failed,Frame_Ok,Total_Frame_Decoded;
    static byte[] Communication_Byte;
    HashMap<String, UsbDevice> devicelist= null;
    static byte[] sample;
    static boolean Communication_Ok;
    static int Sequence_No,Response_Time;
    Thread Receive;
    ByteBuffer buffer;

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

        //communication_data = (EditText)findViewById(R.id.editText_comm);
        send = (Button)findViewById(R.id.button1_sendin);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Communication_Byte=new byte[1];
                if(Check_Devices_Available()==true) {
                    int Packet_Size = USB_Driver_Child.Data_In_End_Point.getMaxPacketSize();
                    Toast.makeText(MainActivity.this,""+Packet_Size, Toast.LENGTH_LONG).show();
                    Receive.start();
                    Communication_Ok=false;
                    for(int i=0;(i<5 && Communication_Ok!=true);i++)
                    Send_Communication_Check_Command();

                    if(Communication_Ok)
                        Toast.makeText(MainActivity.this, "Communication Successfully Established", 1000).show();
                    else
                        Toast.makeText(MainActivity.this, "Communication Failure", 10000).show();
                }
            }

            private boolean Check_Devices_Available() {
                Usb_Driver_class = new UsbDriver(MainActivity.this, connectionHandler, VID, PID);

                if(USB_Driver_Child.Device_Exception==0){
                    if(USB_Driver_Child.USB_Device_Connection==null || USB_Driver_Child.Data_Out_End_Point==null)
                        return false;

                    Toast.makeText(MainActivity.this,"Device Found", 1000).show();
                    return true;
                }else if(USB_Driver_Child.Device_Exception==1){
                    Toast.makeText(MainActivity.this,"No Devices Attached ", Toast.LENGTH_LONG).show();
                    return false;
                }else if(USB_Driver_Child.Device_Exception==2){
                    Toast.makeText(MainActivity.this,"Device Found,But No End Points", Toast.LENGTH_LONG).show();
                    return false;
                }else if(USB_Driver_Child.Device_Exception==3){
                    Toast.makeText(MainActivity.this,"Unable to Open Device", Toast.LENGTH_LONG).show();
                    return false;
                }
                return false;
            }

            Thread Receive  = new Thread(new Runnable(){

                @SuppressWarnings("unused")
                @Override
                public void run() {
                    Sequence_No=0;
                    buffer = ByteBuffer.allocate(64);
                    sample = new byte[64];
                    int Frame_Size;
                    UsbRequest request = new UsbRequest();
                    int i,j;
                    byte [] datarx=new byte[1];
                    char q;
                    while (true) {
                        request.initialize(UsbDriver.USB_Device_Connection, UsbDriver.Data_In_End_Point);
                        request.queue(buffer, 64);
                        if (UsbDriver.USB_Device_Connection.requestWait() == request) {
                            sample=buffer.array();
                            for(i=0;i<64;i++){
                                if(sample[i]=='&'){
                                    Communication_Ok=true;
                                    break;
                                }else if(sample[i]==0x03){
                                    if(sample[0]==0x02)
                                    //Frame_Ok=true;
                                    break;
                                }
                            }

                            if(Frame_Ok==true){
                                //Frame_Ok=false;
                                //if(sample[1]==1)
                                //Coil_No=1;
                                //else
                                //Coil_No=2;
                                //Response_Time= (int)(((sample[2]&0x00FF)<<8) + (sample[3]&0x00FF));

                                //Total_Frame_Decoded=true;
                                //sample = null;
                            }
                        }
                    }
                }
            });

            private void Send_Communication_Check_Command() {
                long i,j;
                Communication_Byte[0]='&';
                UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_Out_End_Point,Communication_Byte, 1, 0);
                for(i=0;(i<1000 && Communication_Ok!=true) ;i++)
                    for(j=0;(j<1000 && Communication_Ok!=true);j++);
            }
        });
    }

}
</code>```

This is my logcat:

```<code>E/AndroidRuntime(2452): FATAL EXCEPTION: main
E/AndroidRuntime(2452): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
E/AndroidRuntime(2452):     at android.hardware.usb.UsbDevice.getInterface(UsbDevice.java:155)
E/AndroidRuntime(2452):     at com.developer.milancomm.UsbDriver.Check_Devices(UsbDriver.java:74)
E/AndroidRuntime(2452):     at com.developer.milancomm.UsbDriver.<init>(UsbDriver.java:48)
E/AndroidRuntime(2452):     at com.developer.milancomm.MainActivity$1.Check_Devices_Available(MainActivity.java:86)
E/AndroidRuntime(2452):     at com.developer.milancomm.MainActivity$1.onClick(MainActivity.java:63)
E/AndroidRuntime(2452):     at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(2452):     at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(2452):     at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(2452):     at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2452):     at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2452):     at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(2452):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2452):     at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(2452):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(2452):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(2452):     at dalvik.system.NativeStart.main(Native Method)
</code>```

答: Make sure you set a size/length for the array</p>

Body:
I am creating an android application that consists of a serial communication.I am getting an error called java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 please tell me how to fix it

This is my usb driver:

public class UsbDriver {

    private final Context mApplicationContext;
    private final UsbManager mUsbManager;
    @SuppressWarnings("unused")
    private final UsbConnectionHandler mConnectionHandler;
    private final int VID;
    private final int PID;
    protected static final String ACTION_USB_PERMISSION = "ch.serverbox.android.USB";
    public static int Device_Exception;
    public static UsbDevice Device_Details;
    public static UsbEndpoint Data_In_End_Point = null;
    public static UsbEndpoint Data_Out_End_Point = null;
    public static UsbDeviceConnection USB_Device_Connection;

    public UsbDriver(Activity parentActivity,UsbConnectionHandler connectionHandler, int vid, int pid) {
        mApplicationContext = parentActivity.getApplicationContext();
        mConnectionHandler = connectionHandler;
        mUsbManager = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
        VID = 1027;
        PID = 24577;
        Device_Exception = 0;
    //  init();
        Check_Devices();
    }

    private void Check_Devices() {
        @SuppressWarnings("unused")
        int j=0;
        HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviter = devlist.values().iterator();
        Device_Details = null;
        if (devlist.size() != 0) {
            while (deviter.hasNext()) {
                Device_Details = deviter.next();
                if (Device_Details.getVendorId() == VID && Device_Details.getProductId() == PID){
                    if (!mUsbManager.hasPermission(Device_Details)){
                        onPermissionDenied(Device_Details);
                    } else {
                        UsbDeviceConnection conn = mUsbManager.openDevice(Device_Details);
                        if (!conn.claimInterface(Device_Details.getInterface(1), true)){
                            return;
                        }

                        conn.controlTransfer(0x21, 34, 0, 0, null, 0, 0);
                        conn.controlTransfer(0x21, 32, 0, 0,new byte[] { (byte) 0x80, 0x25 , 0x00, 0x00,0x00, 0x00, 0x08 }, 7, 0);
                        USB_Device_Connection=conn;
                        Data_In_End_Point = null;
                        Data_Out_End_Point = null;

                        UsbInterface usbIf = Device_Details.getInterface(1);
                        for (int i = 0; i < usbIf.getEndpointCount(); i++) {
                            if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                                if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
                                    Data_In_End_Point = usbIf.getEndpoint(i);
                                else
                                    Data_Out_End_Point = usbIf.getEndpoint(i);
                            }
                        }
                        if (Data_In_End_Point == null || Data_Out_End_Point == null)
                            Device_Exception = 2;
                    }
                    break;
                }j++;
            }
            if (Device_Details == null) {
                Device_Exception = 3;
                return;
            }
        }
        else {
            Device_Exception = 1;
            return;
        }
    }

    public void onPermissionDenied(UsbDevice d) {
        UsbManager usbman = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
        PendingIntent pi = PendingIntent.getBroadcast(mApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        mApplicationContext.registerReceiver(mPermissionReceiver,new IntentFilter(ACTION_USB_PERMISSION));
        usbman.requestPermission(d, pi);
    }

    private class PermissionReceiver extends BroadcastReceiver {
        private final IPermissionListener mPermissionListener;

        public PermissionReceiver(IPermissionListener permissionListener){
            mPermissionListener = permissionListener;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            mApplicationContext.unregisterReceiver(this);
            if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
                if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    mPermissionListener.onPermissionDenied((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
                } else {
                    l("Permission granted");
                    UsbDevice dev = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (dev != null){
                        if (dev.getVendorId() == VID && dev.getProductId() == PID) {
                            Check_Devices() ;
                        }
                    }else{
                        e("device not present!");
                    }
                }
            }
        }
    }

    private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(new IPermissionListener() {
        @Override
        public void onPermissionDenied(UsbDevice d) {
            l("Permission denied on " + d.getDeviceId());
        }
    });

    private static interface IPermissionListener {
        void onPermissionDenied(UsbDevice d);
    }

    public final static String TAG = "USBController";

    private void l(Object msg) {
        Log.d(TAG, ">==<" + msg.toString() + " >==<");
    }

    private void e(Object msg) {
        Log.e(TAG, ">==< " + msg.toString() + " >==<");
    }
}

This is my usb connection handler

public interface UsbConnectionHandler {
    void onUsbStopped();
    void onErrorLooperRunningAlready();
    void onDeviceNotFound();
}

This is my main activity:

public class MainActivity extends Activity {
    EditText communication_data;
    Button send;

    public static final int targetVendorID = 1027;
    public static final int targetProductID = 24577;
    public  UsbManager manager;
    public  UsbDeviceConnection usbDeviceConnection;
    public  UsbInterface usbInterfaceFound = null;
    public  UsbEndpoint endpointOut = null;
    public  UsbEndpoint endpointIn = null;
    public  UsbDevice usbdevice,device_details;
    public  UsbEndpoint listusbendpoint;
    private static final int VID = 1027;
    private static final int PID = 24577;
    @SuppressWarnings("unused")
    private static UsbDriver Usb_Driver_class;
    ActionBar actionbar;
    UsbConnectionHandler connectionHandler;
    public static UsbDriver USB_Driver_Child;
    public static boolean Communication_Failed,Frame_Ok,Total_Frame_Decoded;
    static byte[] Communication_Byte;
    HashMap<String, UsbDevice> devicelist= null;
    static byte[] sample;
    static boolean Communication_Ok;
    static int Sequence_No,Response_Time;
    Thread Receive;
    ByteBuffer buffer;

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

        //communication_data = (EditText)findViewById(R.id.editText_comm);
        send = (Button)findViewById(R.id.button1_sendin);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Communication_Byte=new byte[1];
                if(Check_Devices_Available()==true) {
                    int Packet_Size = USB_Driver_Child.Data_In_End_Point.getMaxPacketSize();
                    Toast.makeText(MainActivity.this,""+Packet_Size, Toast.LENGTH_LONG).show();
                    Receive.start();
                    Communication_Ok=false;
                    for(int i=0;(i<5 && Communication_Ok!=true);i++)
                    Send_Communication_Check_Command();

                    if(Communication_Ok)
                        Toast.makeText(MainActivity.this, "Communication Successfully Established", 1000).show();
                    else
                        Toast.makeText(MainActivity.this, "Communication Failure", 10000).show();
                }
            }

            private boolean Check_Devices_Available() {
                Usb_Driver_class = new UsbDriver(MainActivity.this, connectionHandler, VID, PID);

                if(USB_Driver_Child.Device_Exception==0){
                    if(USB_Driver_Child.USB_Device_Connection==null || USB_Driver_Child.Data_Out_End_Point==null)
                        return false;

                    Toast.makeText(MainActivity.this,"Device Found", 1000).show();
                    return true;
                }else if(USB_Driver_Child.Device_Exception==1){
                    Toast.makeText(MainActivity.this,"No Devices Attached ", Toast.LENGTH_LONG).show();
                    return false;
                }else if(USB_Driver_Child.Device_Exception==2){
                    Toast.makeText(MainActivity.this,"Device Found,But No End Points", Toast.LENGTH_LONG).show();
                    return false;
                }else if(USB_Driver_Child.Device_Exception==3){
                    Toast.makeText(MainActivity.this,"Unable to Open Device", Toast.LENGTH_LONG).show();
                    return false;
                }
                return false;
            }

            Thread Receive  = new Thread(new Runnable(){

                @SuppressWarnings("unused")
                @Override
                public void run() {
                    Sequence_No=0;
                    buffer = ByteBuffer.allocate(64);
                    sample = new byte[64];
                    int Frame_Size;
                    UsbRequest request = new UsbRequest();
                    int i,j;
                    byte [] datarx=new byte[1];
                    char q;
                    while (true) {
                        request.initialize(UsbDriver.USB_Device_Connection, UsbDriver.Data_In_End_Point);
                        request.queue(buffer, 64);
                        if (UsbDriver.USB_Device_Connection.requestWait() == request) {
                            sample=buffer.array();
                            for(i=0;i<64;i++){
                                if(sample[i]=='&'){
                                    Communication_Ok=true;
                                    break;
                                }else if(sample[i]==0x03){
                                    if(sample[0]==0x02)
                                    //Frame_Ok=true;
                                    break;
                                }
                            }

                            if(Frame_Ok==true){
                                //Frame_Ok=false;
                                //if(sample[1]==1)
                                //Coil_No=1;
                                //else
                                //Coil_No=2;
                                //Response_Time= (int)(((sample[2]&0x00FF)<<8) + (sample[3]&0x00FF));

                                //Total_Frame_Decoded=true;
                                //sample = null;
                            }
                        }
                    }
                }
            });

            private void Send_Communication_Check_Command() {
                long i,j;
                Communication_Byte[0]='&';
                UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_Out_End_Point,Communication_Byte, 1, 0);
                for(i=0;(i<1000 && Communication_Ok!=true) ;i++)
                    for(j=0;(j<1000 && Communication_Ok!=true);j++);
            }
        });
    }

}

This is my logcat:

E/AndroidRuntime(2452): FATAL EXCEPTION: main
E/AndroidRuntime(2452): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
E/AndroidRuntime(2452):     at android.hardware.usb.UsbDevice.getInterface(UsbDevice.java:155)
E/AndroidRuntime(2452):     at com.developer.milancomm.UsbDriver.Check_Devices(UsbDriver.java:74)
E/AndroidRuntime(2452):     at com.developer.milancomm.UsbDriver.<init>(UsbDriver.java:48)
E/AndroidRuntime(2452):     at com.developer.milancomm.MainActivity$1.Check_Devices_Available(MainActivity.java:86)
E/AndroidRuntime(2452):     at com.developer.milancomm.MainActivity$1.onClick(MainActivity.java:63)
E/AndroidRuntime(2452):     at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(2452):     at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(2452):     at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(2452):     at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2452):     at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2452):     at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(2452):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2452):     at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(2452):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(2452):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(2452):     at dalvik.system.NativeStart.main(Native Method)


来源: stackexchange

问:
How to convert map's keys from int to String in Flutter
I have a List of objects (this is an example of how the list would be filled by the user):

```<code>  List<Exercise> entreno = [
    Exercise(
      nombreEjercicio: 'Press Banca',
      serieData: [
        Serie(
          peso: '80',
          repes: '8',
        ),
        Serie(
          peso: '90',
          repes: '6',
        ),
      ],
    ),
  ];

class Exercise {
  String nombreEjercicio;
  List<Serie> serieData;

  Exercise({this.serieData, this.nombreEjercicio});
}

class Serie {
  String peso;
  String repes;
  String numSerie;

  Serie({this.peso, this.repes, this.numSerie});
}
</code>```

The thing is that I want to pass this List<Exercise> entreno to firestore as the setData(), so I created a function to change the List<Exercise> type to Map<String, dynamic>:

```<code>  Map<String, dynamic> entrenamientoToMap(List<Exercise> entreno) {
    return Map.fromIterable(
      entreno,
      key: (e) => e.nombreEjercicio,
      value: (e) {
        return [
          for (var n in e.serieData) {'repeticiones': n.repes, 'peso': n.peso}
        ].asMap();
      },
    );
  }
</code>```

With that I get something like this:

```<code>{Press Banca: {0: {repeticiones: 8, peso: 80}, 1: {repeticiones: 6, peso: 90}}}
</code>```

and this is just what I want to upload to firestore.

But I'm getting this error when trying to set this as the setData():

```<code>E/flutter (30304): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'int' is not a subtype of type 'String'
</code>```

I guess the problem is on asMap() because it gives int keys. Then, how can I convert map's keys from int to String so I can pass the data to firestore?.

答:
Yes, the .asMap() function returns Map<int, String> that is where your code crashes.

You can add one .forEach() right after getting the Map from .asMap() function which can convert the keys and store it as Map<String, String>.

Have a look at this code snippet:

```<code>  List<String> items = ["one", "two", "three"];
  Map<int, String> basicMap = items.asMap(); //keys as int
  Map<String, String> newMap = new Map<String, String>(); //keys as String

  basicMap.forEach((key, value) {
    newMap.putIfAbsent(key.toString(), () => value);
  });
</code>```

We can check that the keys are of type String using following loop:

```<code>  newMap.forEach((key, value){
    print(key is String);
  }); //prints true for all keys
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a List of objects (this is an example of how the list would be filled by the user):

  List<Exercise> entreno = [
    Exercise(
      nombreEjercicio: 'Press Banca',
      serieData: [
        Serie(
          peso: '80',
          repes: '8',
        ),
        Serie(
          peso: '90',
          repes: '6',
        ),
      ],
    ),
  ];

class Exercise {
  String nombreEjercicio;
  List<Serie> serieData;

  Exercise({this.serieData, this.nombreEjercicio});
}

class Serie {
  String peso;
  String repes;
  String numSerie;

  Serie({this.peso, this.repes, this.numSerie});
}

The thing is that I want to pass this List<Exercise> entreno to firestore as the setData(), so I created a function to change the List<Exercise> type to Map<String, dynamic>:

  Map<String, dynamic> entrenamientoToMap(List<Exercise> entreno) {
    return Map.fromIterable(
      entreno,
      key: (e) => e.nombreEjercicio,
      value: (e) {
        return [
          for (var n in e.serieData) {'repeticiones': n.repes, 'peso': n.peso}
        ].asMap();
      },
    );
  }

With that I get something like this:

{Press Banca: {0: {repeticiones: 8, peso: 80}, 1: {repeticiones: 6, peso: 90}}}

and this is just what I want to upload to firestore.

But I'm getting this error when trying to set this as the setData():

E/flutter (30304): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'int' is not a subtype of type 'String'

I guess the problem is on asMap() because it gives int keys. Then, how can I convert map's keys from int to String so I can pass the data to firestore?.

Body:
Yes, the .asMap() function returns Map<int, String> that is where your code crashes.

You can add one .forEach() right after getting the Map from .asMap() function which can convert the keys and store it as Map<String, String>.

Have a look at this code snippet:

  List<String> items = ["one", "two", "three"];
  Map<int, String> basicMap = items.asMap(); //keys as int
  Map<String, String> newMap = new Map<String, String>(); //keys as String

  basicMap.forEach((key, value) {
    newMap.putIfAbsent(key.toString(), () => value);
  });

We can check that the keys are of type String using following loop:

  newMap.forEach((key, value){
    print(key is String);
  }); //prints true for all keys


问:
MySQL not using PHP variables properly in Queries, replacing the variables with strings/integers works fine
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.

I have tried like this:

```<code>$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
</code>```

I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:

```<code>$PartNo =  $_POST['ManuPartNo’];

$BikeManufacturer =  $_POST['BikeManufacturer’];

$BikeModel =  $_POST['BikeModel’];

$BikeType =  $_POST['BikeType’];

$BikeWheel =  $_POST['BikeWheel’];

$BikeColour =  $_POST['BikeColour’];

$BikeSpeed =  $_POST['BikeSpeed’];

$BrakeType =  $_POST['BrakeType’];

$FrameGender =  $_POST['FrameGender’];

$AgeGroup =  $_POST['AgeGroup’];

$DistFeatures =  $_POST['DistFeatures’];

</code>```

These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'

I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.

This is all running on a plesk server.

答:
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.

```<code>// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";

$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

// Include db.php on every page where queries are executed and perform queries the following way

// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)

$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;

// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();

if($stmt){
    echo "Row inserted";
}else{
    echo "Error!";
}
</code>```

See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.

Body:
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.

I have tried like this:

$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";

I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:

$PartNo =  $_POST['ManuPartNo’];

$BikeManufacturer =  $_POST['BikeManufacturer’];

$BikeModel =  $_POST['BikeModel’];

$BikeType =  $_POST['BikeType’];

$BikeWheel =  $_POST['BikeWheel’];

$BikeColour =  $_POST['BikeColour’];

$BikeSpeed =  $_POST['BikeSpeed’];

$BrakeType =  $_POST['BrakeType’];

$FrameGender =  $_POST['FrameGender’];

$AgeGroup =  $_POST['AgeGroup’];

$DistFeatures =  $_POST['DistFeatures’];

These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'

I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.

This is all running on a plesk server.

Body:
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.

// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";

$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

// Include db.php on every page where queries are executed and perform queries the following way

// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)

$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;

// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();

if($stmt){
    echo "Row inserted";
}else{
    echo "Error!";
}

See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.


问:
reverse serialize() -jquery
I sent my data (json) for an ajax request with this code;

```<code>var formdata = $("#customForm").serialize();

            type: "post",
            dataType: "json",
            data: formdata,
</code>```

In the php file, there is possible reverse the serialize?

or i need to make  something like that: $pass = $_POST['pass']; for all fields?

thanks

答:
it sounds like you are headed in the right direction with your "or" statement.  The data should be available in the $_POST array without needing to "deserialize" anything.

EDIT

Try to name your input fields so that they all come into the post variable as an array:

```<code><input name="myformdata[first_name]" id="first_name" />
<input name="myformdata[last_name]" id="last_name" />
</code>```

Then in the post array you can access all the form data like:

```<code><?php $form_data_array = $_POST['myformdata']; ?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: reverse serialize() -jquery

Body:
I sent my data (json) for an ajax request with this code;

var formdata = $("#customForm").serialize();

            type: "post",
            dataType: "json",
            data: formdata,

In the php file, there is possible reverse the serialize?

or i need to make  something like that: $pass = $_POST['pass']; for all fields?

thanks

Body:
it sounds like you are headed in the right direction with your "or" statement.  The data should be available in the $_POST array without needing to "deserialize" anything.

EDIT

Try to name your input fields so that they all come into the post variable as an array:

<input name="myformdata[first_name]" id="first_name" />
<input name="myformdata[last_name]" id="last_name" />

Then in the post array you can access all the form data like:

<?php $form_data_array = $_POST['myformdata']; ?>


问:
Why is bind slower than a closure?
A previous poster asked Function.bind vs Closure in Javascript : how to choose?

and received this answer in part, which seems to indicate bind should be faster than a closure:

Scope traversal means, when you are reaching to grab a value
  (variable,object) that exists in a different scope, therefore
  additional overhead is added (code becomes slower to execute).

Using bind, you 're calling a function with an existing scope, so that
  scope traversal does not take place.

Two jsperfs suggest that bind is actually much, much slower than a closure.

This was posted as a comment to the above

And, I decided to write my own jsperf

So why is bind so much slower (70+% on chromium)?

Since it is not faster and closures can serve the same purpose, should bind be avoided?

答:
I just want to give a little bit of perspective here:

Note that while bind()ing is slow, calling the functions once bound is not!

My test code in Firefox 76.0 on Linux:

//Set it up.
q = function(r, s) {

};
r = {};
s = {};
a = [];
for (let n = 0; n < 1000000; ++n) {
  //Tried all 3 of these.
  //a.push(q);
  //a.push(q.bind(r));
  a.push(q.bind(r, s));
}

//Performance-testing.
s = performance.now();
for (let x of a) {
  x();
}
e = performance.now();
document.body.innerHTML = (e - s);```

So while it is true that .bind()ing can be some ~2X slower than not binding (I tested that too), the above code takes the same amount of time for all 3 cases (binding 0, 1, or 2 variables).

Personally, I don't care if the .bind()ing is slow in my current use case, I care about the performance of the code being called once those variables are already bound to the functions.

Title: Why is bind slower than a closure?

Body:
I just want to give a little bit of perspective here:

Note that while bind()ing is slow, calling the functions once bound is not!

My test code in Firefox 76.0 on Linux:

//Set it up.
q = function(r, s) {

};
r = {};
s = {};
a = [];
for (let n = 0; n < 1000000; ++n) {
  //Tried all 3 of these.
  //a.push(q);
  //a.push(q.bind(r));
  a.push(q.bind(r, s));
}

//Performance-testing.
s = performance.now();
for (let x of a) {
  x();
}
e = performance.now();
document.body.innerHTML = (e - s);

So while it is true that .bind()ing can be some ~2X slower than not binding (I tested that too), the above code takes the same amount of time for all 3 cases (binding 0, 1, or 2 variables).

Personally, I don't care if the .bind()ing is slow in my current use case, I care about the performance of the code being called once those variables are already bound to the functions.


问:
Resurrecting coefficients from simulated data in Poisson regression
I am trying to understand how to resurrect model estimates from simulated data in a poisson regressions. There are other similar posts on interpreting coefficients on StackExchange/CrossValidated (https://stats.stackexchange.com/questions/11096/how-to-interpret-coefficients-in-a-poisson-regression, https://stats.stackexchange.com/questions/128926/how-to-interpret-parameter-estimates-in-poisson-glm-results), but I think my question is different (although admittedly related). I am trying to resurrect known relationships in order to understand what is happening with the model. I am posting here instead of CrossValidated because I am thinking that it is less of statistical interpretation and more of how I would get a known / simulated relationship back via code.

Here are some simulated data y and x with known relationships to some response resp

```<code>set.seed(707)
x<-rnorm(10000,mean=5,sd=1)
y<-rnorm(10000,mean=5,sd=1)
resp<-(0.5*x+0.7*y-0.1*x*y) # where I define some relationships
</code>```

With a linear regression, it is very straight forward:

```<code>summary(lm(resp~y+x+y:x))
</code>```

The output shows the exact linear relationship between x, y, and the interaction.

```<code>Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  1.592e-14  1.927e-15  8.260e+00   <2e-16 ***
y            7.000e-01  3.795e-16  1.845e+15   <2e-16 ***
x            5.000e-01  3.800e-16  1.316e+15   <2e-16 ***
y:x         -1.000e-01  7.489e-17 -1.335e+15   <2e-16 ***
</code>```

Now, if I am interested in a poisson regression, I need integers, I just round, but keep the relationship between predictors and response:

```<code>resp<-round((0.5*x+0.7*y-0.1*x*y),0)
glm1<-glm(resp~y+x+y:x,family=poisson())
summary(glm1)

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.419925   0.138906   3.023   0.0025 **
y            0.163919   0.026646   6.152 7.66e-10 ***
x            0.056689   0.027375   2.071   0.0384 *
y:x         -0.011020   0.005261  -2.095   0.0362 *
</code>```

It is my understanding that one needs to exponentiate the results to understand them, because of the link function. But here, neither the exponentiated estimate nor intercept + estimate get me back to the original values.

```<code>> exp(0.419925+0.163919)
[1] 1.792917
> exp(0.163919)
[1] 1.178119
</code>```

How do I interpret these values as related to the original 0.7*y relationship?

Now if I put that same linear equation into the exponential function, I get the values directly - no need to use exp():

```<code>resp<-round(exp(0.5*x+0.7*y-0.1*x*y),0)
summary(glm(resp~y+x+y:x,family=poisson()))
Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.002970   0.045422   0.065    0.948
y            0.699539   0.008542  81.894   <2e-16 ***
x            0.499476   0.008912  56.047   <2e-16 ***
y:x         -0.099922   0.001690 -59.121   <2e-16 ***
</code>```

Can someone explain to me what I am misinterpreting here, and how I might find the original values of a known relationship without first using the exp() function, as above?

答:
You're neglecting the fact that the Poisson GLM uses a log link (exponential inverse-link) by default (or rather, you're not using that information consistently). You should either generate your 'data' with an exponential inverse-link:

```<code>resp <- round(exp(0.5*x+0.7*y-0.1*x*y))
</code>```

or fit the model with an identity link (family=poisson(link="identity")).  (I wouldn't recommend the latter, as it is rarely a sensible model.)

For what it's worth, it's harder to simulate Poisson data that will exactly match a specified set of parameters, because (unlike the Gaussian where you can reduce the variance to arbitrarily small values) you can't generate real Poisson data with arbitrarily little noise. (Your round() statement produces integers, but not Poisson-distributed outcomes.)

Body:
I am trying to understand how to resurrect model estimates from simulated data in a poisson regressions. There are other similar posts on interpreting coefficients on StackExchange/CrossValidated (https://stats.stackexchange.com/questions/11096/how-to-interpret-coefficients-in-a-poisson-regression, https://stats.stackexchange.com/questions/128926/how-to-interpret-parameter-estimates-in-poisson-glm-results), but I think my question is different (although admittedly related). I am trying to resurrect known relationships in order to understand what is happening with the model. I am posting here instead of CrossValidated because I am thinking that it is less of statistical interpretation and more of how I would get a known / simulated relationship back via code.

Here are some simulated data y and x with known relationships to some response resp

set.seed(707)
x<-rnorm(10000,mean=5,sd=1)
y<-rnorm(10000,mean=5,sd=1)
resp<-(0.5*x+0.7*y-0.1*x*y) # where I define some relationships

With a linear regression, it is very straight forward:

summary(lm(resp~y+x+y:x))

The output shows the exact linear relationship between x, y, and the interaction.

Coefficients:
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  1.592e-14  1.927e-15  8.260e+00   <2e-16 ***
y            7.000e-01  3.795e-16  1.845e+15   <2e-16 ***
x            5.000e-01  3.800e-16  1.316e+15   <2e-16 ***
y:x         -1.000e-01  7.489e-17 -1.335e+15   <2e-16 ***

Now, if I am interested in a poisson regression, I need integers, I just round, but keep the relationship between predictors and response:

resp<-round((0.5*x+0.7*y-0.1*x*y),0)
glm1<-glm(resp~y+x+y:x,family=poisson())
summary(glm1)

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.419925   0.138906   3.023   0.0025 **
y            0.163919   0.026646   6.152 7.66e-10 ***
x            0.056689   0.027375   2.071   0.0384 *
y:x         -0.011020   0.005261  -2.095   0.0362 *

It is my understanding that one needs to exponentiate the results to understand them, because of the link function. But here, neither the exponentiated estimate nor intercept + estimate get me back to the original values.

> exp(0.419925+0.163919)
[1] 1.792917
> exp(0.163919)
[1] 1.178119

How do I interpret these values as related to the original 0.7*y relationship?

Now if I put that same linear equation into the exponential function, I get the values directly - no need to use exp():

resp<-round(exp(0.5*x+0.7*y-0.1*x*y),0)
summary(glm(resp~y+x+y:x,family=poisson()))
Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.002970   0.045422   0.065    0.948
y            0.699539   0.008542  81.894   <2e-16 ***
x            0.499476   0.008912  56.047   <2e-16 ***
y:x         -0.099922   0.001690 -59.121   <2e-16 ***

Can someone explain to me what I am misinterpreting here, and how I might find the original values of a known relationship without first using the exp() function, as above?

Body:
You're neglecting the fact that the Poisson GLM uses a log link (exponential inverse-link) by default (or rather, you're not using that information consistently). You should either generate your 'data' with an exponential inverse-link:

resp <- round(exp(0.5*x+0.7*y-0.1*x*y))

or fit the model with an identity link (family=poisson(link="identity")).  (I wouldn't recommend the latter, as it is rarely a sensible model.)

For what it's worth, it's harder to simulate Poisson data that will exactly match a specified set of parameters, because (unlike the Gaussian where you can reduce the variance to arbitrarily small values) you can't generate real Poisson data with arbitrarily little noise. (Your round() statement produces integers, but not Poisson-distributed outcomes.)


问:
How to set default form values for objects in Spring Boot : Thymeleaf
Alright, so im trying to learn Spring Boot and thymeleaf.  I have object worker that gets submitted and created, put in a database then the thymelaf page is updated to allow me to edit the worker I just created.  For the editing process I need to save the Worker object to the database with the same id so it will update it, my problem is that ID part. I dont want the user to input the id on the webpage but I want it to automatically be set.  The problem is, Spring Boot doesnt know which object im editing at the moment, but I have a feeling that thymeleaf knows, I just dont know how to go about it.

```<code>               <div th:each="woo : ${workers}">
                    <h1 th:text="${woo.getFirstName() + ' ' + woo.getLastName()}"></h1>
                    <form th:action="@{/updateWorker}" th:object="${worker}" method="post">
                        <div>First name:<input type="text" placeholder="John" name="firstName" th:value="${woo.firstName}"/></div>
                        <div>Last name: <input type="text" placeholder="Smith" name="lastName" th:value="${woo.lastName}"/></div>
                        <button type="submit">UPDATE</button>
                    </form>
                </div>
</code>```

And So I have this ^... The worker object has a variable id which I would like it to be automatically set to the id of object "woo" on form submission.  Any ideas on how to go about it?   Also any helpful critique on how I go about writing my thymeleaf template would be much appreciated, thanks.

edit: And so, just an hour later I figured out a partial solution,
<button type="submit" class="btn update" name="id" th:value="${woo.id}">UPDATE</button>, that allows me to set one value on button press.  Although what if I want to set a few default values in the future, this temporary solution I just found only allows one value, what if I want to set two or even three.  Any ideas?

答:
You can create a hidden input with ID value:</p>

```<code><input type="hidden" name="id" th:value="${woo.id}"/>
</code>```

Body:
Alright, so im trying to learn Spring Boot and thymeleaf.  I have object worker that gets submitted and created, put in a database then the thymelaf page is updated to allow me to edit the worker I just created.  For the editing process I need to save the Worker object to the database with the same id so it will update it, my problem is that ID part. I dont want the user to input the id on the webpage but I want it to automatically be set.  The problem is, Spring Boot doesnt know which object im editing at the moment, but I have a feeling that thymeleaf knows, I just dont know how to go about it.

                    <form th:action="@{/updateWorker}" th:object="${worker}" method="post">

First name:<input type="text" placeholder="John" name="firstName" th:value="${woo.firstName}"/>

Last name: <input type="text" placeholder="Smith" name="lastName" th:value="${woo.lastName}"/>

                        <button type="submit">UPDATE</button>
                    </form>

And So I have this ^... The worker object has a variable id which I would like it to be automatically set to the id of object "woo" on form submission.  Any ideas on how to go about it?   Also any helpful critique on how I go about writing my thymeleaf template would be much appreciated, thanks.

edit: And so, just an hour later I figured out a partial solution,
<button type="submit" class="btn update" name="id" th:value="${woo.id}">UPDATE</button>, that allows me to set one value on button press.  Although what if I want to set a few default values in the future, this temporary solution I just found only allows one value, what if I want to set two or even three.  Any ideas?

Body:
You can create a hidden input with ID value:

<input type="hidden" name="id" th:value="${woo.id}"/>


问:
how to add foriegnkey object and connnect it a post object through a single endpoint in Django rest Framework
models.py

```<code>class PostAdvertisment(models.Model):
    # post=models.ForeignKey(Post,on_delete=models.CASCADE,null=True,blank=True)
    created_at=models.DateTimeField(auto_now_add=True)
    title=models.CharField(max_length=255,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    advertizing_content= models.TextField(null =True ,blank=True)
    def __str__(self):
        return f'{self.title}'
class Post(models.Model):

    # created_at=models.DateTimeField(efault=datetime.now, blank=True)

    created_at=models.DateTimeField(auto_now_add=True)
    author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post")
    title=models.CharField(max_length=128,null=True,blank=True)
    rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True)

    # rating=models.IntegerField(null=True,blank=True)
    content=models.TextField(null=True,blank=True)
    review=models.CharField(max_length=250,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters")
    tags = TaggableManager(blank=True)
    comments=models.ManyToManyField('Comment',blank=True,related_name="comments_post")
    anonymous = models.BooleanField(default=False, blank=True)
    fake = models.BooleanField(default=False, blank=True)

    genuine = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_genuines")
    spam = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_spames")
    advertisement=models.ForeignKey(PostAdvertisment,on_delete=models.CASCADE,null=True,blank=True)

    def __str__(self):
        return f'{self.content}'
    def get_absolute_url(self):
        return reverse('post:post_detail' , kwargs={'post_id':Post.id})
</code>```

so here is my serializers.py

```<code>class PostSerializer(TaggitSerializer,serializers.ModelSerializer):
    tags = TagListSerializerField()
    author = serializers.StringRelatedField(read_only=True)
    comments = CommentSerializer(many=True, required=False, read_only=True)
    # title = serializers.CharField()

    advertisement = PostAdvertisementSerializer()
    # advertisement = serializers.SlugRelatedField(
    #     queryset=PostAdvertisment.objects.all(),
    #     slug_field='advertisement'
    #      )
    # category_name = serializers.CharField(source='advertisement.title')
    class Meta:
        model = Post
        fields = ('id','title','rate','author','content','review','url','tags', 'fake','comments', 'created_at', 'anonymous','advertisement')
    # def create(self, validated_data):
    #     tag = validated_data.pop('advertisement')
    #     tag_instance, created =PostAdvertisment.objects.get_or_create(title=tag)
    #     article_instance = Post.objects.create(**validated_data, advertisement=tag_instance)
    #     return article_instance
    # def create(self, validated_data):
    #     serializer = self.get_serializer(data=self.request.data)
    #     advertisment =  self.request.data.pop('advertisement')
    #     company_instance = PostAdvertisment.objects.filter(id=advertisment).first()
    #     if not serializer.is_valid():
    #         print(serializer.errors)
    #     data = serializer.validated_data
    #     serializer.save(PostAdvertisment=company_instance)
    #     headers = self.get_success_headers(serializer.data)
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    def create(self,validated_data):
        advertisement=validated_data.pop('advertisement')

        post=  Post.objects.create(**validated_data)
        for advertise in advertisement:
            PostAdvertisment.object.create(**advertise)
        return post
</code>```

so the commented part of the code is something which  I've Tried
differnt appraoches gave me differnt kidn of error but none of them have worked

```<code>https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers
</code>```

I've followeed this
but its no use when ever i try to post an object either that advertisment might be null or it gives me some kind of strange error depening  on the create method i have used

```<code>"advertisement":[]
this is what the error

{
    "advertisement": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got list."
        ]
    }
}
</code>```

when i changed it to {}

```<code>"advertisement": null
</code>```

but when i tried to give data to it

```<code>AttributeError at /api/post/
type object 'PostAdvertisment' has no attribute 'object'

Request Method: POST
Request URL: http://localhost:8000/api/post/
</code>```

im not sure how to add data to nested objects

答:
First, I don't think the advertisement is expected to be a list. Based on the Post model and PostSerializer, advertisement is only one.

After creating a PostAdvertisement you also have to update post.advertisement/post.advertisement_id. This is how I think it would be:

```<code>advertisement=validated_data.pop('advertisement')
post = Post.objects.create(**validated_data)
post.advertisement = PostAdvertisment.objects.create(**advertisement)
post.save()
return post
</code>```

You could also create the PostAdvertisement first then create the Post so there is only 2 db queries instead of 3:

```<code>validated_data["advertisement"] = PostAdvertisment.objects.create(**validated_data["advertisement"])
post = Post.objects.create(**validated_data)
return post
</code>```

Body:
models.py

class PostAdvertisment(models.Model):
    # post=models.ForeignKey(Post,on_delete=models.CASCADE,null=True,blank=True)
    created_at=models.DateTimeField(auto_now_add=True)
    title=models.CharField(max_length=255,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    advertizing_content= models.TextField(null =True ,blank=True)
    def __str__(self):
        return f'{self.title}'
class Post(models.Model):

    # created_at=models.DateTimeField(efault=datetime.now, blank=True)

    created_at=models.DateTimeField(auto_now_add=True)
    author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="post")
    title=models.CharField(max_length=128,null=True,blank=True)
    rate=models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)],default=True,null=True,blank=True)

    # rating=models.IntegerField(null=True,blank=True)
    content=models.TextField(null=True,blank=True)
    review=models.CharField(max_length=250,null=True,blank=True)
    url=models.URLField(null=True,blank=True)
    voters = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True,related_name="post_voters")
    tags = TaggableManager(blank=True)
    comments=models.ManyToManyField('Comment',blank=True,related_name="comments_post")
    anonymous = models.BooleanField(default=False, blank=True)
    fake = models.BooleanField(default=False, blank=True)

    genuine = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_genuines")
    spam = models.ManyToManyField(settings.AUTH_USER_MODEL , blank=True, related_name="post_spames")
    advertisement=models.ForeignKey(PostAdvertisment,on_delete=models.CASCADE,null=True,blank=True)

    def __str__(self):
        return f'{self.content}'
    def get_absolute_url(self):
        return reverse('post:post_detail' , kwargs={'post_id':Post.id})

so here is my serializers.py

class PostSerializer(TaggitSerializer,serializers.ModelSerializer):
    tags = TagListSerializerField()
    author = serializers.StringRelatedField(read_only=True)
    comments = CommentSerializer(many=True, required=False, read_only=True)
    # title = serializers.CharField()

    advertisement = PostAdvertisementSerializer()
    # advertisement = serializers.SlugRelatedField(
    #     queryset=PostAdvertisment.objects.all(),
    #     slug_field='advertisement'
    #      )
    # category_name = serializers.CharField(source='advertisement.title')
    class Meta:
        model = Post
        fields = ('id','title','rate','author','content','review','url','tags', 'fake','comments', 'created_at', 'anonymous','advertisement')
    # def create(self, validated_data):
    #     tag = validated_data.pop('advertisement')
    #     tag_instance, created =PostAdvertisment.objects.get_or_create(title=tag)
    #     article_instance = Post.objects.create(**validated_data, advertisement=tag_instance)
    #     return article_instance
    # def create(self, validated_data):
    #     serializer = self.get_serializer(data=self.request.data)
    #     advertisment =  self.request.data.pop('advertisement')
    #     company_instance = PostAdvertisment.objects.filter(id=advertisment).first()
    #     if not serializer.is_valid():
    #         print(serializer.errors)
    #     data = serializer.validated_data
    #     serializer.save(PostAdvertisment=company_instance)
    #     headers = self.get_success_headers(serializer.data)
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    def create(self,validated_data):
        advertisement=validated_data.pop('advertisement')

        post=  Post.objects.create(**validated_data)
        for advertise in advertisement:
            PostAdvertisment.object.create(**advertise)
        return post

so the commented part of the code is something which  I've Tried
differnt appraoches gave me differnt kidn of error but none of them have worked

https://www.django-rest-framework.org/api-guide/relations/#writable-nested-serializers

I've followeed this
but its no use when ever i try to post an object either that advertisment might be null or it gives me some kind of strange error depening  on the create method i have used

"advertisement":[]
this is what the error

{
    "advertisement": {
        "non_field_errors": [
            "Invalid data. Expected a dictionary, but got list."
        ]
    }
}

when i changed it to {}

"advertisement": null

but when i tried to give data to it

AttributeError at /api/post/
type object 'PostAdvertisment' has no attribute 'object'

Request Method: POST
Request URL: http://localhost:8000/api/post/

im not sure how to add data to nested objects

Body:
First, I don't think the advertisement is expected to be a list. Based on the Post model and PostSerializer, advertisement is only one.

After creating a PostAdvertisement you also have to update post.advertisement/post.advertisement_id. This is how I think it would be:

advertisement=validated_data.pop('advertisement')
post = Post.objects.create(**validated_data)
post.advertisement = PostAdvertisment.objects.create(**advertisement)
post.save()
return post

You could also create the PostAdvertisement first then create the Post so there is only 2 db queries instead of 3:

validated_data["advertisement"] = PostAdvertisment.objects.create(**validated_data["advertisement"])
post = Post.objects.create(**validated_data)
return post


问:
Datagridview filters in VB.net
I'm trying to filter a datagridview containing flights, by chosing a period of time, a route or a budget.

The code seems to work fine for the route (RotaID) but not for the dates (DataHoraPartida) nor the budget (PrecoBase).

This is the code

```<code>Public Class FormProcurarViagem
    Private ListaViagens As New Viagens
    Private ListaRotas As New Rotas

    Private DataSetTemp As New DataSet()

    Private DataSource2Grid As New BindingSource()

    Public Event EnviaDadosViagem(ByVal NovaReservaViagem As ReservaViagem)

        Private Sub FormReservas_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListaViagens = LerXML_Viagens()
        Me.ViagensBindingSource.DataSource = ListaViagens

        FillGrid()

        ListaRotas = LerXML_Rotas()

        With ComboBox1
            .DisplayMember = "RotaID"
            .ValueMember = "RotaID"
            .DataSource = ListaRotas
            .DataBindings.Add("SelectedValue", ViagensBindingSource, "RotaID", DataSourceUpdateMode.OnPropertyChanged)
        End With

        With ComboBox2
            Dim i As Integer
            Dim j As Integer

            For j = 0 To 10
                i = i + 50
                ComboBox2.Items.Add(i)
            Next j

        End With

        DateTimePicker1.Format = DateTimePickerFormat.Custom
        DateTimePicker1.CustomFormat = "yyyy/MM/dd"
        DateTimePicker2.Format = DateTimePickerFormat.Custom
        DateTimePicker2.CustomFormat = "yyyy/MM/dd"

    End Sub

    Private Sub FillGrid()

          DataSetTemp.ReadXml("Viagens.xml")

        Dim tables As DataTableCollection = DataSetTemp.Tables

        Dim view1 As New DataView(tables(0))

        ViagensDataGridView.AutoGenerateColumns = True

        Me.Controls.Add(ViagensDataGridView)

        ' Create a BindingSource and set its DataSource property to the DataView.

        DataSource2Grid.DataSource = view1

        ' Set the data source for the DataGridView.

        ViagensDataGridView.DataSource = DataSource2Grid

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        DataSource2Grid.Filter = String.Format("DataHoraPartida >= '{0:yyyy/MM/dd}' And DataHoraPartida <= '{1:yyyy/MM/dd}'", DateTimePicker1.Value.Date, DateTimePicker2.Value.Date)

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        DataSource2Grid.Filter = "PrecoBase <=" & Me.ComboBox2.Text
    End Sub

    Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted

        DataSource2Grid.Filter = "RotaID like '%" & Me.ComboBox1.Text & "%'"
    End Sub

End Class
</code>```

In the data source the date format is yyyy/MM/dd HH:mm and the PrecoBase format is double, I don't know if that is what is causing the problem.

答:
If the data in your data source is not type DateTime then it should be, so you should first take steps to remedy that. You can then apply whatever formatting you want in the grid by setting the .DefaultCellStyle.Format property of the column.

Once you actually have data of the correct type, you can filter it properly, as per the documentation. Filtering actual Dates would look like this:

DataSource2Grid.Filter = String.Format("DataHoraPartida >= #{0:M/dd/yyyy}#' AND DataHoraPartida <= #{1:M/dd/yyyy}#", DateTimePicker1.Value, DateTimePicker2.Value)
```

<p><code>DateTime</code> literals are ALWAYS delimited with <code>#</code> characters and they are ALWAYS formatted using US date format, i.e. <code>M/dd/yyyy</code>. There's also no point specifying the <code>Date</code> property of the two values because the format already drops the time. I'd also recommend using string interpolation over <code>String.Format</code> in most cases if you're using VB 2015 (I think, or it may be 2017) or later:</p>

<pre class="lang-vb prettyprint-override"><code>DataSource2Grid.Filter = $"DataHoraPartida >= #{DateTimePicker1.Value:M/dd/yyyy}#' AND DataHoraPartida <= #{DateTimePicker2.Value:M/dd/yyyy}#"
</code>```

Title: Datagridview filters in VB.net

Body:
I'm trying to filter a datagridview containing flights, by chosing a period of time, a route or a budget.

The code seems to work fine for the route (RotaID) but not for the dates (DataHoraPartida) nor the budget (PrecoBase).

This is the code

Public Class FormProcurarViagem
    Private ListaViagens As New Viagens
    Private ListaRotas As New Rotas

    Private DataSetTemp As New DataSet()

    Private DataSource2Grid As New BindingSource()

    Public Event EnviaDadosViagem(ByVal NovaReservaViagem As ReservaViagem)

        Private Sub FormReservas_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListaViagens = LerXML_Viagens()
        Me.ViagensBindingSource.DataSource = ListaViagens

        FillGrid()

        ListaRotas = LerXML_Rotas()

        With ComboBox1
            .DisplayMember = "RotaID"
            .ValueMember = "RotaID"
            .DataSource = ListaRotas
            .DataBindings.Add("SelectedValue", ViagensBindingSource, "RotaID", DataSourceUpdateMode.OnPropertyChanged)
        End With

        With ComboBox2
            Dim i As Integer
            Dim j As Integer

            For j = 0 To 10
                i = i + 50
                ComboBox2.Items.Add(i)
            Next j

        End With

        DateTimePicker1.Format = DateTimePickerFormat.Custom
        DateTimePicker1.CustomFormat = "yyyy/MM/dd"
        DateTimePicker2.Format = DateTimePickerFormat.Custom
        DateTimePicker2.CustomFormat = "yyyy/MM/dd"

    End Sub

    Private Sub FillGrid()

          DataSetTemp.ReadXml("Viagens.xml")

        Dim tables As DataTableCollection = DataSetTemp.Tables

        Dim view1 As New DataView(tables(0))

        ViagensDataGridView.AutoGenerateColumns = True

        Me.Controls.Add(ViagensDataGridView)

        ' Create a BindingSource and set its DataSource property to the DataView.

        DataSource2Grid.DataSource = view1

        ' Set the data source for the DataGridView.

        ViagensDataGridView.DataSource = DataSource2Grid

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        DataSource2Grid.Filter = String.Format("DataHoraPartida >= '{0:yyyy/MM/dd}' And DataHoraPartida <= '{1:yyyy/MM/dd}'", DateTimePicker1.Value.Date, DateTimePicker2.Value.Date)

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        DataSource2Grid.Filter = "PrecoBase <=" & Me.ComboBox2.Text
    End Sub

    Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted

        DataSource2Grid.Filter = "RotaID like '%" & Me.ComboBox1.Text & "%'"
    End Sub

End Class

In the data source the date format is yyyy/MM/dd HH:mm and the PrecoBase format is double, I don't know if that is what is causing the problem.

Body:
If the data in your data source is not type DateTime then it should be, so you should first take steps to remedy that. You can then apply whatever formatting you want in the grid by setting the .DefaultCellStyle.Format property of the column.

Once you actually have data of the correct type, you can filter it properly, as per the documentation. Filtering actual Dates would look like this:

DataSource2Grid.Filter = String.Format("DataHoraPartida >= #{0:M/dd/yyyy}#' AND DataHoraPartida <= #{1:M/dd/yyyy}#", DateTimePicker1.Value, DateTimePicker2.Value)

DateTime literals are ALWAYS delimited with # characters and they are ALWAYS formatted using US date format, i.e. M/dd/yyyy. There's also no point specifying the Date property of the two values because the format already drops the time. I'd also recommend using string interpolation over String.Format in most cases if you're using VB 2015 (I think, or it may be 2017) or later:

DataSource2Grid.Filter = $"DataHoraPartida >= #{DateTimePicker1.Value:M/dd/yyyy}#' AND DataHoraPartida <= #{DateTimePicker2.Value:M/dd/yyyy}#"


问:
mixed models design and syntax in R
I am new to mixed model analysis. Can somebody help me to get things clear?

I have the follwoing repeated measurement design:
pre test - intervention - post test.

Varaibles:
Go_rt - reaction time.
pre_post - categorical variable (pre-test;post-test)
expectation - participants expectations.

I have the follwoing R code where I want apply mixed model to evalute wether reaction time is statistically different (pre-test vs post test). Plus I want to whether there is interction with effect with participants expectations.

mod <- lmer(Go_rt ~ pre_post +expectations + pre_post:expectations + (1|participant), data=data,
          REML=FALSE)

What I doubt about is whether the pre_post variable has to be specified in the random part. So the code will look like this:

mod1 <- lmer(Go_rt ~ pre_post +expectations + pre_post:expectations + (1+ pre_post|participant), data=data,
          REML=FALSE)

And what will it change if I change it like this?

mod2 <- lmer(Go_rt ~ pre_post +expectations + pre_post:expectations + (1|participant) + (1|pre_post), data=data,
          REML=FALSE)

Actually the mod2 give me significant results for interaciton effect whereas mod & mod1 does not.

答:
It isn't exactly clear what you are asking, it seems that you are unsure of what you should be modelling, which is a statistical question and may be more appropriate on Cross Validated, but it also seems that you are unsure about R (or rather the package lme4) syntax.

Check out this https://arxiv.org/pdf/1406.5823.pdf comprehensive guide to using lme4, specifically page 6 will be helpful for understanding random effects syntax. From that document:

"Each random-effects term is of the form (expr|factor). The expression expr is evaluated as
a linear model formula, producing a model matrix following the same rules used in standard
R modelling functions (e.g., lm or glm). The expression factor is evaluated as an R factor"

When you have RE terms specified like this: (1|participant) + (1|pre_post) that means that the RE are crossed (see PeerJ paper below), whereas pre_post + (1+ pre_post|participant) is a correlated intercept and slope (see page 6 in link above).

I agree with @sjp that you don't want to use a random effect for something with only two levels. This paper, which is a wonderful introduction to mixed models, suggests that you should have at least 5 levels: https://peerj.com/articles/4794/

An alternative to @sjp suggestion of log transforming data that might work for trial time data is to use the glmer() function with a family=gamma argument, but either way it is good to inspect residual plots for model fits http://www.sthda.com/english/articles/39-regression-model-diagnostics/161-linear-regression-assumptions-and-diagnostics-in-r-essentials/.

In the case that you don't actually need a random effects term, then the base R functions lm and glm will replace lmer and glmer respectively.

Title: mixed models design and syntax in R


问:
how would you save and read an array of arrays in firestore?
I am trying to save react-seat-picker
https://github.com/roggervalf/react-seat-picker#readme
data into firestore and read it back.

The one piece of code describing data that should be written/saved to firestore is this:

```<code> const rows = [
      [{id: 1, number: 1, isSelected: true, tooltip: 'Reserved by you'}, {id: 2, number: 2, tooltip: 'Cost: 15$'}, null, {id: 3, number: '3', isReserved: true, orientation: 'east', tooltip: 'Reserved by Rogger'}, {id: 4, number: '4', orientation: 'west'}, null, {id: 5, number: 5}, {id: 6, number: 6}],
      [{id: 7, number: 1, isReserved: true, tooltip: 'Reserved by Matthias Nadler'}, {id: 8, number: 2, isReserved: true}, null, {id: 9, number: '3', isReserved: true, orientation: 'east'}, {id: 10, number: '4', orientation: 'west'}, null, {id: 11, number: 5}, {id: 12, number: 6}],
      [{id: 13, number: 1}, {id: 14, number: 2}, null, {id: 15, number: 3, isReserved: true, orientation: 'east'}, {id: 16, number: '4', orientation: 'west'}, null, {id: 17, number: 5}, {id: 18, number: 6}],
      [{id: 19, number: 1, tooltip: 'Cost: 25$'}, {id: 20, number: 2}, null, {id: 21, number: 3, orientation: 'east'}, {id: 22, number: '4', orientation: 'west'}, null, {id: 23, number: 5}, {id: 24, number: 6}],
      [{id: 25, number: 1, isReserved: true}, {id: 26, number: 2, orientation: 'east'}, null, {id: 27, number: '3', isReserved: true}, {id: 28, number: '4', orientation: 'west'}, null,{id: 29, number: 5, tooltip: 'Cost: 11$'}, {id: 30, number: 6, isReserved: true}]
    ]
</code>```

答: So far firebase firestore doesn't support nested arrays,you need to change the data structure.Have a look at this solution</p>

Body:
I am trying to save react-seat-picker
https://github.com/roggervalf/react-seat-picker#readme
data into firestore and read it back.

The one piece of code describing data that should be written/saved to firestore is this:

 const rows = [
      [{id: 1, number: 1, isSelected: true, tooltip: 'Reserved by you'}, {id: 2, number: 2, tooltip: 'Cost: 15$'}, null, {id: 3, number: '3', isReserved: true, orientation: 'east', tooltip: 'Reserved by Rogger'}, {id: 4, number: '4', orientation: 'west'}, null, {id: 5, number: 5}, {id: 6, number: 6}],
      [{id: 7, number: 1, isReserved: true, tooltip: 'Reserved by Matthias Nadler'}, {id: 8, number: 2, isReserved: true}, null, {id: 9, number: '3', isReserved: true, orientation: 'east'}, {id: 10, number: '4', orientation: 'west'}, null, {id: 11, number: 5}, {id: 12, number: 6}],
      [{id: 13, number: 1}, {id: 14, number: 2}, null, {id: 15, number: 3, isReserved: true, orientation: 'east'}, {id: 16, number: '4', orientation: 'west'}, null, {id: 17, number: 5}, {id: 18, number: 6}],
      [{id: 19, number: 1, tooltip: 'Cost: 25$'}, {id: 20, number: 2}, null, {id: 21, number: 3, orientation: 'east'}, {id: 22, number: '4', orientation: 'west'}, null, {id: 23, number: 5}, {id: 24, number: 6}],
      [{id: 25, number: 1, isReserved: true}, {id: 26, number: 2, orientation: 'east'}, null, {id: 27, number: '3', isReserved: true}, {id: 28, number: '4', orientation: 'west'}, null,{id: 29, number: 5, tooltip: 'Cost: 11$'}, {id: 30, number: 6, isReserved: true}]
    ]


问:
Converting array of bits to array of hex in C through bitwise operations
I'm trying to convert an array of bits to an array of bytes, except my operations seem to be reading my bits in the opposite direction from what I want them to be. For example, say the array of binary bits is 10110111 11000000 00000110. I want the byte array to be {B7, C0, 06}. Instead, my code below produces an output of of {ED, 03, 60} i.e. it reads every 8 bits in the opposite direction. Could anyone provide me some suggestions as to where I am going wrong?

```<code>void find_hex_arr(uint8_t* bit_arr, int bit_len) {
  uint8_t* hex_arr = malloc(bit_len/8);
  int index = 0;
  unsigned int i = 0;
  unsigned int j = 0;
  for (i = 0; i < bit_len; i = j) {
    for (j = i; j < i + 8; ++j) {
      hex_arr[index] |= bit_arr[j] << (j - i);
    }
    index++;
  }
}
</code>```

答:
You should change this:

```<code>for (i = 0; i < bit_len; i = j) {
    for (j = i; j < i + 8; ++j) {
      hex_arr[index] |= bit_arr[j] << (j - i);
</code>```

into this:

```<code>for (i = 0; i < bit_len; i += 8) {
    for (j = 0; j < 8; ++j) {
      hex_arr[index] |= bit_arr[i+j] << (7 - j);
</code>```

because your shifts reorder bits in the opposite direction.

Body:
I'm trying to convert an array of bits to an array of bytes, except my operations seem to be reading my bits in the opposite direction from what I want them to be. For example, say the array of binary bits is 10110111 11000000 00000110. I want the byte array to be {B7, C0, 06}. Instead, my code below produces an output of of {ED, 03, 60} i.e. it reads every 8 bits in the opposite direction. Could anyone provide me some suggestions as to where I am going wrong?

void find_hex_arr(uint8_t* bit_arr, int bit_len) {
  uint8_t* hex_arr = malloc(bit_len/8);
  int index = 0;
  unsigned int i = 0;
  unsigned int j = 0;
  for (i = 0; i < bit_len; i = j) {
    for (j = i; j < i + 8; ++j) {
      hex_arr[index] |= bit_arr[j] << (j - i);
    }
    index++;
  }
}

Body:
You should change this:

for (i = 0; i < bit_len; i = j) {
    for (j = i; j < i + 8; ++j) {
      hex_arr[index] |= bit_arr[j] << (j - i);

into this:

for (i = 0; i < bit_len; i += 8) {
    for (j = 0; j < 8; ++j) {
      hex_arr[index] |= bit_arr[i+j] << (7 - j);

because your shifts reorder bits in the opposite direction.


问:
How to change the color of a text/item/css inside a *ngFor?
I have one item creater using an array, that creates a list of items using the *ngFor="let option.

I want to change the color of those items based on their values, but I cant seem to do it.

tankItAwnserArray = ['Yes','Yes','Option','NO'];```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ion-item *ngFor="let option of tankItAwnserArray">
        <ion-item> Move Damage:  {{option}}</ion-item>
      </ion-item></code>```

I want the "Yes" value to be Green, the "Option" to be orange and the "No" to be red.

I tried a lot of things but I cant see to make it work.

Can anyone help me?

答:
You could use the conditional CSS class with *ngClass

Component.HTML

```<code><ion-item *ngFor="let option of tankItAwnserArray">
    <ion-item>
        Move Damage:
        <span [ngClass]="{'green-class': option === 'Yes', 'orange-class': option === 'Option', 'red-class': option === 'No' }">{{option}}</span>
    </ion-item>
</ion-item>
</code>```

Component.CSS

```<code>.green-class { color: green; }
.orange-class { color: orange; }
.red-class { color: red; }
</code>```

Body:
I have one item creater using an array, that creates a list of items using the *ngFor="let option.

I want to change the color of those items based on their values, but I cant seem to do it.

tankItAwnserArray = ['Yes','Yes','Option','NO'];

 <ion-item *ngFor="let option of tankItAwnserArray">
        <ion-item> Move Damage:  {{option}}</ion-item>
      </ion-item>

I want the "Yes" value to be Green, the "Option" to be orange and the "No" to be red.

I tried a lot of things but I cant see to make it work.

Can anyone help me?

Body:
You could use the conditional CSS class with *ngClass

Component.HTML

<ion-item *ngFor="let option of tankItAwnserArray">
    <ion-item>
        Move Damage:
        <span [ngClass]="{'green-class': option === 'Yes', 'orange-class': option === 'Option', 'red-class': option === 'No' }">{{option}}</span>
    </ion-item>
</ion-item>

Component.CSS

.green-class { color: green; }
.orange-class { color: orange; }
.red-class { color: red; }


答:
The value that you're shifting is where the problem in.

The first time you enter the inner loop, i is 0 and j is 0.  This makes j-i 0 so the value in question gets OR'ed into the rightmost bit instead of the leftmost.  Then when j is 1 your shift 1 so the bit goes into the second right bit instead of the second left.

So your shift is going from 0 to 7 when it should be going from 7 to 0.  You fix this by subtracting the shift amount from 7.

```<code>hex_arr[index] |= bit_arr[j] << (7 - (j - i));
</code>```

Title: Converting array of bits to array of hex in C through bitwise operations

Body:
The value that you're shifting is where the problem in.

The first time you enter the inner loop, i is 0 and j is 0.  This makes j-i 0 so the value in question gets OR'ed into the rightmost bit instead of the leftmost.  Then when j is 1 your shift 1 so the bit goes into the second right bit instead of the second left.

So your shift is going from 0 to 7 when it should be going from 7 to 0.  You fix this by subtracting the shift amount from 7.

hex_arr[index] |= bit_arr[j] << (7 - (j - i));