问:
How to use import () to dynamically load components in React?
I tried to use import() instead of React.lazy to dynamically load components, but it didn't work.

App.js

```<code>import React, { useState } from 'react';
function App() {
  const [Com, setCom] = useState(null);

  const handleClick = () => {
      import("./A.js").then(c => {
        //console.log(c.default)
        setCom(c.default)
      })
  }

  return (
      <div>
        <button onClick={handleClick}>Load</button>
        { Com ? <Com /> : null }
      </div>
   );
}

export default App;
</code>```

A.js

```<code>import React from "react";

export default function A () {
    return (<div>A</div>)
}
</code>```

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

In fact, I printed out c.default. It's really a function.

c.default

```<code>ƒ A() {
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 4
    },
    __self: this
  }, "A");
}
</code>```

答:
Actually, it's not related to the dynamic import but the useState implementation. For example:

```<code>import Comp from "./A";

function App() {
  const [Com, setCom] = useState(Comp);

  return (
    <div>
      <Com />
    </div>
  );
}
</code>```

Will throw the same error. That's because when you call useState(Comp), Comp "function" (which is the Component) been execute (you can test it by removing any <Com /> from the code and adding console.log inside A. The console.log still appears).

As a result Com is no longer a Component but a JSX element. When you try to render JSX element in a function way (meaning wrapping it with < and />, this error thrown.

The solution is either to set Com as a component (() => Com) or to render it as a JSX child ({Com})

```<code>import React, { useState } from "react";

function App() {
  const [Com, setCom] = useState(null);

  const handleClick = () => {
    import("./A.js").then(c => {
      //console.log(c.default)
      setCom(c.default);
    });
  };

  return (
    <div>
      <button onClick={handleClick}>Load</button>
      {/* <Comp /> */}
      {Com}
    </div>
  );
}

export default App;
</code>```

https://codesandbox.io/s/answer-for-httpsstackoverflowcomq62125854863110-jj2wu

BTW, you can see the difference by console.dir the original outcome of import Comp from "./A"; and the outcome of useState(Comp)

```<code>import Comp from "./A";

function App() {
  const [Com, setCom] = useState(Comp);
  // console.log(1, Com, 2, Comp);
  console.dir(Com) // Object
  console.dir(Comp) // ƒ A()
  //...
}
</code>```

Body:
I tried to use import() instead of React.lazy to dynamically load components, but it didn't work.

App.js

import React, { useState } from 'react';
function App() {
  const [Com, setCom] = useState(null);

  const handleClick = () => {
      import("./A.js").then(c => {
        //console.log(c.default)
        setCom(c.default)
      })
  }

  return (

        <button onClick={handleClick}>Load</button>
        { Com ? <Com /> : null }

   );
}

export default App;

A.js

import React from "react";

export default function A () {
    return (
A
)
}

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

In fact, I printed out c.default. It's really a function.

c.default

ƒ A() {
  return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
    __source: {
      fileName: _jsxFileName,
      lineNumber: 4
    },
    __self: this
  }, "A");
}

Body:
Actually, it's not related to the dynamic import but the useState implementation. For example:

import Comp from "./A";

function App() {
  const [Com, setCom] = useState(Comp);

  return (
    <div>
      <Com />
    </div>
  );
}

Will throw the same error. That's because when you call useState(Comp), Comp "function" (which is the Component) been execute (you can test it by removing any <Com /> from the code and adding console.log inside A. The console.log still appears).

As a result Com is no longer a Component but a JSX element. When you try to render JSX element in a function way (meaning wrapping it with < and />, this error thrown.

The solution is either to set Com as a component (() => Com) or to render it as a JSX child ({Com})

import React, { useState } from "react";

function App() {
  const [Com, setCom] = useState(null);

  const handleClick = () => {
    import("./A.js").then(c => {
      //console.log(c.default)
      setCom(c.default);
    });
  };

  return (
    <div>
      <button onClick={handleClick}>Load</button>
      {/* <Comp /> */}
      {Com}
    </div>
  );
}

export default App;

https://codesandbox.io/s/answer-for-httpsstackoverflowcomq62125854863110-jj2wu

BTW, you can see the difference by console.dir the original outcome of import Comp from "./A"; and the outcome of useState(Comp)

import Comp from "./A";

function App() {
  const [Com, setCom] = useState(Comp);
  // console.log(1, Com, 2, Comp);
  console.dir(Com) // Object
  console.dir(Comp) // ƒ A()
  //...
}


来源: stackexchange

问:
stop character been inserted into input react
I want to detect which character base on user keyboard hence I use onKeyDown, but how do I stop ',' been inserted into the input element?</p>

```<code>const [inputValue, setInputValue] = useState("");

  const handleKeyDown = (e: any) => {
    if (['188'].includes(e.keyCode)) {
      console.log("do something");
    }
  };

  const handleChange = (e: any) => {
    setInputValue(e.target.value)
  }

  return (
      <input
        type="text"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
  );
</code>```

答:
You just need to check the input in handleChange to decide to update new value or not
Try the code below:
Or Codesandbox

import React, { useState } from "react";
import "./styles.css";

const App = () => {
  const [inputValue, setInputValue] = useState("");

  const handleChange = e => {
    if (!e.target.value.includes(",")) {
      setInputValue(e.target.value);
    }
  };

  return (
    <input
      value={inputValue}
      type="text"
      onChange={handleChange}
    />
  );
};

export default App;```

ContentLicense: CC BY-SA 4.0

Body:
I want to detect which character base on user keyboard hence I use onKeyDown, but how do I stop ',' been inserted into the input element?

const [inputValue, setInputValue] = useState("");

  const handleKeyDown = (e: any) => {
    if (['188'].includes(e.keyCode)) {
      console.log("do something");
    }
  };

  const handleChange = (e: any) => {
    setInputValue(e.target.value)
  }

  return (
      <input
        type="text"
        onChange={handleChange}
        onKeyDown={handleKeyDown}
      />
  );


问:
`MediaStore.MediaColumns.DATA` is deprecated, what column should I use as an alternative
I want to load all the pictures from the media provider to my app by using MediaStore API, but this column MediaStore.MediaColumns.DATA is deprecated. So, what can I use as an alternative?

I want to update the following code to get rid of the deprecated MediaStore.MediaColumns.DATA column:

fun ContentResolver.loadImagesPaths(): List<String> {
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val images = mutableListOf<String>()
    val projection = arrayOf(MediaStore.MediaColumns.DATA)
    query(uri, projection, null, null, null)?.use { cursor ->
        val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
        while (cursor.moveToNext()) {
            images += cursor.getString(dataColumn)
        }
    }
    return images
}
```
<p>Edit:</p>
<p>Updated code:</p>
<pre class="lang-kotlin prettyprint-override"><code>fun ContentResolver.loadImagesUris(): List<Uri> {
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val images = mutableListOf<Uri>()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    query(uri, projection, null, null, null)?.use { cursor ->
        val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()) {
            images += ContentUris.withAppendedId(uri, cursor.getLong(idColumn))
        }
    }
    return images
}
</code>```

Check out this link for further details on how to access media files from shared storage: https://developer.android.com/training/data-storage/shared/media

答:
I finally solved the problem by creating this class

```<code>class FileHelper {
val mediaType = "multipart/form-data".toMediaTypeOrNull()

fun getPartBodyFromUri(context: Context, uri: Uri): MultipartBody.Part {
    val realPath = getPathFromURI(context, uri)
    val fileImage = createFile(realPath)
    val requestBody = createRequestBody(fileImage)
    return createPart(fileImage, requestBody)
}

private fun createFile(realPath: String): File {
    return File(realPath)
}

private fun createRequestBody(file: File): RequestBody {
    return file.asRequestBody(mediaType)
}

private fun createPart(file: File, requestBody: RequestBody): MultipartBody.Part {
    return MultipartBody.Part.createFormData("imageFile", file.name, requestBody)
}

private fun getPathFromURI(context: Context, uri: Uri): String {
    var realPath = String()
    uri.path?.let { path ->

        val databaseUri: Uri
        val selection: String?
        val selectionArgs: Array<String>?
        if (path.contains("/document/image:")) { // files selected from "Documents"
            databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            selection = "_id=?"
            selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
        } else { // files selected from all other sources, especially on Samsung devices
            databaseUri = uri
            selection = null
            selectionArgs = null
        }
        try {
            val column = "_data"
            val projection = arrayOf(column)
            val cursor = context.contentResolver.query(
                databaseUri,
                projection,
                selection,
                selectionArgs,
                null
            )
            cursor?.let {
                if (it.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(column)
                    realPath = cursor.getString(columnIndex)
                }
                cursor.close()
            }
        } catch (e: Exception) {
            println(e)
        }
    }
    return realPath
}
</code>```

}

Media.DATA it's deprecate and "MediaStore.Images.Media._ID" to get the  correct column, not working so I create column I need

```<code>val column = "_data"
val projection = arrayOf(column)
</code>```

then I use getColumnIndexOrThrow() method to get correct index

```<code>val columnIndex = cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)
</code>```

Body:
I want to load all the pictures from the media provider to my app by using MediaStore API, but this column MediaStore.MediaColumns.DATA is deprecated. So, what can I use as an alternative?

I want to update the following code to get rid of the deprecated MediaStore.MediaColumns.DATA column:

fun ContentResolver.loadImagesPaths(): List<String> {
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val images = mutableListOf<String>()
    val projection = arrayOf(MediaStore.MediaColumns.DATA)
    query(uri, projection, null, null, null)?.use { cursor ->
        val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
        while (cursor.moveToNext()) {
            images += cursor.getString(dataColumn)
        }
    }
    return images
}

Edit:

Updated code:

fun ContentResolver.loadImagesUris(): List<Uri> {
    val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val images = mutableListOf<Uri>()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    query(uri, projection, null, null, null)?.use { cursor ->
        val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()) {
            images += ContentUris.withAppendedId(uri, cursor.getLong(idColumn))
        }
    }
    return images
}

Check out this link for further details on how to access media files from shared storage: https://developer.android.com/training/data-storage/shared/media

Body:
I finally solved the problem by creating this class

class FileHelper {
val mediaType = "multipart/form-data".toMediaTypeOrNull()

fun getPartBodyFromUri(context: Context, uri: Uri): MultipartBody.Part {
    val realPath = getPathFromURI(context, uri)
    val fileImage = createFile(realPath)
    val requestBody = createRequestBody(fileImage)
    return createPart(fileImage, requestBody)
}

private fun createFile(realPath: String): File {
    return File(realPath)
}

private fun createRequestBody(file: File): RequestBody {
    return file.asRequestBody(mediaType)
}

private fun createPart(file: File, requestBody: RequestBody): MultipartBody.Part {
    return MultipartBody.Part.createFormData("imageFile", file.name, requestBody)
}

private fun getPathFromURI(context: Context, uri: Uri): String {
    var realPath = String()
    uri.path?.let { path ->

        val databaseUri: Uri
        val selection: String?
        val selectionArgs: Array<String>?
        if (path.contains("/document/image:")) { // files selected from "Documents"
            databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            selection = "_id=?"
            selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
        } else { // files selected from all other sources, especially on Samsung devices
            databaseUri = uri
            selection = null
            selectionArgs = null
        }
        try {
            val column = "_data"
            val projection = arrayOf(column)
            val cursor = context.contentResolver.query(
                databaseUri,
                projection,
                selection,
                selectionArgs,
                null
            )
            cursor?.let {
                if (it.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(column)
                    realPath = cursor.getString(columnIndex)
                }
                cursor.close()
            }
        } catch (e: Exception) {
            println(e)
        }
    }
    return realPath
}

}

Media.DATA it's deprecate and "MediaStore.Images.Media._ID" to get the  correct column, not working so I create column I need

val column = "_data"
val projection = arrayOf(column)

then I use getColumnIndexOrThrow() method to get correct index

val columnIndex = cursor.getColumnIndexOrThrow(column)
realPath = cursor.getString(columnIndex)


问:
React-Native Execution failed for task ':app:packageDebug'
Whenever I try to run 'react-native run-android'

I got failure:

Execution failed for task ':app:packageDebug'

I tried checkout to previus commits.
I tried removing android/app/build and re-build
I tried removing debug.keystore and initiated it again.

none of them solved the problem.

I successfully run my app before in android virtual device, and I've already uploaded my app to google play store, and it works.

I haven't seen this error before. My code worked totally fine before:

I removed some font files in android/src/main/assets/fonts. This maybe the reason.

I ran "react-native run-ios". This may be the reason.

Task :app:packageDebug FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
117 actionable tasks: 5 executed, 112 up-to-date

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:packageDebug'.

4 exceptions were raised by workers:
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.

BUILD FAILED in 22s

```<code>at checkExecSyncError (child_process.js:629:11)
at execFileSync (child_process.js:647:13)
at runOnAllDevices (/Users/leonkong/Desktop/dev/CoddingHippo/Native_Makkcha/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:74:39)
at buildAndRun (/Users/leonkong/Desktop/dev/CoddingHippo/Native_Makkcha/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:158:41)
at then.result (/Users/leonkong/Desktop/dev/CoddingHippo/Native_Makkcha/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:125:12)
</code>```

Build Success message. And running app on virtual device  by android studio 2

答:
I also face issue.

I just open Android Studio - Clear Build - Run app.

Works for me

Body:
Whenever I try to run 'react-native run-android'

I got failure:

Execution failed for task ':app:packageDebug'

I tried checkout to previus commits.
I tried removing android/app/build and re-build
I tried removing debug.keystore and initiated it again.

none of them solved the problem.

I successfully run my app before in android virtual device, and I've already uploaded my app to google play store, and it works.

I haven't seen this error before. My code worked totally fine before:

I removed some font files in android/src/main/assets/fonts. This maybe the reason.

I ran "react-native run-ios". This may be the reason.

Task :app:packageDebug FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings
117 actionable tasks: 5 executed, 112 up-to-date

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:packageDebug'.

4 exceptions were raised by workers:
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.
  java.io.UncheckedIOException: java.io.IOException: Execution of compression failed.

BUILD FAILED in 22s

at checkExecSyncError (child_process.js:629:11)
at execFileSync (child_process.js:647:13)
at runOnAllDevices (/Users/leonkong/Desktop/dev/CoddingHippo/Native_Makkcha/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:74:39)
at buildAndRun (/Users/leonkong/Desktop/dev/CoddingHippo/Native_Makkcha/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:158:41)
at then.result (/Users/leonkong/Desktop/dev/CoddingHippo/Native_Makkcha/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:125:12)

Build Success message. And running app on virtual device  by android studio 2


问:
Android ViewGroup crash: Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
We have found several cases for this kind of crashes reported by backend logging monitoring. It seems the crashes do not tie to particular UX failure. And from the reports, there is no sign of how our own classes being involved(no sign of any of our classes names). Here is an example of typical crashes:

```<code>java.lang.NullPointerException: Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3357)
at android.view.View.updateDisplayListIfDirty(View.java:14288)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:273)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:279)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:318)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2561)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2377)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2007)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1086)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6453)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:846)
at android.view.Choreographer.doCallbacks(Choreographer.java:647)
at android.view.Choreographer.doFrame(Choreographer.java:601)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:829)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:927)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:713)
</code>```

Does anyone know whether there is related bug logged against Android code?

答:
I was trying to navigate from Fragment A to Fragment B, and Fragment A was a form that required data from Fragment B.

So when I tried to navigate without filling up A, it was throwing this exception.

Also, even if A was independent of the data B, it was throwing this exception.

I have no idea why but I added a condition where the user had to fill-up the form before navigating away and that solved the issue.

ContentLicense: CC BY-SA 3.0

Body:
We have found several cases for this kind of crashes reported by backend logging monitoring. It seems the crashes do not tie to particular UX failure. And from the reports, there is no sign of how our own classes being involved(no sign of any of our classes names). Here is an example of typical crashes:

java.lang.NullPointerException: Attempt to read from field 'int android.view.View.mViewFlags' on a null object reference
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3357)
at android.view.View.updateDisplayListIfDirty(View.java:14288)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:3549)
at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:3528)
at android.view.View.updateDisplayListIfDirty(View.java:14253)
at android.view.View.getDisplayList(View.java:14315)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:273)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:279)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:318)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2561)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2377)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2007)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1086)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6453)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:846)
at android.view.Choreographer.doCallbacks(Choreographer.java:647)
at android.view.Choreographer.doFrame(Choreographer.java:601)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:829)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:927)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:713)

Does anyone know whether there is related bug logged against Android code?


问:
How to create Spinner-list using CustomAdapter in android
in my app,I want to create SpinnerList using CustomAdapter class,For this i wrote below code but when I tap on spinner list then array-List images are not loading in spinner-list as like my below screen why this problem is coming?

main_layout.xml:-

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Category:"
        android:layout_marginBottom="5dp"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

MainActivity:-

```<code>public class MainActivity extends AppCompatActivity  {

    public static final String[] titles = new String[] { "Strawberry",
            "Banana", "Orange", "Hello" };

    public static final Integer[] images = { R.drawable.image1,
            R.drawable.image2, R.drawable.image3, R.drawable.image4 };

    Spinner spinner;
    List<RowItem> rowItems;

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

        rowItems = new ArrayList<RowItem>();
        for (int i = 0; i < titles.length; i++) {

            RowItem item = new RowItem(titles[i],images[i]);
            rowItems.add(item);
        }

        spinner = (Spinner)findViewById(R.id.spinner);
       CustomAdapter adapter = new CustomAdapter(MainActivity.this,
            R.layout.listitems_layout, R.id.title, rowItems);
        spinner.setAdapter(adapter);
    }
}
</code>```

listitems_layout.xml:-

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

    <ImageView
        android:id="@+id/icon"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/image1"
        android:padding="10dp"
        />

    <TextView
        android:layout_marginTop="30dp"
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/icon"
        android:textColor="#CC0033"
        android:text="Strawberry"
        android:textSize="16dp" />

</LinearLayout>
</code>```

CustomAdapter:-

```<code>package com.example.venkat.spinnerexample1;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class CustomAdapter extends ArrayAdapter<RowItem> {

    LayoutInflater flater;

     public CustomAdapter(Activity context,int resouceId, int textviewId, List<RowItem> list){

    super(context,resouceId,textviewId, list);
    flater = context.getLayoutInflater();
}

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        RowItem rowItem = getItem(position);

        View rowview = flater.inflate(R.layout.listitems_layout,null,true);

        TextView txtTitle = (TextView) rowview.findViewById(R.id.title);
        txtTitle.setText(rowItem.getTitle());

        ImageView imageView = (ImageView) rowview.findViewById(R.id.icon);
        imageView.setImageResource(rowItem.getImageId());

        return rowview;
    }
}
</code>```

RowItem:-

```<code>package com.example.venkat.spinnerexample1;

public class RowItem {

    private int ImageId;
    private String Title;

    public RowItem(String Title,int ImageId){

        this.Title = Title;
        this.ImageId = ImageId;
    }

    public String getTitle(){

        return Title;
    }

    public void setTitle(String Title){

        this.Title = Title;
    }

    public int getImageId(){

        return ImageId;
    }

    public void setImageId(int ImageId){

        this.ImageId = ImageId;
    }

    @Override
    public String toString() {
        return Title ;
    }
}
</code>```

screen:-
---

答:
We can also use ViewHolder Pattern</p>

```<code>public class TypeAdapter extends ArrayAdapter<RowItem> {
    public TypeAdapter(@NonNull Context context, ArrayList<Calendar> objects) {
        super(context, R.layout.calendar_type_row, objects);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return rowView(convertView, position);
    }

    @Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return rowView(convertView, position);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        //Views
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            //Init Views by itemView.findViewById
        }
    }

    private View rowView(View convertView, int position) {
        if(convertView==null)
        {
          convertView = LayoutInflater.from(getContext()).inflate(R.layout.calendar_type_row,null);
        }
        RowItem rowType = getItem(position);
        ViewHolder viewHolder = new ViewHolder(convertView);
        //Setup Values
        return convertView;
    }
}
</code>```

Body:
in my app,I want to create SpinnerList using CustomAdapter class,For this i wrote below code but when I tap on spinner list then array-List images are not loading in spinner-list as like my below screen why this problem is coming?

main_layout.xml:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Category:"
        android:layout_marginBottom="5dp"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity:-

public class MainActivity extends AppCompatActivity  {

    public static final String[] titles = new String[] { "Strawberry",
            "Banana", "Orange", "Hello" };

    public static final Integer[] images = { R.drawable.image1,
            R.drawable.image2, R.drawable.image3, R.drawable.image4 };

    Spinner spinner;
    List<RowItem> rowItems;

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

        rowItems = new ArrayList<RowItem>();
        for (int i = 0; i < titles.length; i++) {

            RowItem item = new RowItem(titles[i],images[i]);
            rowItems.add(item);
        }

        spinner = (Spinner)findViewById(R.id.spinner);
       CustomAdapter adapter = new CustomAdapter(MainActivity.this,
            R.layout.listitems_layout, R.id.title, rowItems);
        spinner.setAdapter(adapter);
    }
}

listitems_layout.xml:-

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

    <ImageView
        android:id="@+id/icon"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/image1"
        android:padding="10dp"
        />

    <TextView
        android:layout_marginTop="30dp"
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/icon"
        android:textColor="#CC0033"
        android:text="Strawberry"
        android:textSize="16dp" />

</LinearLayout>

CustomAdapter:-

package com.example.venkat.spinnerexample1;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class CustomAdapter extends ArrayAdapter<RowItem> {

    LayoutInflater flater;

     public CustomAdapter(Activity context,int resouceId, int textviewId, List<RowItem> list){

    super(context,resouceId,textviewId, list);
    flater = context.getLayoutInflater();
}

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        RowItem rowItem = getItem(position);

        View rowview = flater.inflate(R.layout.listitems_layout,null,true);

        TextView txtTitle = (TextView) rowview.findViewById(R.id.title);
        txtTitle.setText(rowItem.getTitle());

        ImageView imageView = (ImageView) rowview.findViewById(R.id.icon);
        imageView.setImageResource(rowItem.getImageId());

        return rowview;
    }
}

RowItem:-

package com.example.venkat.spinnerexample1;

public class RowItem {

    private int ImageId;
    private String Title;

    public RowItem(String Title,int ImageId){

        this.Title = Title;
        this.ImageId = ImageId;
    }

    public String getTitle(){

        return Title;
    }

    public void setTitle(String Title){

        this.Title = Title;
    }

    public int getImageId(){

        return ImageId;
    }

    public void setImageId(int ImageId){

        this.ImageId = ImageId;
    }

    @Override
    public String toString() {
        return Title ;
    }
}

screen:-
---

Body:
We can also use ViewHolder Pattern

public class TypeAdapter extends ArrayAdapter<RowItem> {
    public TypeAdapter(@NonNull Context context, ArrayList<Calendar> objects) {
        super(context, R.layout.calendar_type_row, objects);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return rowView(convertView, position);
    }

    @Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return rowView(convertView, position);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        //Views
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            //Init Views by itemView.findViewById
        }
    }

    private View rowView(View convertView, int position) {
        if(convertView==null)
        {
          convertView = LayoutInflater.from(getContext()).inflate(R.layout.calendar_type_row,null);
        }
        RowItem rowType = getItem(position);
        ViewHolder viewHolder = new ViewHolder(convertView);
        //Setup Values
        return convertView;
    }
}


问:
how to know the value of bind parameter in PDO in php
I have following code in which I want to know the value of bind parameter:

```<code>$sql->bindParam( ':checkbox', $value['CHECKBOXLIST'], PDO::PARAM_STR );
</code>```

How can i know value of :checkbox variable?

This variable i am passing to IN query of WHERE clause, but unable to get result. This is a statement. $value['CHECKBOXLIST'] returns array like 1,2,3,4.

where  Checkbox IN (:checkbox)

How can I also handle it?

答:
PDOStatement->bindParam() stores a reference to a PHP variable:

bool PDOStatement::bindParam ( mixed
  $parameter , mixed &$variable [, int
  $data_type = PDO::PARAM_STR [, int
  $length [, mixed $driver_options ]]] )

When you run the query, the value is read from such variable. So the value is right in that variable, in your case $value['CHECKBOXLIST']. If you remove or overwrite the variable before running the query, the value will be lost.

Body:
I have following code in which I want to know the value of bind parameter:

$sql->bindParam( ':checkbox', $value['CHECKBOXLIST'], PDO::PARAM_STR );

How can i know value of :checkbox variable?

This variable i am passing to IN query of WHERE clause, but unable to get result. This is a statement. $value['CHECKBOXLIST'] returns array like 1,2,3,4.

where  Checkbox IN (:checkbox)

How can I also handle it?


问:
"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?
I am trying to send a simple dictionary to a json file from python, but I keep getting the "TypeError: 1425 is not JSON serializable" message.

```<code>import json
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8'))
afile.close()
</code>```

If I add the default argument, then it writes, but the integer values are written to the json file as strings, which is undesirable.

```<code>afile.write(json.dumps(alerts,encoding='UTF-8',default=str))
</code>```

答:
Use the below code to resolve the issue.</p>
```<code>import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()
</code>```

Body:
I am trying to send a simple dictionary to a json file from python, but I keep getting the "TypeError: 1425 is not JSON serializable" message.

import json
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8'))
afile.close()

If I add the default argument, then it writes, but the integer values are written to the json file as strings, which is undesirable.

afile.write(json.dumps(alerts,encoding='UTF-8',default=str))

Body:
Use the below code to resolve the issue.

import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()


问:
python string operation. sticked words separation
I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings.
for example,

```<code>my_function('abcde')

output =
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]
</code>```

It is not quite the permutation since the order matters.

答:
Same result without itertools:

s = 'python'
splits = len(s) - 1
output = []
for i in range(2 ** splits):
    combination = []
    word = ''
    for position in range(splits + 1):
        word += s[position]
        if not (i & (1 << position)):
            combination.append(word)
            word = ''
    output.append(combination)
output.sort()

for combination in output:
    print(combination)
```

Just for beginners.

Body:
I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings.
for example,

my_function('abcde')

output =
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]

It is not quite the permutation since the order matters.

Body:
Same result without itertools:

s = 'python'
splits = len(s) - 1
output = []
for i in range(2 ** splits):
    combination = []
    word = ''
    for position in range(splits + 1):
        word += s[position]
        if not (i & (1 << position)):
            combination.append(word)
            word = ''
    output.append(combination)
output.sort()

for combination in output:
    print(combination)

Just for beginners.


问:
Date value in matDatepicker is not equal with formControl using Reactive Form inAngular 8
I have a concern regarding matDatepicker in Angular wherein the date (from api) in my formControl using Reactive Forms does not reflect the exact value in matDatepicker. My matDatePicker shows "12/31/2019" while my formControl is "2020-01-01T00:00:00.000Z". My local timezone is UTC -08:00 Pacific (local computer) while my webservice server timezone and mySQL Database is UTC-00:00. I noticed that Angular applies the offset value from my local timezone. What can I do to adjust it to reflect the exact value from my database?

Reactive form:

```<code>this.currencyRatesArray = <FormArray>this.currencyForm.get('currencyRates');
      for (const currencyRate of _currency.currencyRates) {
        const grp = this.formBuilder.group({
          id: [currencyRate.id],
          effectiveDateFrom: [new Date(currencyRate.effectiveDateFrom), Validators.required],
          effectiveDateTo: [new Date(currencyRate.effectiveDateTo), Validators.required],
          currencyRate: [currencyRate.currencyRate, Validators.required],
          active: [currencyRate.active, Validators.required],
        });
        this.currencyRatesArray.push(grp);
        this.currencyForm.setControl('currencyRates', this.currencyRatesArray);
        this.dataSource = new MatTableDataSource(
          (this.currencyForm.get('currencyRates') as FormArray).controls);
      }
</code>```

JSON String from Webservice

```<code>"currencyRates": [
{
  "id": "6ea84267-5a47-4aeb-afac-7eee65ff95ec",
  "effectiveDateFrom": "2020-01-01T00:00:00.000Z",
  "effectiveDateTo": "2020-12-31T00:00:00.000Z",
  "currencyRate": 1,
  "active": true
}
</code>```

]

答:
I have encountered the issue few days back. Angular material date picker by default uses DatePipe to manipulate date variables. Which is creating the issue.
I have fixed is using moment.js in my app. So install moment.js.

Please follow the code it might help you.

```<code>npm I moment // install this

import * as moment from 'moment'; // include this in your ts file

effectiveDateFrom: [moment(currencyRate.effectiveDateFrom), Validators.required],
effectiveDateTo: [moment(currencyRate.effectiveDateTo), Validators.required],
</code>```

Also while you save use moment as well for your DB.

```<code>const saveDate = moment(toDate).format('YYYY-MM-DD')
</code>```

here I choose to save the date in YYYY-MM-DD for my purpose you can change though. But moment.js will surely help you in this situation.

Body:
I have a concern regarding matDatepicker in Angular wherein the date (from api) in my formControl using Reactive Forms does not reflect the exact value in matDatepicker. My matDatePicker shows "12/31/2019" while my formControl is "2020-01-01T00:00:00.000Z". My local timezone is UTC -08:00 Pacific (local computer) while my webservice server timezone and mySQL Database is UTC-00:00. I noticed that Angular applies the offset value from my local timezone. What can I do to adjust it to reflect the exact value from my database?

Reactive form:

this.currencyRatesArray = <FormArray>this.currencyForm.get('currencyRates');
      for (const currencyRate of _currency.currencyRates) {
        const grp = this.formBuilder.group({
          id: [currencyRate.id],
          effectiveDateFrom: [new Date(currencyRate.effectiveDateFrom), Validators.required],
          effectiveDateTo: [new Date(currencyRate.effectiveDateTo), Validators.required],
          currencyRate: [currencyRate.currencyRate, Validators.required],
          active: [currencyRate.active, Validators.required],
        });
        this.currencyRatesArray.push(grp);
        this.currencyForm.setControl('currencyRates', this.currencyRatesArray);
        this.dataSource = new MatTableDataSource(
          (this.currencyForm.get('currencyRates') as FormArray).controls);
      }

JSON String from Webservice

"currencyRates": [
{
  "id": "6ea84267-5a47-4aeb-afac-7eee65ff95ec",
  "effectiveDateFrom": "2020-01-01T00:00:00.000Z",
  "effectiveDateTo": "2020-12-31T00:00:00.000Z",
  "currencyRate": 1,
  "active": true
}

]

Body:
I have encountered the issue few days back. Angular material date picker by default uses DatePipe to manipulate date variables. Which is creating the issue.
I have fixed is using moment.js in my app. So install moment.js.

Please follow the code it might help you.

npm I moment // install this

import * as moment from 'moment'; // include this in your ts file

effectiveDateFrom: [moment(currencyRate.effectiveDateFrom), Validators.required],
effectiveDateTo: [moment(currencyRate.effectiveDateTo), Validators.required],

Also while you save use moment as well for your DB.

const saveDate = moment(toDate).format('YYYY-MM-DD')

here I choose to save the date in YYYY-MM-DD for my purpose you can change though. But moment.js will surely help you in this situation.


问:
Problem adding class to more lines of a form using jquery clone function
I have the following doubt, I am maintaining a form using the php language, it has a method that clones all content, that is, the body of a current row table for each time the user wants to create too many rows, well, this method is written in javascript using jquery. What happens, I added a select to this form and also a function for validating an input field to be required, but the cat's jump is in it, I add a new line, the function copies the current line and creates another one below, right, who does this is the .clone () method, from jquery, and when I edit the line below these changes fall on the line above, my validation function seems to only have an effect on the first line, I'm confused, as I leave and how to solve this bug, I would like a north. Thankful if anyone has a suggestion.

Well, I use another function to make the date field required

So, this function only occurs in the first line, in the cloned lines it does not provide effect, is there a plausible solution to this problem? appreciate

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td>
  <select name='atestado_covid_dispensado[]' onchange='verifica(this.value)'>
    <option value='0' (['atestado_covid_dispensado']!='1'? '' :'selected')>Não</option>
    <option value='1' (['atestado_covid_dispensado']=='1'? 'selected' :'')>Sim</option>
  </select>
</td>
<td>
  <input type='text' id='troca_status' size = '12' class='datepicker' name='atestado_covid[]'>
</td>

Below the script that clones

<!-- begin snippet: js hide: false console: true babel: false --></code>```

this clone method, it adds new lines, but I used the other script to request my field to be validated with required, but it only worked for the first line

this is my method that I want to work for the other cloned lines. but I don't know if this is possible

```

Now I'm going to add the page that results from this code on the site, that is, or I add a new line on +, and the changes are only on the first line, it seems that my id "swap_status" only recognizes the first line.
enter image description here

答: I don't undertand exactly what you are asking, but it seems that the newly added lines are not being validated. From the provided code we can infer that the problem is that the function called "verifica" is using the function called "getElementById" which means that it gets the first element with the given id. If you want to verify all the inputs you'll need to the provide a commom class name to all of the inputs, something like "covid-related-data". After that, get them with "getElementsByClassName" and verify one by one in a loop.</p>

Body:
I have the following doubt, I am maintaining a form using the php language, it has a method that clones all content, that is, the body of a current row table for each time the user wants to create too many rows, well, this method is written in javascript using jquery. What happens, I added a select to this form and also a function for validating an input field to be required, but the cat's jump is in it, I add a new line, the function copies the current line and creates another one below, right, who does this is the .clone () method, from jquery, and when I edit the line below these changes fall on the line above, my validation function seems to only have an effect on the first line, I'm confused, as I leave and how to solve this bug, I would like a north. Thankful if anyone has a suggestion.

Well, I use another function to make the date field required

So, this function only occurs in the first line, in the cloned lines it does not provide effect, is there a plausible solution to this problem? appreciate

  <select name='atestado_covid_dispensado[]' onchange='verifica(this.value)'>
    <option value='0' (['atestado_covid_dispensado']!='1'? '' :'selected')>Não</option>
    <option value='1' (['atestado_covid_dispensado']=='1'? 'selected' :'')>Sim</option>
  </select>

  <input type='text' id='troca_status' size = '12' class='datepicker' name='atestado_covid[]'>

Below the script that clones

this clone method, it adds new lines, but I used the other script to request my field to be validated with required, but it only worked for the first line

this is my method that I want to work for the other cloned lines. but I don't know if this is possible

Now I'm going to add the page that results from this code on the site, that is, or I add a new line on +, and the changes are only on the first line, it seems that my id "swap_status" only recognizes the first line.
enter image description here


问:
Flash dynamic shape resizing
I need to create a designer tool in Flash for laying out how kitchen worktops/countertops look. I found something similar to what I need:

http://www.kitchenplanneronline.com/

If you scroll down the page you place a rooms dimensions onto the workspace, and resize it. If you notice, when you resize the shape moves and a measurement shows on each edge.

Does anyone know how to do this?

答: Program on the page you refer does not seem to work. As I understood you try to change and move measurements each time object is changed. Try to throw events (e.g. "objectResized", "xChanged", "yChanged") in setter of size and coords. And then handle replacing and changing of measurements on those events.

Title: Flash dynamic shape resizing


问:
How to determine how many times '0' to '9' have been used in a specific range instantly
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

```<code>num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)
</code>```

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

答:
To solve this problem efficiently, you can't go through numbers one by one and count up their digits. You need to apply math.

Suppose the upper limit of the range is 123456. Let's try to figure out how many times each possible digit occurs in this range, in the hundreds place.

For every 1000 consecutive integers, each possible digit occurs 100 times in the hundreds place, except for when that digit would be a leading zero. There are 123456//1000=123 full 1000-integer chunks, with 123456%1000=456 integers from 123001 to 123456 left over. The full chunks give us 123*100=12300 occurrences of each digit in the hundreds place, minus 99 for digit 0 because of leading zeros.

In the range from 123001 to 123456, 0 appears 99 times in the hundreds place, each digit from 1 to 3 appears 100 times, and 4 appears 57 times.

Figure out how to formalize this logic enough to implement it in a program, and apply it to every digit place, and you'll easily be able to handle inputs much larger than 2 billion.

Body:
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.


问:
Plugin incompatible with the new build found: Firebase Services

I am not able to update to Android Studio 4.0

When I check for updates, it is showing me the below message.

"Plugin incompatible with the new build found: Firebase Services."

答:
This is the Firebase Services for Android Studio plugin (https://plugins.jetbrains.com/plugin/12667-firebase-services),
(already stated by the message).
This does not prevent you from upgrading to the latest version of Android Studio, it just lets you know that this plugin that you have installed is not compatible with the new version. It shouldn't be such a problem, because you can continue using Firebase Services, you just won't be able to add Firebase Services through the assistant - https://firebase.google.com/docs/android/setup#assistant</p>


问:
Unable to use template file as a template for the component in Liferay angular portlet
Unable to use the template file as a template for the component in Liferay angular portlet. The same syntax is working fine with the plain angular application.

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
    templateUrl: './app.component.html'
    /*
     * I've tried to pass template file path as below but it wasn't worked
     * templateUrl: './app.component.html'
     * templateUrl: './app.component'
     * templateUrl: 'app.component.html'
     * templateUrl: 'app.component'
     */
})

export class AppComponent {}
</code>```

app.component.html

```<code><h1>app component loaded using template file.</h1>
</code>```

Below is my environment detail

OS : windows

Liferay : liferay-ce-portal-tomcat-7.3.2-ga3

node : v8.12.0

angular/cli : ^1.6.7

angular/compiler-cli : ^5.0.0

liferay-npm-bundler : 2.18.2

typescript : 2.4.2

答:
I found the solution from Liferay forum : https://liferay.dev/forums/-/message_boards/message/103176934#_com_liferay_message_boards_web_portlet_MBPortlet_message_106877078

According to the description, I've updated templateUrl path as below and it works fine.

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
    templateUrl: '/o/student-crud-portlet/lib/app/app.component.html'
})

export class AppComponent {}
</code>```

Body:
Unable to use the template file as a template for the component in Liferay angular portlet. The same syntax is working fine with the plain angular application.

app.component.ts

import { Component } from '@angular/core';

@Component({
    templateUrl: './app.component.html'
    /*
     * I've tried to pass template file path as below but it wasn't worked
     * templateUrl: './app.component.html'
     * templateUrl: './app.component'
     * templateUrl: 'app.component.html'
     * templateUrl: 'app.component'
     */
})

export class AppComponent {}

app.component.html

app component loaded using template file.

Below is my environment detail

OS : windows

Liferay : liferay-ce-portal-tomcat-7.3.2-ga3

node : v8.12.0

angular/cli : ^1.6.7

angular/compiler-cli : ^5.0.0

liferay-npm-bundler : 2.18.2

typescript : 2.4.2

Body:
I found the solution from Liferay forum : https://liferay.dev/forums/-/message_boards/message/103176934#_com_liferay_message_boards_web_portlet_MBPortlet_message_106877078

According to the description, I've updated templateUrl path as below and it works fine.

app.component.ts

import { Component } from '@angular/core';

@Component({
    templateUrl: '/o/student-crud-portlet/lib/app/app.component.html'
})

export class AppComponent {}


问:
__PRETTY_FUNCTION equivalent in Python
g++ has this nice variable PRETTY_FUNCTION that contains the name of the function called. For functions it produces the prototype (e.g., "void foo(long)"). For member functions in classes, the name includes the class name (e.g., "void Foo::foo(long)").

Is there an equivalent in Python. I have been playing around with "sys._getframe()" which gets close, but there doesn't seem to be a similarly simple mechanism that includes the class name when it is a member function.

I like to use this in error handlers.

Surely someone has a magical one-liner for this...

TIA,

-Joe

答:
Example Python Code

This is about the closest I can get right now. Search for "<<< here".

Typing Foo.CLNAME is kind of silly. It would be nice if this could somehow be collapsed to an external function and stay outside of the class. There must be a way to do this in Python in a way similar to the way LINE and NAME work.

The implementations of those two are based on code I got from here:

How to determine file, function and line number?

Nice stuff!

-Joe

=====

```<code>#!/usr/bin/env python

# import system modules
#
import os
import sys

# define a hack to get the function name
#
class __MYNAME__(object):
    def __repr__(self):
        try:
            raise Exception
    except:
        return str(sys.exc_info()[2].tb_frame.f_back.f_code.co_name)

    def __init__(self):
        pass

__NAME__ = __MYNAME__()

# define a hack to get the line number in a program
#
class __MYLINE__(object):
    def __repr__(self):
        try:
            raise Exception
        except:
            return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)

__LINE__ = __MYLINE__()

# use these in a function call
#
def joe():
    print("[FUNCTION] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

# use these in a class member function
#
class Foo():

    def __init__(self):
        Foo.__CLNAME__ = self.__class__.__name__

    def joe(self):
        print("[CLASS] name: %s::%s, line: %s" %
              (Foo.__CLNAME__, __NAME__, __LINE__))  # <<< here

#--------------------------------
# test all this in a main program
#--------------------------------
def main(argv):

    # main program
    #
    print("[MAIN PROGRAM] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

    # function call
    #
    joe()

    # class member function
    #
    foo = Foo()
    foo.joe()

    # exit gracefully
    #
    sys.exit(os.EX_OK)

#
# end of main

# begin gracefully
#
if __name__ == "__main__":
    main(sys.argv[0:])

#
# end of file
</code>```

Title: __PRETTY_FUNCTION equivalent in Python

Body:
Example Python Code

This is about the closest I can get right now. Search for "<<< here".

Typing Foo.CLNAME is kind of silly. It would be nice if this could somehow be collapsed to an external function and stay outside of the class. There must be a way to do this in Python in a way similar to the way LINE and NAME work.

The implementations of those two are based on code I got from here:

How to determine file, function and line number?

Nice stuff!

-Joe

=====

#!/usr/bin/env python

# import system modules
#
import os
import sys

# define a hack to get the function name
#
class __MYNAME__(object):
    def __repr__(self):
        try:
            raise Exception
    except:
        return str(sys.exc_info()[2].tb_frame.f_back.f_code.co_name)

    def __init__(self):
        pass

__NAME__ = __MYNAME__()

# define a hack to get the line number in a program
#
class __MYLINE__(object):
    def __repr__(self):
        try:
            raise Exception
        except:
            return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)

__LINE__ = __MYLINE__()

# use these in a function call
#
def joe():
    print("[FUNCTION] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

# use these in a class member function
#
class Foo():

    def __init__(self):
        Foo.__CLNAME__ = self.__class__.__name__

    def joe(self):
        print("[CLASS] name: %s::%s, line: %s" %
              (Foo.__CLNAME__, __NAME__, __LINE__))  # <<< here

#--------------------------------
# test all this in a main program
#--------------------------------
def main(argv):

    # main program
    #
    print("[MAIN PROGRAM] name: %s, line: %s" %
          (__NAME__, __LINE__))                      # <<< here

    # function call
    #
    joe()

    # class member function
    #
    foo = Foo()
    foo.joe()

    # exit gracefully
    #
    sys.exit(os.EX_OK)

#
# end of main

# begin gracefully
#
if __name__ == "__main__":
    main(sys.argv[0:])

#
# end of file


问:
python pandas.read_csv library print everything in one column
I have this python script:

```<code>dati = pd.read_csv(percorso_file,sep='\ s +',
                   engine='python', header=0, usecols=[0])
print(dati)
</code>```

the output is as follows:

```<code>220  T;2;Africa;24;Africa centro meridionale;983;Sa...
221  T;5;Oceania;50;Oceania;988;Terre australi e an...
222  T;4;America;42;America centro meridionale;992;...
223  T;4;America;42;America centro meridionale;994;...
224  T;5;Oceania;50;Oceania;997;Wallis e Futuna;Wal...

[225 rows x 1 columns]
</code>```

It prints me all in one column, when in reality there are 20 of them, how do I get everything printed in multiple columns?

答:
After importing pandas, as an alternative to using the context manager, set such options for displaying entire dataframes:</p>

```<code>pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_colwidth', -1)
</code>```

Body:
I have this python script:

dati = pd.read_csv(percorso_file,sep='\ s +',
                   engine='python', header=0, usecols=[0])
print(dati)

the output is as follows:

220  T;2;Africa;24;Africa centro meridionale;983;Sa...
221  T;5;Oceania;50;Oceania;988;Terre australi e an...
222  T;4;America;42;America centro meridionale;992;...
223  T;4;America;42;America centro meridionale;994;...
224  T;5;Oceania;50;Oceania;997;Wallis e Futuna;Wal...

[225 rows x 1 columns]

It prints me all in one column, when in reality there are 20 of them, how do I get everything printed in multiple columns?

Body:
After importing pandas, as an alternative to using the context manager, set such options for displaying entire dataframes:

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_colwidth', -1)


问:
Passing the serialized data to the controller in MVC through AJAX
I have a view :

```<code>@{
    ViewBag.Title = "Home Page";
}

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
    @section Scripts{

        <script src="~/Scripts/datatable/DataTables-1.10.20/js/jquery.dataTables.min.js"></script>
        <script src="~/Scripts/datatable/DataTables-1.10.20/js/dataTables.jqueryui.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#contenttable").DataTable({

                });

                $("#submitdata").click(function () {
                    var datatabledata = $("#datatble-form").serialize();
                    alert(datatabledata);
                    $.ajax({
                        url: "/Home/getData",
                        type: "POST",
                        data: { model: datatabledata },
                        success: function () {
                            alert('success');
                        },
                        error: function () {
                            alert('failure');
                        }
                    });
                });
            });
        </script>
    }
</head>

<body>
    <form id="datatble-form">
        <table>
            <tr>
                <td>Friend Name</td>
                <td><input name="FriendName" type="text" /></td>
            </tr>
            <tr>
                <td>Friend Age</td>
                <td><input name="FriendAge" type="text" /></td>
            </tr>
            <tr>
                <td>Position</td>
                <td><input name="Friendposition" type="text" /></td>
            </tr>
            <tr>
                <td>Office</td>
                <td><input name="Friendoffice" type="text" /></td>
            </tr>
        </table>

        <input id="submitdata" type="button" value="Submit" />
    </form>
</body>
</html>
</code>```

My controller is :

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using datatableViewTocontroller.Models;

namespace datatableViewTocontroller.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult getData(string model)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            MyClass myClass = jss.Deserialize<MyClass>(model);
            return RedirectToAction("index");
        }

}
</code>```

}

and My Model is :

```<code>namespace datatableViewTocontroller.Models
{
    public class MyClass
    {
        public string FriendName { get; set; }
        public string FriendAge { get; set; }
        public string Friendposition { get; set; }
        public string Friendoffice { get; set; }
    }
}
</code>```

Ok now I ellaborate my problem.
I have a form with the inputs for name, age, position and office and Iam trying to submit the data to the controller by serialize(). The form is getting serialized ( because it is displaying the values in the alert ) and controller call is also successfull like :

but while deserialzing I have got this error :
Invalid JSON primitive: FriendName.
like this :

How can I resolve this issue ? please help..

答:
1.Add serializeObject function to serialize form data to json

```<code><script>
        (function ($) {
            $.fn.serializeObject = function () {

                var self = this,
                    json = {},
                    push_counters = {},
                    patterns = {
                        "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                        "key": /[a-zA-Z0-9_]+|(?=\[\])/g,
                        "push": /^$/,
                        "fixed": /^\d+$/,
                        "named": /^[a-zA-Z0-9_]+$/
                    };

                this.build = function (base, key, value) {
                    base[key] = value;
                    return base;
                };

                this.push_counter = function (key) {
                    if (push_counters[key] === undefined) {
                        push_counters[key] = 0;
                    }
                    return push_counters[key]++;
                };

                $.each($(this).serializeArray(), function () {

                    // Skip invalid keys
                    if (!patterns.validate.test(this.name)) {
                        return;
                    }

                    var k,
                        keys = this.name.match(patterns.key),
                        merge = this.value,
                        reverse_key = this.name;

                    while ((k = keys.pop()) !== undefined) {

                        // Adjust reverse_key
                        reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                        // Push
                        if (k.match(patterns.push)) {
                            merge = self.build([], self.push_counter(reverse_key), merge);
                        }

                        // Fixed
                        else if (k.match(patterns.fixed)) {
                            merge = self.build([], k, merge);
                        }

                        // Named
                        else if (k.match(patterns.named)) {
                            merge = self.build({}, k, merge);
                        }
                    }

                    json = $.extend(true, json, merge);
                });

                return json;
            };
        })(jQuery);
    </script>
        <script>
            $(document).ready(function () {
                $("#contenttable").DataTable({

                });

                $("#submitdata").click(function () {

                    var datatabledata = $("#datatble-form").serializeObject();
                    $.ajax({
                        url: "/Home/getData",
                        type: "POST",
                        dataType: "json",
                        data: { model: datatabledata },
                        crossDomain: true,
                        success: function (result) {
                            if (result.success == true) {
                                window.location = result.redirecturl;
                            }
                        },
                        error: function () {
                            alert('failure');
                        }
                    });
                });
            });
        </script>
</code>```

2. No need to deserialize MyClass in action codes,

```<code>public IActionResult Index(MyClass model)
        {
            return View(model);
        }

        [HttpPost]
        public ActionResult getData(MyClass model)
        {
            //no need to deserialize MyClass
            return Json(new { success = true, redirecturl = Url.Action("Index", "Home", model) });
        }
</code>```

Screenshots of test:

Body:
I have a view :

@{
    ViewBag.Title = "Home Page";
}

    <title></title>
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
    @section Scripts{

    }

    <form id="datatble-form">

                Friend Name
                <input name="FriendName" type="text" />

                Friend Age
                <input name="FriendAge" type="text" />

                Position
                <input name="Friendposition" type="text" />

                Office
                <input name="Friendoffice" type="text" />

        <input id="submitdata" type="button" value="Submit" />
    </form>

My controller is :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using datatableViewTocontroller.Models;

namespace datatableViewTocontroller.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult getData(string model)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            MyClass myClass = jss.Deserialize<MyClass>(model);
            return RedirectToAction("index");
        }

}

}

and My Model is :

namespace datatableViewTocontroller.Models
{
    public class MyClass
    {
        public string FriendName { get; set; }
        public string FriendAge { get; set; }
        public string Friendposition { get; set; }
        public string Friendoffice { get; set; }
    }
}

Ok now I ellaborate my problem.
I have a form with the inputs for name, age, position and office and Iam trying to submit the data to the controller by serialize(). The form is getting serialized ( because it is displaying the values in the alert ) and controller call is also successfull like :

but while deserialzing I have got this error :
Invalid JSON primitive: FriendName.
like this :

How can I resolve this issue ? please help..

Body:
1.Add serializeObject function to serialize form data to json

<script>
        (function ($) {
            $.fn.serializeObject = function () {

                var self = this,
                    json = {},
                    push_counters = {},
                    patterns = {
                        "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                        "key": /[a-zA-Z0-9_]+|(?=\[\])/g,
                        "push": /^$/,
                        "fixed": /^\d+$/,
                        "named": /^[a-zA-Z0-9_]+$/
                    };

                this.build = function (base, key, value) {
                    base[key] = value;
                    return base;
                };

                this.push_counter = function (key) {
                    if (push_counters[key] === undefined) {
                        push_counters[key] = 0;
                    }
                    return push_counters[key]++;
                };

                $.each($(this).serializeArray(), function () {

                    // Skip invalid keys
                    if (!patterns.validate.test(this.name)) {
                        return;
                    }

                    var k,
                        keys = this.name.match(patterns.key),
                        merge = this.value,
                        reverse_key = this.name;

                    while ((k = keys.pop()) !== undefined) {

                        // Adjust reverse_key
                        reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                        // Push
                        if (k.match(patterns.push)) {
                            merge = self.build([], self.push_counter(reverse_key), merge);
                        }

                        // Fixed
                        else if (k.match(patterns.fixed)) {
                            merge = self.build([], k, merge);
                        }

                        // Named
                        else if (k.match(patterns.named)) {
                            merge = self.build({}, k, merge);
                        }
                    }

                    json = $.extend(true, json, merge);
                });

                return json;
            };
        })(jQuery);
    </script>
        <script>
            $(document).ready(function () {
                $("#contenttable").DataTable({

                });

                $("#submitdata").click(function () {

                    var datatabledata = $("#datatble-form").serializeObject();
                    $.ajax({
                        url: "/Home/getData",
                        type: "POST",
                        dataType: "json",
                        data: { model: datatabledata },
                        crossDomain: true,
                        success: function (result) {
                            if (result.success == true) {
                                window.location = result.redirecturl;
                            }
                        },
                        error: function () {
                            alert('failure');
                        }
                    });
                });
            });
        </script>

2. No need to deserialize MyClass in action codes,

public IActionResult Index(MyClass model)
        {
            return View(model);
        }

        [HttpPost]
        public ActionResult getData(MyClass model)
        {
            //no need to deserialize MyClass
            return Json(new { success = true, redirecturl = Url.Action("Index", "Home", model) });
        }

Screenshots of test:


问:
SQL server loses connection after one minutre
I am using Heroku and a Clear DB for a python script I made. The script seems to work if after the bot is deployed in Discord, it will collect the information of a user and reply back to them after it collects a certain number of entries. However, If there are no messages during a minute's time, I get the following error in my terminal:

```<code> File "C:\Users\Chase The Great\Anaconda3\lib\site-packages\mysql\connector\network.py", line 251, in recv_plain
    raise errors.InterfaceError(errno=2013)
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query
</code>```

Is there a way to make the connection active again or make the connection indefinite?

I am using the module mysql.connector for communicating to the DB. Here is some of my code if there is an inaccuracy for how I am writing it:

```<code>async def on_message(message):
    sql_users_info = "SELECT * FROM host_server.user_levels;"
    mycursor.execute(sql_users_info)
    user_info = mycursor.fetchall()
    user_names = []
    user_exp = []
    for i in user_info:
        user_names.append(i[0])
        user_exp.append(i[1])
    await update_data(user_names, message.author)
    await add_experience(user_names, message.author, user_exp)
    await level_up(user_names, message.author, message.channel)
    await client.process_commands(message)
</code>```

答:
I was able to figure out what the issue was. Connections need to be reestablished when Databases are not in use. Inside the await commands you use the following:

```<code>mydb = mysql.connector.connect(
 host="localhost",
 user="yourusername",
 passwd="yourpassword")
 mycursor = mydb.cursor()
 mycursor.execute("YOUR SQL CODE")
</code>```

You will need to do this every time a message is sent.

Body:
I am using Heroku and a Clear DB for a python script I made. The script seems to work if after the bot is deployed in Discord, it will collect the information of a user and reply back to them after it collects a certain number of entries. However, If there are no messages during a minute's time, I get the following error in my terminal:

 File "C:\Users\Chase The Great\Anaconda3\lib\site-packages\mysql\connector\network.py", line 251, in recv_plain
    raise errors.InterfaceError(errno=2013)
mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query

Is there a way to make the connection active again or make the connection indefinite?

I am using the module mysql.connector for communicating to the DB. Here is some of my code if there is an inaccuracy for how I am writing it:

async def on_message(message):
    sql_users_info = "SELECT * FROM host_server.user_levels;"
    mycursor.execute(sql_users_info)
    user_info = mycursor.fetchall()
    user_names = []
    user_exp = []
    for i in user_info:
        user_names.append(i[0])
        user_exp.append(i[1])
    await update_data(user_names, message.author)
    await add_experience(user_names, message.author, user_exp)
    await level_up(user_names, message.author, message.channel)
    await client.process_commands(message)

Body:
I was able to figure out what the issue was. Connections need to be reestablished when Databases are not in use. Inside the await commands you use the following:

mydb = mysql.connector.connect(
 host="localhost",
 user="yourusername",
 passwd="yourpassword")
 mycursor = mydb.cursor()
 mycursor.execute("YOUR SQL CODE")

You will need to do this every time a message is sent.


问:
How can I install pip when there is already python but pip is missed?
I'm using a remote server, which some others use together.

There are several versions of python installed.

I need python 3.6 version, and I can run it with  /bin/python3.6 command.

And I also want to make a virtualenv of the version, so I tried /bin/python3.6 -m pip --version

But it showed

/bin/python3.6: No module named pip
```

<p>When I checked the lib directory, <code>ll /usr/lib/python3.6/site-packages/</code></p>

<pre class="lang-none prettyprint-override"><code>total 0 drwxr-xr-x 2 root root 6 Dec 20  2017 __pycache__
</code>```

It seems that the server has python3.6, but misses pip for that, right?

How can I resolve this, with the minimum modification?

The server is centos7.

Any thought or comment appreciated :)

答:
As drum mentioned at the comment, I installed pip referring to pip.pypa.io/en/stable/installing.

I ran the python file with /usr/bin/python3.6 get-pip.py.

After installing virtualenv, I faced virtualenv not found error.

You can solve the above error with the following link.(It was a path issue) Virtualenv Command Not Found

Body:
I'm using a remote server, which some others use together.

There are several versions of python installed.

I need python 3.6 version, and I can run it with  /bin/python3.6 command.

And I also want to make a virtualenv of the version, so I tried /bin/python3.6 -m pip --version

But it showed

/bin/python3.6: No module named pip

When I checked the lib directory, ll /usr/lib/python3.6/site-packages/

total 0 drwxr-xr-x 2 root root 6 Dec 20  2017 __pycache__

It seems that the server has python3.6, but misses pip for that, right?

How can I resolve this, with the minimum modification?

The server is centos7.

Any thought or comment appreciated :)