content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
30
130
Q: How to migrate from Nexus Professional to Nexus OSS I want to "downgrade" an installation of Nexus Professional 2.x to Nexus OSS 2.x. Is it possible? What do I have to do? A: Yes, it is not a complicated task. Install Nexus OSS on the same server. Do change the following so that the new Nexus OSS has the same configuration as the existing Nexus Professional runtime. Configuration port is set in [runtime]/conf/nexus.properties sonatype-work directory location is set in [runtime]/conf/nexus.properties the java command is set in [runtime]/bin/jsw/conf/wrapper.conf the log directory location is set in [runtime]/conf/nexus.properties Process Stop the Professional Make sure to backup the sonatype-work/nexus/conf directory Remove the professional plugins from sonatype-work/nexus/plugin-repository Add the p2 plugins for OSS to the sonatype-work/nexus/plugin-repository sonatype-work/nexus/conf/nexus.xml Remove procurement repositories references from nexus.xml Remove Scheduled task that use the professional plugins or features from from nexus.xml Note: Those two tasks could have been done from the Nexus Professional UI before stopping it. Remove User-Token-Realm from the sonatype-work/nexus/conf/security-configuration.xml Start the Nexus OSS start preferably with nexus console instead of nexus start, so it shows more information check the [runtime]/logs/wrapper.log check the sonatype-work-nexus/logs/nexus.log A: As a note: If your license to Nexus 3 Pro has expired, when you log in to the UI, you cannot access anything in the admin UI. You are only redirected back to the License screen with a stern warning message that you don't have a valid license. I tried removing all Pro plugins etc as in the earlier answer. Tried finding where the Pro licenser was stored on file - but could not find any documentation from Sonatype of this. I assumed it was stored somewhere in the database. In my case I worked with an evaluation server, so I removed the whole sonatype-work/nexus3 directory and restarted the nexus server. Even without data, it still claimed to be a Nexus Pro installation. Finally I found the setting stored in the users home directory, in ~/.java/.userPrefs/com/sonatype of all places. When that directory was removed/renamed I could start Nexus as a regular OSS. It's not easy to find this in Sonatypes documentation, but they mention it in some places like: https://support.sonatype.com/hc/en-us/articles/213465018-Every-time-Nexus-is-restarted-it-asks-for-the-license-to-be-installed- A: The accepted answer to this question is old and doesn't work for the current version (Feb 2021 v3.29) of the Nexus. Here are few things that I would like to add. These are crucial and essential for the Nexus OSS to work. Make sure that you are downloading the OSS If you just copy the configurations and point to the blobs it doesn't work. You need to take a backup of OrientDB of Nexus and restore it, then only blobs and repositories will be recognized by the Nexus. Without OrientDB, blobs mean nothing to the Nexus. I will add detailed steps to this answer when I will get some more time. I just put the important points in brief to unblock people who may be stuck just like I was. A: Here is Sonatype instruction to downgrade Nexus 3 Pro to Nexus 3 OSS: https://support.sonatype.com/hc/en-us/articles/115015608967-How-to-downgrade-from-Nexus-3-Pro-to-Nexus-3-OSS A: I just ran into the expired PRO license scenario, and unfortunately I was unable to turn off the PRO realms (User Token, specifically) that were active. Luckily, Nexus3 exposes a REST API that can be used for that purpose, and after following Sonatype's instructions to boot back into OSS mode, I was able to use one of those APIs to disable the PRO-only realms that I had enabled. Otherwise the Realms page wouldn't load. The API page is at ${YOUR_NEXUS_URL}/#admin/system/api And there you can just search in the page for the realm-related (or other) APIs. Hopefully you'll find this useful ...
How to migrate from Nexus Professional to Nexus OSS
I want to "downgrade" an installation of Nexus Professional 2.x to Nexus OSS 2.x. Is it possible? What do I have to do?
[ "Yes, it is not a complicated task. \nInstall Nexus OSS on the same server.\nDo change the following so that the new Nexus OSS has the same configuration as the existing Nexus Professional runtime.\nConfiguration\n\nport is set in [runtime]/conf/nexus.properties\nsonatype-work directory location is set in [runtime]/conf/nexus.properties\nthe java command is set in [runtime]/bin/jsw/conf/wrapper.conf \nthe log directory location is set in [runtime]/conf/nexus.properties\n\nProcess\n\nStop the Professional\nMake sure to backup the sonatype-work/nexus/conf directory\nRemove the professional plugins from sonatype-work/nexus/plugin-repository\nAdd the p2 plugins for OSS to the sonatype-work/nexus/plugin-repository\nsonatype-work/nexus/conf/nexus.xml\nRemove procurement repositories references from nexus.xml\nRemove Scheduled task that use the professional plugins or features from from nexus.xml \nNote: Those two tasks could have been done from the Nexus Professional UI before stopping it. \nRemove User-Token-Realm from the sonatype-work/nexus/conf/security-configuration.xml\n\nStart the Nexus OSS\n\nstart preferably with nexus console instead of nexus start, so it shows more information\ncheck the [runtime]/logs/wrapper.log \ncheck the sonatype-work-nexus/logs/nexus.log\n\n", "As a note: If your license to Nexus 3 Pro has expired, when you log in to the UI, you cannot access anything in the admin UI. You are only redirected back to the License screen with a stern warning message that you don't have a valid license.\nI tried removing all Pro plugins etc as in the earlier answer. Tried finding where the Pro licenser was stored on file - but could not find any documentation from Sonatype of this. I assumed it was stored somewhere in the database.\nIn my case I worked with an evaluation server, so I removed the whole sonatype-work/nexus3 directory and restarted the nexus server. Even without data, it still claimed to be a Nexus Pro installation.\nFinally I found the setting stored in the users home directory, in ~/.java/.userPrefs/com/sonatype of all places.\nWhen that directory was removed/renamed I could start Nexus as a regular OSS.\nIt's not easy to find this in Sonatypes documentation, but they mention it in some places like: https://support.sonatype.com/hc/en-us/articles/213465018-Every-time-Nexus-is-restarted-it-asks-for-the-license-to-be-installed-\n", "The accepted answer to this question is old and doesn't work for the current version (Feb 2021 v3.29) of the Nexus.\nHere are few things that I would like to add. These are crucial and essential for the Nexus OSS to work.\n\nMake sure that you are downloading the OSS\n\nIf you just copy the configurations and point to the blobs it doesn't work. You need to take a backup of OrientDB of Nexus and restore it, then only blobs and repositories will be recognized by the Nexus.\n\n\nWithout OrientDB, blobs mean nothing to the Nexus. I will add detailed steps to this answer when I will get some more time. I just put the important points in brief to unblock people who may be stuck just like I was.\n", "Here is Sonatype instruction to downgrade Nexus 3 Pro to Nexus 3 OSS:\nhttps://support.sonatype.com/hc/en-us/articles/115015608967-How-to-downgrade-from-Nexus-3-Pro-to-Nexus-3-OSS\n", "I just ran into the expired PRO license scenario, and unfortunately I was unable to turn off the PRO realms (User Token, specifically) that were active.\nLuckily, Nexus3 exposes a REST API that can be used for that purpose, and after following Sonatype's instructions to boot back into OSS mode, I was able to use one of those APIs to disable the PRO-only realms that I had enabled. Otherwise the Realms page wouldn't load.\nThe API page is at\n\n${YOUR_NEXUS_URL}/#admin/system/api\n\nAnd there you can just search in the page for the realm-related (or other) APIs.\nHopefully you'll find this useful ...\n" ]
[ 4, 2, 0, 0, 0 ]
[]
[]
[ "maven", "nexus", "nexus2", "repository" ]
stackoverflow_0033689175_maven_nexus_nexus2_repository.txt
Q: python not recognized in Windows CMD even after adding to PATH I'm trying to -learn to write and- run Python scripts on my Windows 7 64 bit machine. I installed Python in C:/Python34, and I added this to my Windows' PATH variable : C:\Python34; C:\Python34\python.exe (the second one is probably meaningless but I tried) and still I get this error in Windows command line : C:\Users\me>python test.py 'python' is not recognized as an internal or external command, operable program or batch file. So how do I truly install Python on my Windows x64 machine ? A: This might be trivial, but have you tried closing your command line window and opening a new one? This is supposed to reload all the environment variables. Try typing echo %PATH% into the command prompt and see if you can find your Python directory there. Also, the second part of your addition to the PATH environment variable is indeed unnecessary. A: I had the same problem: python not being recognized, with python in the path which was was not truncated. Following the comment of eryksun in yossim's answer: Also, if you installed for all users you should have %SystemRoot%\py.exe, which >is typically C:\Windows\py.exe. So without setting Python's directory in PATH >you can simply run py to start Python; if 2.x is installed use py -3 since >Python 2 is the default. – eryksun I tried to use py instead of python and it worked. Meaning: python setup.py build -> does NOT work. py setup.py build -> does work. Hope it helps A: I was also having the same problem. Turns out the path I added included '..\python.exe' at the end, which as turns out was not required. I only needed to add the directory in which 'python.exe' is in (which in my case is the Anaconda's distribution directory in Users folder), similar to what we do when installing JDK in our system's PATH variable. Hope it helps! A: It wasn't working for me even after adding the path. What finally did the trick, was changing the order of listed paths in the PATH variable. I moved %USERPROFILE%\AppData\Local\Microsoft\WindowsApps down vs. having it the first path listed there. A: Environment PATH Length Limitation is 1024 characters If restarting your cmd window does not work you might have reached the character limit for PATH, which is a surprisingly short 1024 characters. Note that the user interface will happily allows you to define a PATH that is way longer than 1024, and will just truncate anything longer than this. Use echo %PATH% in your cmd window to see if the PATH being truncated. Solution Unfortunately, there is no good way to fix this besides removing something else from your PATH. NOTE: Your PATH = SYSTEM_PATH + USER_PATH, so you need to make sure the combined is < 1024. A: Also, make sure to leave no spaces after the semi-colon. For example, this didn't work for me: C:\Windows\system32; C:\Python27; C:\Python27\Scripts; But, this did: C:\Windows\system32;C:\Python27;C:\Python27\Scripts; A: I'm late to the game here, but I'd like to share my solution for future users. The previous answers were on the right track, but if you do not open the CMD as an administrator, then you will be thrown that same error. I know this seems trivial and obvious, but after spending the past 8 hours programming before attempting to install Django for the first time, you might be surprised at the stupid mistakes you might make. A: I have faced same problem even though my path contains 400 characters. Try to update the path from the command line(Run as administrator) Command to update path: setx path "%path%;c:\examplePath" After this command I could see that paths that I configured earlier in environment variables got updated and working. To check the configured paths: echo %PATH% A: I was facing similar porblem. What helped me is where command. C:\WINDOWS\system32>where python C:\Users\xxxxxxx\AppData\Local\Microsoft\WindowsApps\python.exe C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_86\python.exe On updating PATH variable to point to only one desired directory (basically I removed %USERPROFILE%\AppData\Local\Microsoft\WindowsApps from PATH) fixed my problem. A: I had the same issue with Python 2.7 on Windows 10 until I changed the file path in Enviroment Variables to the folder path, ie C:\Python27\python.exe didn't work but C:\Python27\ did work. A: I did everything: Added Python to PATH Uninstall all the Pythons - Both from downloaded python.org and Microsoft Store and reinstall from python.org Change the order of PATH Deleted %USERPROFILE%\AppData\Local\Microsoft\WindowsApps from PATH But nothing worked. What worked for me was: Settings > Application > App execution aliases. Then disable all the Pyhtons from here and it worked!
python not recognized in Windows CMD even after adding to PATH
I'm trying to -learn to write and- run Python scripts on my Windows 7 64 bit machine. I installed Python in C:/Python34, and I added this to my Windows' PATH variable : C:\Python34; C:\Python34\python.exe (the second one is probably meaningless but I tried) and still I get this error in Windows command line : C:\Users\me>python test.py 'python' is not recognized as an internal or external command, operable program or batch file. So how do I truly install Python on my Windows x64 machine ?
[ "This might be trivial, but have you tried closing your command line window and opening a new one? This is supposed to reload all the environment variables.\nTry typing\necho %PATH%\n\ninto the command prompt and see if you can find your Python directory there.\nAlso, the second part of your addition to the PATH environment variable is indeed unnecessary.\n", "I had the same problem: python not being recognized, with python in the path which was was not truncated. \nFollowing the comment of eryksun in yossim's answer:\n\nAlso, if you installed for all users you should have %SystemRoot%\\py.exe, which >is typically C:\\Windows\\py.exe. So without setting Python's directory in PATH >you can simply run py to start Python; if 2.x is installed use py -3 since >Python 2 is the default. – eryksun \n\nI tried to use py instead of python and it worked.\nMeaning: \npython setup.py build -> does NOT work.\npy setup.py build -> does work.\nHope it helps\n", "I was also having the same problem.\nTurns out the path I added included '..\\python.exe' at the end, which as turns out was not required. I only needed to add the directory in which 'python.exe' is in (which in my case is the Anaconda's distribution directory in Users folder), similar to what we do when installing JDK in our system's PATH variable.\nHope it helps!\n", "It wasn't working for me even after adding the path. What finally did the trick, was changing the order of listed paths in the PATH variable. I moved %USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps down vs. having it the first path listed there.\n", "Environment PATH Length Limitation is 1024 characters\nIf restarting your cmd window does not work you might have reached the character limit for PATH, which is a surprisingly short 1024 characters.\nNote that the user interface will happily allows you to define a PATH that is way longer than 1024, and will just truncate anything longer than this. Use\necho %PATH%\n\nin your cmd window to see if the PATH being truncated.\nSolution\nUnfortunately, there is no good way to fix this besides removing something else from your PATH.\n\nNOTE: Your PATH = SYSTEM_PATH + USER_PATH, so you need to make sure the combined is < 1024.\n", "Also, make sure to leave no spaces after the semi-colon.\nFor example, this didn't work for me:\nC:\\Windows\\system32; C:\\Python27; C:\\Python27\\Scripts;\nBut, this did:\nC:\\Windows\\system32;C:\\Python27;C:\\Python27\\Scripts;\n", "I'm late to the game here, but I'd like to share my solution for future users. The previous answers were on the right track, but if you do not open the CMD as an administrator, then you will be thrown that same error. I know this seems trivial and obvious, but after spending the past 8 hours programming before attempting to install Django for the first time, you might be surprised at the stupid mistakes you might make.\n", "I have faced same problem even though my path contains 400 characters.\nTry to update the path from the command line(Run as administrator)\nCommand to update path: setx path \"%path%;c:\\examplePath\"\nAfter this command I could see that paths that I configured earlier in environment variables got updated and working.\nTo check the configured paths: echo %PATH%\n", "I was facing similar porblem. What helped me is where command.\n\nC:\\WINDOWS\\system32>where python\nC:\\Users\\xxxxxxx\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe\nC:\\Program Files (x86)\\Microsoft Visual\nStudio\\Shared\\Python39_86\\python.exe\n\nOn updating PATH variable to point to only one desired directory (basically I removed %USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps from PATH) fixed my problem.\n", "I had the same issue with Python 2.7 on Windows 10 until I changed the file path in Enviroment Variables to the folder path, ie C:\\Python27\\python.exe didn't work but C:\\Python27\\ did work.\n", "I did everything:\n\nAdded Python to PATH\nUninstall all the Pythons - Both from downloaded python.org and Microsoft Store and reinstall from python.org\nChange the order of PATH\nDeleted %USERPROFILE%\\AppData\\Local\\Microsoft\\WindowsApps from PATH\n\nBut nothing worked. What worked for me was:\nSettings > Application > App execution aliases. Then disable all the Pyhtons from here and it worked!\n\n" ]
[ 24, 22, 8, 6, 4, 2, 1, 1, 1, 0, 0 ]
[ "For me, installing the 'Windows x86-64 executable installer' from the official python portal did the trick.\nPython interpreter was not initially recognized, while i had installed 32 bit python.\nUninstalled python 32 bit and installed 64 bit.\nSo, if you are on a x-64 processor, install 64bit python.\n", "I tried it multiple times with the default installer option, the first one, (Python 3.7.3) with both 'add to environment variable' and 'all users' checked, though the latter was greyed out and couldn't be unchecked.\nIt failed to work for other users except for the user I installed it under until I uninstalled it and chose \"Custom Install\". It then clearly showed the install path being in the C:\\Program Files\\Python37 directory when it was failing to install it there the other way even though the 'All Users' option was checked.\n", "Same thing was happening with me when i was trying to open the python immediately with CMD.\nThen I kept my in sleep mode and started CMD using these Key Windows_key+R, typed cmd and OK. Then the package of python worked perfectly.\n", "\nUninstall python and pyqt\nThen go to pyqt setup and open installation but don't install. You will see a message box saying something like pyqt version built with python version 32bit/64bit. \nThen see python version bit and download that version from python.org from all release menu. \nThen first install python and then install pyqt. It will work like butter.\n\n", "I spent sometime checking and rechecking the path and restarting to no avail.\nThe only thing that worked for me was to rename the executable C:\\Python34\\python.exe to C:\\Python34\\python34.exe. This way, calling typing python34 at the command line now works.\nOn windows it seems that when calling 'python', the system finds C:\\Python27 in the path before it finds C:\\Python34\nI'm not sure if this is the right way to do this, seems like a hack, but it seems to work OK.\n" ]
[ -1, -1, -1, -1, -2 ]
[ "cmd", "command_line", "python", "python_3.x", "windows" ]
stackoverflow_0024186823_cmd_command_line_python_python_3.x_windows.txt
Q: How to convert YOLO format annotations to x1, y1, x2, y2 coordinates in Python? I would like to know how to convert annotations in YOLO format (e.g., center_X, center_y, width, height = 0.069824, 0.123535, 0.104492, 0.120117) to x1, y1, x2, y2 coordinates? A: If I recall correctly: x1 = (center_X-width/2)*image_width x2 = (center_X+width/2)*image_width y1 = (center_y-height/2)*image_height y2 = (center_y+height/2)*image_height A: Given that the upper-left corner of the image is [0,0]: For the upper-left corner you have to do [x,y] = [center_X, center_Y] - 1/2 * [width, height] . For the bottom-right corner [x,y] = [center_X, center_Y] + 1/2 * [width, height] . A: def get_coord(label_file, img_width, img_height): lfile = open(label_file) coords = [] all_coords = [] for line in lfile: l = line.split(" ") coords = list(map(float, list(map(float, l[1:5])))) x1 = float(img_width) * (2.0 * float(coords[0]) - float(coords[2])) / 2.0 y1 = float(img_height) * (2.0 * float(coords[1]) - float(coords[3])) / 2.0 x2 = float(img_width) * (2.0 * float(coords[0]) + float(coords[2])) / 2.0 y2 = float(img_height) * (2.0 * float(coords[1]) + float(coords[3])) / 2.0 tmp = [x1, y1, x2, y2] all_coords.append(list(map(int, tmp))) lfile.close() return all_coords
How to convert YOLO format annotations to x1, y1, x2, y2 coordinates in Python?
I would like to know how to convert annotations in YOLO format (e.g., center_X, center_y, width, height = 0.069824, 0.123535, 0.104492, 0.120117) to x1, y1, x2, y2 coordinates?
[ "If I recall correctly:\nx1 = (center_X-width/2)*image_width\nx2 = (center_X+width/2)*image_width\ny1 = (center_y-height/2)*image_height\ny2 = (center_y+height/2)*image_height\n\n", "Given that the upper-left corner of the image is [0,0]: For the upper-left corner you have to do [x,y] = [center_X, center_Y] - 1/2 * [width, height] . For the bottom-right corner [x,y] = [center_X, center_Y] + 1/2 * [width, height] .\n", "def get_coord(label_file, img_width, img_height):\n\nlfile = open(label_file)\ncoords = []\nall_coords = []\n\nfor line in lfile:\n l = line.split(\" \")\n \n coords = list(map(float, list(map(float, l[1:5]))))\n x1 = float(img_width) * (2.0 * float(coords[0]) - float(coords[2])) / 2.0\n y1 = float(img_height) * (2.0 * float(coords[1]) - float(coords[3])) / 2.0\n x2 = float(img_width) * (2.0 * float(coords[0]) + float(coords[2])) / 2.0\n y2 = float(img_height) * (2.0 * float(coords[1]) + float(coords[3])) / 2.0\n tmp = [x1, y1, x2, y2]\n all_coords.append(list(map(int, tmp)))\nlfile.close()\nreturn all_coords\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "computer_vision", "python", "yolo" ]
stackoverflow_0066801530_computer_vision_python_yolo.txt
Q: Selenide / Jenkins: java.lang.IllegalStateException: No webdriver is bound to current thread: I have some tests written in Selenide/Java. Also I have local Jenkins on my Windows, tests are running under this Jenkins perfectly, but i have problem with tests from same repository running on external Jenkins (Linux) Logs from Jenkins: [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running [1mTests[m ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2 1491 [main] INFO com.github.javafaker.Faker - Using default locale en Jul 08, 2019 2:36:49 PM com.codeborne.selenide.drivercommands.LazyDriver getAndCheckWebDriver INFO: No webdriver is bound to current thread: 1 - let's create a new webdriver Jul 08, 2019 2:36:49 PM java.util.prefs.FileSystemPreferences$1 run INFO: Created user preferences directory. 2687 [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Reading https://chromedriver.storage.googleapis.com/ to seek chromedriver 3700 [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Latest version of chromedriver is 76.0.3809.25 3704 [main] INFO io.github.bonigarcia.wdm.Downloader - Downloading https://chromedriver.storage.googleapis.com/76.0.3809.25/chromedriver_linux64.zip 4066 [main] INFO io.github.bonigarcia.wdm.Downloader - Extracting binary from compressed file chromedriver_linux64.zip 4194 [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as /var/lib/jenkins/.m2/repository/webdriver/chromedriver/linux64/76.0.3809.25/chromedriver Starting ChromeDriver 76.0.3809.25 (a0c95f440512e06df1c9c206f2d79cc20be18bb1-refs/branch-heads/3809@{#271}) on port 28990 Only local connections are allowed. Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code. Jul 08, 2019 2:36:52 PM com.codeborne.selenide.drivercommands.LazyDriver getAndCheckWebDriver INFO: No webdriver is bound to current thread: 1 - let's create a new webdriver Starting ChromeDriver 76.0.3809.25 (a0c95f440512e06df1c9c206f2d79cc20be18bb1-refs/branch-heads/3809@{#271}) on port 30572 Only local connections are allowed. Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code. [ERROR] [1;31mTests [0;1mrun: [0;1m3[m, [1;31mFailures: [0;1;31m3[m, Errors: 0, Skipped: 0, Time elapsed: 5.878 s[1;31m <<< FAILURE![m - in [1mTests[m [ERROR] test001_logowanie_programs(Tests) Time elapsed: 3.105 s <<< FAILURE! java.lang.IllegalStateException: No webdriver is bound to current thread: 1. You need to call open(url) first. at Tests.test001_logowanie_programs(Tests.java:38) [ERROR] test002_logowanie_evaluation(Tests) Time elapsed: 0.058 s <<< FAILURE! java.lang.IllegalStateException: No webdriver is bound to current thread: 1. You need to call open(url) first. at Tests.test002_logowanie_evaluation(Tests.java:50) [ERROR] test003_fail(Tests) Time elapsed: 0.159 s <<< FAILURE! java.lang.IllegalStateException: No webdriver is bound to current thread: 1. You need to call open(url) first. at Tests.test003_fail(Tests.java:67) [INFO] [INFO] Results: [INFO] [ERROR] [1;31mFailures: [m [ERROR] [1;31m Tests.test001_logowanie_programs:38 » IllegalState No webdriver is bound to cu...[m [ERROR] [1;31m Tests.test002_logowanie_evaluation:50 » IllegalState No webdriver is bound to ...[m [ERROR] [1;31m Tests.test003_fail:67 » IllegalState No webdriver is bound to current thread: ...[m [INFO] [ERROR] [1;31mTests run: 3, Failures: 3, Errors: 0, Skipped: 0[m [INFO] [ERROR] There are test failures. Please refer to /var/lib/jenkins/jobs/nawa_selenide/workspace/target/surefire-reports for the individual test results. Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream. [JENKINS] Recording test results [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 20.071 s [INFO] Finished at: 2019-07-08T14:36:56+02:00 [INFO] Final Memory: 31M/330M [INFO] ------------------------------------------------------------------------ Waiting for Jenkins to finish collecting data [JENKINS] Archiving /var/lib/jenkins/jobs/nawa_selenide/workspace/pom.xml to com/nawa/1.0-SNAPSHOT/nawa-1.0-SNAPSHOT.pom channel stopped Finished: UNSTABLE On every test we have: java.lang.IllegalStateException: No webdriver is bound to current thread: Do You have experience with similar situation? Why on local machine tests are done correctly, but on main Jenkins in company there are only failures caused by No webdriver is bound to current thread? Only operating system is difference. This is problem with jenkins configuration under Linux? When I run the tests locally, using Jenkins (with Maven), I get the same message, but the WebDriver is actually created and runs my test cases. My maven goals are: mvn clean test -Puat Declaration of Chrome in tests: @BeforeClass public void setUp() throws Exception { Configuration.holdBrowserOpen = false; Configuration.browser = "chrome"; Configuration.timeout = 10000; Configuration.headless = true; SelenideLogger.addListener("AllureSelenide", new AllureSelenide().screenshots(true).savePageSource(true)); objReader.environmentPropertiesLoader(); } _______________edit Now i check Start Xvfb before the build, and shut it down after in Jenkins job Build Environment, i read that is very important, maybe xvfb is the cause, i dont know, now in console i have java.io.IOException: Cannot run program "Xvfb": error=2, No such file or directory A: Did anyone answer? You need to call open Url as the error says. driver.open(URL HERE) at the end of your setup method. A: this is my solution: after open(), store current webDriver, and before use - restore webDriver WebDriver webDriver; // constructor public SelenideCommand() { Configuration.holdBrowserOpen = true; Selenide.open("https://www.instagram.com/"); webDriver = WebDriverRunner.getWebDriver(); } public void login(String userName, String password) { WebDriverRunner.setWebDriver(webDriver); Selenide.element(Selectors.byName("username")).setValue(userName); Selenide.element(Selectors.byName("password")).setValue(password); Selenide.elements(Selectors.byTagName("button")).get(1).click(); }
Selenide / Jenkins: java.lang.IllegalStateException: No webdriver is bound to current thread:
I have some tests written in Selenide/Java. Also I have local Jenkins on my Windows, tests are running under this Jenkins perfectly, but i have problem with tests from same repository running on external Jenkins (Linux) Logs from Jenkins: [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running [1mTests[m ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2 1491 [main] INFO com.github.javafaker.Faker - Using default locale en Jul 08, 2019 2:36:49 PM com.codeborne.selenide.drivercommands.LazyDriver getAndCheckWebDriver INFO: No webdriver is bound to current thread: 1 - let's create a new webdriver Jul 08, 2019 2:36:49 PM java.util.prefs.FileSystemPreferences$1 run INFO: Created user preferences directory. 2687 [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Reading https://chromedriver.storage.googleapis.com/ to seek chromedriver 3700 [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Latest version of chromedriver is 76.0.3809.25 3704 [main] INFO io.github.bonigarcia.wdm.Downloader - Downloading https://chromedriver.storage.googleapis.com/76.0.3809.25/chromedriver_linux64.zip 4066 [main] INFO io.github.bonigarcia.wdm.Downloader - Extracting binary from compressed file chromedriver_linux64.zip 4194 [main] INFO io.github.bonigarcia.wdm.WebDriverManager - Exporting webdriver.chrome.driver as /var/lib/jenkins/.m2/repository/webdriver/chromedriver/linux64/76.0.3809.25/chromedriver Starting ChromeDriver 76.0.3809.25 (a0c95f440512e06df1c9c206f2d79cc20be18bb1-refs/branch-heads/3809@{#271}) on port 28990 Only local connections are allowed. Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code. Jul 08, 2019 2:36:52 PM com.codeborne.selenide.drivercommands.LazyDriver getAndCheckWebDriver INFO: No webdriver is bound to current thread: 1 - let's create a new webdriver Starting ChromeDriver 76.0.3809.25 (a0c95f440512e06df1c9c206f2d79cc20be18bb1-refs/branch-heads/3809@{#271}) on port 30572 Only local connections are allowed. Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code. [ERROR] [1;31mTests [0;1mrun: [0;1m3[m, [1;31mFailures: [0;1;31m3[m, Errors: 0, Skipped: 0, Time elapsed: 5.878 s[1;31m <<< FAILURE![m - in [1mTests[m [ERROR] test001_logowanie_programs(Tests) Time elapsed: 3.105 s <<< FAILURE! java.lang.IllegalStateException: No webdriver is bound to current thread: 1. You need to call open(url) first. at Tests.test001_logowanie_programs(Tests.java:38) [ERROR] test002_logowanie_evaluation(Tests) Time elapsed: 0.058 s <<< FAILURE! java.lang.IllegalStateException: No webdriver is bound to current thread: 1. You need to call open(url) first. at Tests.test002_logowanie_evaluation(Tests.java:50) [ERROR] test003_fail(Tests) Time elapsed: 0.159 s <<< FAILURE! java.lang.IllegalStateException: No webdriver is bound to current thread: 1. You need to call open(url) first. at Tests.test003_fail(Tests.java:67) [INFO] [INFO] Results: [INFO] [ERROR] [1;31mFailures: [m [ERROR] [1;31m Tests.test001_logowanie_programs:38 » IllegalState No webdriver is bound to cu...[m [ERROR] [1;31m Tests.test002_logowanie_evaluation:50 » IllegalState No webdriver is bound to ...[m [ERROR] [1;31m Tests.test003_fail:67 » IllegalState No webdriver is bound to current thread: ...[m [INFO] [ERROR] [1;31mTests run: 3, Failures: 3, Errors: 0, Skipped: 0[m [INFO] [ERROR] There are test failures. Please refer to /var/lib/jenkins/jobs/nawa_selenide/workspace/target/surefire-reports for the individual test results. Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream. [JENKINS] Recording test results [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 20.071 s [INFO] Finished at: 2019-07-08T14:36:56+02:00 [INFO] Final Memory: 31M/330M [INFO] ------------------------------------------------------------------------ Waiting for Jenkins to finish collecting data [JENKINS] Archiving /var/lib/jenkins/jobs/nawa_selenide/workspace/pom.xml to com/nawa/1.0-SNAPSHOT/nawa-1.0-SNAPSHOT.pom channel stopped Finished: UNSTABLE On every test we have: java.lang.IllegalStateException: No webdriver is bound to current thread: Do You have experience with similar situation? Why on local machine tests are done correctly, but on main Jenkins in company there are only failures caused by No webdriver is bound to current thread? Only operating system is difference. This is problem with jenkins configuration under Linux? When I run the tests locally, using Jenkins (with Maven), I get the same message, but the WebDriver is actually created and runs my test cases. My maven goals are: mvn clean test -Puat Declaration of Chrome in tests: @BeforeClass public void setUp() throws Exception { Configuration.holdBrowserOpen = false; Configuration.browser = "chrome"; Configuration.timeout = 10000; Configuration.headless = true; SelenideLogger.addListener("AllureSelenide", new AllureSelenide().screenshots(true).savePageSource(true)); objReader.environmentPropertiesLoader(); } _______________edit Now i check Start Xvfb before the build, and shut it down after in Jenkins job Build Environment, i read that is very important, maybe xvfb is the cause, i dont know, now in console i have java.io.IOException: Cannot run program "Xvfb": error=2, No such file or directory
[ "Did anyone answer? You need to call open Url as the error says.\ndriver.open(URL HERE) at the end of your setup method.\n", "this is my solution:\nafter open(), store current webDriver, and before use - restore webDriver\n WebDriver webDriver;\n\n// constructor\npublic SelenideCommand() {\n Configuration.holdBrowserOpen = true;\n Selenide.open(\"https://www.instagram.com/\");\n\n webDriver = WebDriverRunner.getWebDriver();\n}\n\npublic void login(String userName, String password) {\n\n WebDriverRunner.setWebDriver(webDriver);\n\n Selenide.element(Selectors.byName(\"username\")).setValue(userName);\n Selenide.element(Selectors.byName(\"password\")).setValue(password);\n Selenide.elements(Selectors.byTagName(\"button\")).get(1).click();\n} \n\n" ]
[ 0, 0 ]
[]
[]
[ "jenkins", "selenide" ]
stackoverflow_0056946504_jenkins_selenide.txt
Q: SyntaxError: Cannot use import statement outside a module using puppeteer Hello I keep trying to run the puppeteer test but keep getting this issue. Please help thanks.enter image description here code: import puppeteer from 'puppeteer'; (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://developers.google.com/web/'); // Type into search box. await page.type('.devsite-search-field', 'Headless Chrome'); // Wait for suggest overlay to appear and click "show all results". const allResultsSelector = '.devsite-suggest-all-results'; await page.waitForSelector(allResultsSelector); await page.click(allResultsSelector); // Wait for the results page to load and display the results. const resultsSelector = '.gsc-results .gs-title'; await page.waitForSelector(resultsSelector); // Extract the results from the page. const links = await page.evaluate(resultsSelector => { return [...document.querySelectorAll(resultsSelector)].map(anchor => { const title = anchor.textContent.split('|')[0].trim(); return `${title} - ${anchor.href}`; }); }, resultsSelector); // Print all the files. console.log(links.join('\n')); await browser.close(); })(); error: SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:74:18) at wrapSafe (node:internal/modules/cjs/loader:1128:20) at Module._compile (node:internal/modules/cjs/loader:1169:27) at Module._extensions..js (node:internal/modules/cjs/loader:1259:10) at Module.load (node:internal/modules/cjs/loader:1068:32) at Module._load (node:internal/modules/cjs/loader:909:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12) at node:internal/main/run_main_module:23:47 I have tried reinstalling node js and npm but nothing has worked. A: { "name": "my-app", "version": "0.0.0", "type": "module", "scripts": { ... }, ... } Add type:module in your package.json file or install the latest Nodejs
SyntaxError: Cannot use import statement outside a module using puppeteer
Hello I keep trying to run the puppeteer test but keep getting this issue. Please help thanks.enter image description here code: import puppeteer from 'puppeteer'; (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://developers.google.com/web/'); // Type into search box. await page.type('.devsite-search-field', 'Headless Chrome'); // Wait for suggest overlay to appear and click "show all results". const allResultsSelector = '.devsite-suggest-all-results'; await page.waitForSelector(allResultsSelector); await page.click(allResultsSelector); // Wait for the results page to load and display the results. const resultsSelector = '.gsc-results .gs-title'; await page.waitForSelector(resultsSelector); // Extract the results from the page. const links = await page.evaluate(resultsSelector => { return [...document.querySelectorAll(resultsSelector)].map(anchor => { const title = anchor.textContent.split('|')[0].trim(); return `${title} - ${anchor.href}`; }); }, resultsSelector); // Print all the files. console.log(links.join('\n')); await browser.close(); })(); error: SyntaxError: Cannot use import statement outside a module at internalCompileFunction (node:internal/vm:74:18) at wrapSafe (node:internal/modules/cjs/loader:1128:20) at Module._compile (node:internal/modules/cjs/loader:1169:27) at Module._extensions..js (node:internal/modules/cjs/loader:1259:10) at Module.load (node:internal/modules/cjs/loader:1068:32) at Module._load (node:internal/modules/cjs/loader:909:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12) at node:internal/main/run_main_module:23:47 I have tried reinstalling node js and npm but nothing has worked.
[ "{\n \"name\": \"my-app\",\n \"version\": \"0.0.0\",\n \"type\": \"module\",\n \"scripts\": { ...\n },\n ...\n }\n\nAdd type:module in your package.json file or install the latest Nodejs\n" ]
[ 1 ]
[]
[]
[ "module", "node.js", "npm", "puppeteer", "syntax_error" ]
stackoverflow_0074650098_module_node.js_npm_puppeteer_syntax_error.txt
Q: Running server-side code once (at dev & build) then using the data in client-side ** Updated with nitro plugin approach ** I'm using Playwright server-side to get some data from a page that I want to use in my frontend, this the setup using nitro plugin Base Project Structure pages index.vue server db index.js plugins playwright.js routes playwright.js ... server/db/index.js export const db = []; server/routes/playwright.js import { db } from '../db'; export default defineEventHandler(() => db); server/plugins/playwright.js import { chromium } from 'playwright'; export default defineNitroPlugin(async () => { const browser = await chromium.launch(); // ... // some operations goes here // and some console logs for tracking progress // ... db.push(results); // results is the scraped data }); On running nuxt dev, the script in plugins/playwright starts, opens the browser, scrape the data and store it to db with all my console.log logged to the terminal (this is different in prod). When I open local host I get the index page with the fetched data from db with no errors. However on running nuxt generate the CLI runs as usual and I see only some of the console.logs printed to terminal as following yarn run v1.22.19 $ nuxt generate Nuxi 3.0.0 Nuxt 3.0.0 with Nitro 1.0.0 WARN Using experimental payload extraction for full-static output. You can opt-out by setting experimental.payloadExtraction to false. i Client built in 1666ms i Building server... √ Server built in 581ms √ Generated public .output/public i Initializing prerenderer Starting Playwright server plugin ⚙️ Read User-specifed options Initiating a new page // There are more console.logs than these three i Prerendering 3 initial routes with crawler ├─ / (290ms) ├─ /200.html (3ms) ├─ /404.html (5ms) ├─ /_payload.js (2ms) √ You can now deploy .output/public to any static hosting! Done in 6.21s. * Terminal will be reused by tasks, press any key to close it. On running nuxt preview and openning local host I get the index page with a an empty array (the initial value for db) Do I need to somehow force the generate command to wait until the nitro plugin finish executing? and how can I do that? A: I'm not sure if this can help, but you can solve this using a "ready" hook: First, create a file like this (./hooks/hooks.js): export default (nuxtConfig) => ({ ready: () => { // Execute your code here } }); Then add it to your nuxt.config.js: import hooks from './hooks/hooks'; export default { // Other stuff hooks: hooks(this), // Other stuff } A: The problem was in playwright package not in nuxt itself, after getting playwright to work and using routes the app worked correctly
Running server-side code once (at dev & build) then using the data in client-side
** Updated with nitro plugin approach ** I'm using Playwright server-side to get some data from a page that I want to use in my frontend, this the setup using nitro plugin Base Project Structure pages index.vue server db index.js plugins playwright.js routes playwright.js ... server/db/index.js export const db = []; server/routes/playwright.js import { db } from '../db'; export default defineEventHandler(() => db); server/plugins/playwright.js import { chromium } from 'playwright'; export default defineNitroPlugin(async () => { const browser = await chromium.launch(); // ... // some operations goes here // and some console logs for tracking progress // ... db.push(results); // results is the scraped data }); On running nuxt dev, the script in plugins/playwright starts, opens the browser, scrape the data and store it to db with all my console.log logged to the terminal (this is different in prod). When I open local host I get the index page with the fetched data from db with no errors. However on running nuxt generate the CLI runs as usual and I see only some of the console.logs printed to terminal as following yarn run v1.22.19 $ nuxt generate Nuxi 3.0.0 Nuxt 3.0.0 with Nitro 1.0.0 WARN Using experimental payload extraction for full-static output. You can opt-out by setting experimental.payloadExtraction to false. i Client built in 1666ms i Building server... √ Server built in 581ms √ Generated public .output/public i Initializing prerenderer Starting Playwright server plugin ⚙️ Read User-specifed options Initiating a new page // There are more console.logs than these three i Prerendering 3 initial routes with crawler ├─ / (290ms) ├─ /200.html (3ms) ├─ /404.html (5ms) ├─ /_payload.js (2ms) √ You can now deploy .output/public to any static hosting! Done in 6.21s. * Terminal will be reused by tasks, press any key to close it. On running nuxt preview and openning local host I get the index page with a an empty array (the initial value for db) Do I need to somehow force the generate command to wait until the nitro plugin finish executing? and how can I do that?
[ "I'm not sure if this can help, but you can solve this using a \"ready\" hook:\nFirst, create a file like this (./hooks/hooks.js):\nexport default (nuxtConfig) => ({\n ready: () => {\n // Execute your code here\n }\n});\n\nThen add it to your nuxt.config.js:\nimport hooks from './hooks/hooks';\nexport default {\n // Other stuff\n hooks: hooks(this),\n // Other stuff\n}\n\n", "The problem was in playwright package not in nuxt itself, after getting playwright to work and using routes the app worked correctly\n" ]
[ 1, 0 ]
[]
[]
[ "javascript", "nuxt.js", "nuxtjs3", "playwright" ]
stackoverflow_0074490863_javascript_nuxt.js_nuxtjs3_playwright.txt
Q: NEXT.JS: Deployment build failed because of next lint Problem I'm trying to deploy my git repository with vercel. But my deployments always fail because of lint errors in files I used for testing. The Vercel docs say: By default, Next.js will run ESLint for all files in the pages/, components/, lib/, and src/ directories. Vercel Docs Link So I moved my _tests folder out of my components folder which helped for the local next linter running npm run lint now runs without any errors which should mirror the Vercel deployment built linter if I'm correct. My lint settings are below: { "extends": "next/core-web-vitals" } But when pushing to the main branch and deploying to vercel the linter still errors on files in the _test folder. Folder structure _tests // Here I moved my components and tests I don't want to have errors with as they're unfinished or only tests .next components lib node_modules pages .... Shouldn't the lint process local and on Vercel be the same and if not how can I test locally the same way as on my deployment build step? What am I missing? I've looked all over the docs regarding eslint. A: First of all I would recommend you to not disregard lint issues even in your tests, because tests are part of your application. So the ideal world solution would be to fix all those lint issues and be happy. But if you still want to exclude some code from being linted, you could use ESLint ignorePatterns. Configuration .eslintrc.json could look like: { "extends": "next/core-web-vitals", "ignorePatterns": [ "_test/**" ] } or you could write .eslintignore file with the following content: _test/ Another possible solution for you could be to turn off Linter in next build command (by default Vercel uses this command for building your application). To do so, you need to add this to your next.config.js: const nextConfig = { ... eslint: { ignoreDuringBuilds: false, }, };
NEXT.JS: Deployment build failed because of next lint
Problem I'm trying to deploy my git repository with vercel. But my deployments always fail because of lint errors in files I used for testing. The Vercel docs say: By default, Next.js will run ESLint for all files in the pages/, components/, lib/, and src/ directories. Vercel Docs Link So I moved my _tests folder out of my components folder which helped for the local next linter running npm run lint now runs without any errors which should mirror the Vercel deployment built linter if I'm correct. My lint settings are below: { "extends": "next/core-web-vitals" } But when pushing to the main branch and deploying to vercel the linter still errors on files in the _test folder. Folder structure _tests // Here I moved my components and tests I don't want to have errors with as they're unfinished or only tests .next components lib node_modules pages .... Shouldn't the lint process local and on Vercel be the same and if not how can I test locally the same way as on my deployment build step? What am I missing? I've looked all over the docs regarding eslint.
[ "First of all I would recommend you to not disregard lint issues even in your tests, because tests are part of your application. So the ideal world solution would be to fix all those lint issues and be happy.\nBut if you still want to exclude some code from being linted, you could use ESLint ignorePatterns. Configuration .eslintrc.json could look like:\n{\n \"extends\": \"next/core-web-vitals\",\n \"ignorePatterns\": [\n \"_test/**\"\n ]\n}\n\nor you could write .eslintignore file with the following content:\n_test/\n\nAnother possible solution for you could be to turn off Linter in next build command (by default Vercel uses this command for building your application). To do so, you need to add this to your next.config.js:\nconst nextConfig = {\n ...\n eslint: {\n ignoreDuringBuilds: false,\n },\n};\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "next.js" ]
stackoverflow_0073963527_javascript_next.js.txt
Q: How to pass DOM element to JS function - Node cannot be found in the current page error I'm trying to pass an element to another function and use it in jQuery as a DOM element: $(document).on('change', selector, function() { element = this; $.ajax({ type: 'POST', url: url, async: false, cache: false, dataType: 'json', data: '', success: function (jsonData) { myFunction(element); } }); }); function myFunction(element) { $(element); } The element is sent, I can get all the data from it, but it seems that it's not linked to the element in the page: I can't use $(element).closest('form') for example. EDIT: I was trying to post a jsfiddle with an example, but I couldn't reproduce it. After testing it harder, I found my mistake ‍♂️. Before executing myFunction I was replacing these elements (including the caller) with the AJAX response, but the structure was the same so I didn't think about it at first sight, because I could find the element using the selector. A: It's not perfectly clear what's the problem you are encountering. As far as I can say, that code should work as expected despite a couple details that I'd prefer was crafted differently. For example I prefer to grab the element triggering an event using the .target property of the event passed to the handler function instead of using this. Also the target (that's how I renamed it) variable belonging to the scope of the change event retains its value when evaluated in the callback invoked by the ajax process when the request will be fulfilled but it would be better factored passing a bound function as an argument to $.ajax(). Anwyay those are just recommendation to better factor code... Your code should already work correctly as expected as showing here. The selector here is statically passed as the input literal so that a change event handler will be attached to all input elements in the document. Plus I changed your success callback to be performed on complete instead because as you can see I used a bogus url for the ajax request. When you give focus to a text input and change its value, after moving the focus elsewhere, the change event will fire and the myFunction call will print out the element triggering the change event and any of its parent info that will show the evidence that such element is attached to the dom. $(document).on('change', 'input', function(event) { //const target = event.target; target = this; $.ajax({ type: 'POST', url: 'http://bogusurl.com', async: false, cache: false, dataType: 'json', data: '', complete: function (jsonData) { myFunction(target); } }); }); function myFunction(element) { console.log(`ChangedElement: ${element.id}`); console.log(`ImParent data attr from parent: ${$(element).closest('.parent').data('imparent')}`); console.log(`parent form action: ${$(element).closest('form').attr('action')}`); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <form action="nexturl"> <div class="parent" data-imparent="yes"> <input id="text1" placeholder="text1"> <input id="text2" placeholder="text2"> </div> </form>
How to pass DOM element to JS function - Node cannot be found in the current page error
I'm trying to pass an element to another function and use it in jQuery as a DOM element: $(document).on('change', selector, function() { element = this; $.ajax({ type: 'POST', url: url, async: false, cache: false, dataType: 'json', data: '', success: function (jsonData) { myFunction(element); } }); }); function myFunction(element) { $(element); } The element is sent, I can get all the data from it, but it seems that it's not linked to the element in the page: I can't use $(element).closest('form') for example. EDIT: I was trying to post a jsfiddle with an example, but I couldn't reproduce it. After testing it harder, I found my mistake ‍♂️. Before executing myFunction I was replacing these elements (including the caller) with the AJAX response, but the structure was the same so I didn't think about it at first sight, because I could find the element using the selector.
[ "It's not perfectly clear what's the problem you are encountering.\nAs far as I can say, that code should work as expected despite a couple details that I'd prefer was crafted differently.\nFor example I prefer to grab the element triggering an event using the .target property of the event passed to the handler function instead of using this. Also the target (that's how I renamed it) variable belonging to the scope of the change event retains its value when evaluated in the callback invoked by the ajax process when the request will be fulfilled but it would be better factored passing a bound function as an argument to $.ajax().\nAnwyay those are just recommendation to better factor code...\nYour code should already work correctly as expected as showing here.\nThe selector here is statically passed as the input literal so that a change event handler will be attached to all input elements in the document.\nPlus I changed your success callback to be performed on complete instead because as you can see I used a bogus url for the ajax request.\nWhen you give focus to a text input and change its value, after moving the focus elsewhere, the change event will fire and the myFunction call will print out the element triggering the change event and any of its parent info that will show the evidence that such element is attached to the dom.\n\n\n$(document).on('change', 'input', function(event) { \n //const target = event.target;\n target = this;\n $.ajax({\n type: 'POST',\n url: 'http://bogusurl.com',\n async: false,\n cache: false,\n dataType: 'json',\n data: '',\n complete: function (jsonData) { \n myFunction(target);\n }\n });\n});\n\nfunction myFunction(element) { \n console.log(`ChangedElement: ${element.id}`);\n console.log(`ImParent data attr from parent: ${$(element).closest('.parent').data('imparent')}`); \n console.log(`parent form action: ${$(element).closest('form').attr('action')}`); \n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js\"></script>\n\n<form action=\"nexturl\">\n <div class=\"parent\" data-imparent=\"yes\">\n <input id=\"text1\" placeholder=\"text1\">\n <input id=\"text2\" placeholder=\"text2\">\n </div>\n</form>\n\n\n\n" ]
[ 0 ]
[]
[]
[ "javascript", "jquery" ]
stackoverflow_0074656520_javascript_jquery.txt
Q: How to add style for Title of ContentPage in .Net MAUI? I'm working with .NET MAUI to create a desktop app. Here, I have a ContentPage with the title My title. <ContentPage x:Class="MAUI.Desktop.Pages.PlanningPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="My title"> .... Its title is aligned left by default, do you know how to align it to the center of the page? If possible, I also want to add more style to it too. Edit: suggested solution I forget to mention that my page is considered NavigationPage. So, here is my solution: <ContentPage x:Class="MAUI.Desktop.Pages.PlanningPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" > <NavigationPage.TitleView> <Label x:Name="pageTitleView" HorizontalTextAlignment="Center" Text="My title"/> </NavigationPage.TitleView> ...... In code-behind xaml.cs file: protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); pageTitleView.WidthRequest = width; } If you're working with Shell app, you could follow the answer from @mm8 A: You could define your own TitleView: <ContentPage x:Class="MAUI.Desktop.Pages.PlanningPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="Planification"> <Shell.TitleView> <Grid> <Label Text="My Title" HorizontalOptions="Center" VerticalOptions="Center" /> </Grid> </Shell.TitleView> ...
How to add style for Title of ContentPage in .Net MAUI?
I'm working with .NET MAUI to create a desktop app. Here, I have a ContentPage with the title My title. <ContentPage x:Class="MAUI.Desktop.Pages.PlanningPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="My title"> .... Its title is aligned left by default, do you know how to align it to the center of the page? If possible, I also want to add more style to it too. Edit: suggested solution I forget to mention that my page is considered NavigationPage. So, here is my solution: <ContentPage x:Class="MAUI.Desktop.Pages.PlanningPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" > <NavigationPage.TitleView> <Label x:Name="pageTitleView" HorizontalTextAlignment="Center" Text="My title"/> </NavigationPage.TitleView> ...... In code-behind xaml.cs file: protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); pageTitleView.WidthRequest = width; } If you're working with Shell app, you could follow the answer from @mm8
[ "You could define your own TitleView:\n<ContentPage x:Class=\"MAUI.Desktop.Pages.PlanningPage\"\n xmlns=\"http://schemas.microsoft.com/dotnet/2021/maui\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\"\n Title=\"Planification\">\n <Shell.TitleView>\n <Grid>\n <Label Text=\"My Title\" HorizontalOptions=\"Center\" VerticalOptions=\"Center\" />\n </Grid>\n </Shell.TitleView>\n ...\n\n" ]
[ 3 ]
[]
[]
[ ".net", "maui", "maui_windows", "winui_3" ]
stackoverflow_0074654765_.net_maui_maui_windows_winui_3.txt
Q: Exception :com.sun.jersey.spi.inject.Errors$ErrorMessagesException I am using the Jersey API for the web services. I am sending the multipart data from client to server. I am getting exception when web services start to execute. @POST @Path("uploadphoto") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("text/plain") public String uploadNotices(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "d:/" + fileDetail.getFileName(); // save it try { writeToFile(uploadedInputStream, uploadedFileLocation); } catch(Exception e) { return "no"; } return "yes"; } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws Exception { OutputStream out = new FileOutputStream(new File(uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } Stacktrace: SEVERE: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Missing dependency for method public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 0 SEVERE: Missing dependency for method public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 1 SEVERE: Method, public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition), annotated with POST of resource, class com.homebulletin.resources.NoticeResources, is not recognized as valid resource method. Jun 18, 2013 10:55:17 AM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable com.sun.jersey.spi.inject.Errors$ErrorMessagesException at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170) at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136) at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760) at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489) at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319) at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609) at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Jun 18, 2013 10:55:17 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Allocate exception for servlet Home Bulletin com.sun.jersey.spi.inject.Errors$ErrorMessagesException at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170) at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136) at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760) at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489) at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319) at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609) at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) A: It seems your missing few jars in your project.Try adding these to your project: jersey-multipart.jar mimepull.jar If you are using maven, you can add this dependency: <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-multipart</artifactId> <version>1.8</version> </dependency> Change the version of jar if you need Also make sure that the version of your jersey-multipart jar should be same as the version of jersey bundle jar A: Forgetting to add @POST or @Get on top of the method name will also cause this error A: It faced me the same error because having same @Path annotations with the same path names( strings). @Path('samepath') /// samepath cause Jersey Error at run time. /* Method 1*/ @Path('samepath') /* Method 2 */ A: com.sun.jersey.spi.inject.Errors$ErrorMessagesException occured when I had two @GET methods with the same path but different query params. Also it may happen if you rename your controller class, do mvn install without mvn clean and put war file to /webapps folder. A: I have seen exactly the same error when using @FormParam (which expects @POST) with @GET parameters. Hope it will help someone as it wasn't very intuitive to find out. A: Replace your web.xml with this code: <servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> A: I met this problem because I did not have no parameter constructor in my class @Path("/deviceconfigs") public class DeviceConfigInterface extends ComInterfaceGen<DeviceConfigApi> { public DeviceConfigInterface(Class<DeviceConfigApi> type) { super(DeviceConfigApi.class); } }. When I used no parameter constructor, the problem is solved. A: I had a similar problem as I missed out to add a "Consumes" annotation for my POST method. Hope it helps someone. A: I know it's to late. But updating it here for future references. Better check the jar versions. I had the same issue. I was using the 1.16 version of jersey core and server, but this one i added with 1.18. It gave the same error. But then I realized and changed to 1.16 then worked fine. It doesn't work with different versions. A: There are multiple potential reasons therefore, just mentioning the most common ones you are lacking some JAR files you have multiple java methods with the same @Path annotation and the same HTTP methods (i.e. with different params or query params) you have a web service method with an invalid response or request param type (i.e. a annotation class as parameter class or other weird stuff) A: Sometimes you specified @FormDataParam instead @QueryParam in GET method, in my case that was the problem. A: i Also got Same Eroor Solution for This is was using import jakarta.ws.rs.PUT But i should use import javax.ws.rs.PUT; I got Answer. Hope this will Help
Exception :com.sun.jersey.spi.inject.Errors$ErrorMessagesException
I am using the Jersey API for the web services. I am sending the multipart data from client to server. I am getting exception when web services start to execute. @POST @Path("uploadphoto") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("text/plain") public String uploadNotices(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "d:/" + fileDetail.getFileName(); // save it try { writeToFile(uploadedInputStream, uploadedFileLocation); } catch(Exception e) { return "no"; } return "yes"; } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws Exception { OutputStream out = new FileOutputStream(new File(uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } Stacktrace: SEVERE: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Missing dependency for method public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 0 SEVERE: Missing dependency for method public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 1 SEVERE: Method, public java.lang.String com.homebulletin.resources.NoticeResources.uploadNotices(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition), annotated with POST of resource, class com.homebulletin.resources.NoticeResources, is not recognized as valid resource method. Jun 18, 2013 10:55:17 AM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable com.sun.jersey.spi.inject.Errors$ErrorMessagesException at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170) at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136) at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760) at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489) at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319) at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609) at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source) Jun 18, 2013 10:55:17 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Allocate exception for servlet Home Bulletin com.sun.jersey.spi.inject.Errors$ErrorMessagesException at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170) at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136) at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765) at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:760) at com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489) at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319) at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609) at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source)
[ "It seems your missing few jars in your project.Try adding these to your project:\n\njersey-multipart.jar\nmimepull.jar\n\nIf you are using maven, you can add this dependency:\n<dependency>\n <groupId>com.sun.jersey.contribs</groupId>\n <artifactId>jersey-multipart</artifactId>\n <version>1.8</version>\n </dependency>\n\nChange the version of jar if you need\nAlso make sure that the version of your jersey-multipart jar should be same as the version of jersey bundle jar\n", "Forgetting to add @POST or @Get on top of the method name will also cause this error\n", "It faced me the same error because having same @Path annotations with the same path names( strings).\n@Path('samepath') /// samepath cause Jersey Error at run time.\n/* Method 1*/\n\n@Path('samepath')\n/* Method 2 */\n\n", "\ncom.sun.jersey.spi.inject.Errors$ErrorMessagesException\n\noccured when I had two @GET methods with the same path but different query params.\nAlso it may happen if you rename your controller class, do mvn install without mvn clean and put war file to /webapps folder.\n", "I have seen exactly the same error when using @FormParam (which expects @POST) with @GET parameters.\nHope it will help someone as it wasn't very intuitive to find out.\n", "Replace your web.xml with this code:\n<servlet>\n <servlet-name>Jersey Web Application</servlet-name>\n <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>\n <load-on-startup>1</load-on-startup>\n</servlet>\n<servlet-mapping>\n <servlet-name>Jersey Web Application</servlet-name>\n <url-pattern>/*</url-pattern>\n</servlet-mapping>\n\n", "I met this problem because I did not have no parameter constructor in my class \n@Path(\"/deviceconfigs\")\npublic class DeviceConfigInterface extends ComInterfaceGen<DeviceConfigApi> {\n public DeviceConfigInterface(Class<DeviceConfigApi> type) {\n super(DeviceConfigApi.class);\n }\n}.\n\nWhen I used no parameter constructor, the problem is solved.\n", "I had a similar problem as I missed out to add a \"Consumes\" annotation for my POST method. Hope it helps someone.\n", "I know it's to late. But updating it here for future references. \nBetter check the jar versions. \nI had the same issue. I was using the 1.16 version of jersey core and server, but this one i added with 1.18. It gave the same error. But then I realized and changed to 1.16 then worked fine. \nIt doesn't work with different versions.\n", "There are multiple potential reasons therefore, just mentioning the most common ones\n\nyou are lacking some JAR files\nyou have multiple java methods with the same @Path annotation and the same HTTP methods (i.e. with different params or query params)\nyou have a web service method with an invalid response or request param type (i.e. a annotation class as parameter class or other weird stuff)\n\n", "Sometimes you specified @FormDataParam instead @QueryParam in GET method, in my case that was the problem.\n", "i Also got Same Eroor\nSolution for This is was using import jakarta.ws.rs.PUT\nBut i should use import javax.ws.rs.PUT;\nI got Answer. Hope this will Help\n" ]
[ 22, 14, 7, 4, 3, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "jakarta_ee", "java", "jersey" ]
stackoverflow_0017161285_jakarta_ee_java_jersey.txt
Q: How to configure Yarn Berry, Eslint with GlobalCache in VsCode? Is there a way to install EsLint with Yarn Berry with yarn option enableGlobalCache: true in VsCode ? I installed the ESLint (dbaeumer.vscode-eslint) extension and all dependencies : "devDependencies": { "@babel/core": ">=7.12.0 <8.0.0", "@babel/plugin-proposal-class-properties": ">=7.10.4 <8.0.0", "@babel/plugin-syntax-dynamic-import": ">=7.8.3 <8.0.0", "@babel/plugin-transform-runtime": ">=7.12.0 <8.0.0", "@babel/preset-env": ">=7.12.0 <8.0.0", "@babel/preset-react": ">=7.10.4 <8.0.0", "@babel/runtime": ">=7.12.0 <8.0.0", "babel-eslint": ">=10.1.0", "babel-loader": ">=8.1.0", "eslint": "^7.12.1", "eslint-config-airbnb": "^18.2.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-react": "^7.21.5", "eslint-plugin-react-hooks": "^4.2.0", "file-loader": ">=6.1.0", "terser-webpack-plugin": ">=4.1.0", "webpack": ">=5.2.0", "webpack-cli": ">=4.1.0" } If I do a yarn eslint --init and let npm install all node_modules, eslint works but yarn up will erase node_modules and I have to reinstall the modules. If I don't install the modules : Error: An error occurred while generating your JavaScript config file. A config file was still generated, but the config file itself may not follow your linting rules. Error: Cannot read config file: C:\FrontApplication\Abc\Main\Source\myProject\.yarn\$$virtual\eslint-config-airbnb-virtual-094ee35fd8\6\Users\someone\AppData\Local\Yarn\Berry\cache\eslint-config-airbnb-npm-18.2.0-898fc49dc6-6.zip\node_modules\eslint-config-airbnb\index.js Error: Cannot find module 'C:\Projets\Abc\Main\Source\myProject\.yarn\$$virtual\eslint-config-airbnb-virtual-094ee35fd8\6\Users\someone\AppData\Local\Yarn\Berry\cache\eslint-config-airbnb-npm-18.2.0-898fc49dc6-6.zip\node_modules\eslint-config-airbnb\index.js' Require stack: - C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\noop.js Require stack: - C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\noop.js Referenced from: BaseConfig at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.external_module_.Module._resolveFilename (C:\FrontApplication\Abc\Main\Source\myProject\.pnp.js:10974:54) at resolveFileName (C:\Users\someone\AppData\Local\Yarn\Berry\cache\resolve-from-npm-4.0.0-f758ec21bf-6.zip\node_modules\resolve-from\index.js:29:39) at resolveFrom (C:\Users\someone\AppData\Local\Yarn\Berry\cache\resolve-from-npm-4.0.0-f758ec21bf-6.zip\node_modules\resolve-from\index.js:43:9) at module.exports (C:\Users\someone\AppData\Local\Yarn\Berry\cache\resolve-from-npm-4.0.0-f758ec21bf-6.zip\node_modules\resolve-from\index.js:46:41) at module.exports (C:\Users\someone\AppData\Local\Yarn\Berry\cache\import-fresh-npm-3.2.1-b4f6711244-6.zip\node_modules\import-fresh\index.js:13:19) at loadJSConfigFile (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:225:16) at loAbconfigFile (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:308:20) at ConfigArrayFactory._loAbconfigData (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:608:42) at ConfigArrayFactory._loadExtendedShareableConfig (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:883:21) A: Do not install packages individually use : yarn dlx @yarnpkg/sdks vscode https://yarnpkg.com/getting-started/editor-sdks Global cache works fine afterwards
How to configure Yarn Berry, Eslint with GlobalCache in VsCode?
Is there a way to install EsLint with Yarn Berry with yarn option enableGlobalCache: true in VsCode ? I installed the ESLint (dbaeumer.vscode-eslint) extension and all dependencies : "devDependencies": { "@babel/core": ">=7.12.0 <8.0.0", "@babel/plugin-proposal-class-properties": ">=7.10.4 <8.0.0", "@babel/plugin-syntax-dynamic-import": ">=7.8.3 <8.0.0", "@babel/plugin-transform-runtime": ">=7.12.0 <8.0.0", "@babel/preset-env": ">=7.12.0 <8.0.0", "@babel/preset-react": ">=7.10.4 <8.0.0", "@babel/runtime": ">=7.12.0 <8.0.0", "babel-eslint": ">=10.1.0", "babel-loader": ">=8.1.0", "eslint": "^7.12.1", "eslint-config-airbnb": "^18.2.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-react": "^7.21.5", "eslint-plugin-react-hooks": "^4.2.0", "file-loader": ">=6.1.0", "terser-webpack-plugin": ">=4.1.0", "webpack": ">=5.2.0", "webpack-cli": ">=4.1.0" } If I do a yarn eslint --init and let npm install all node_modules, eslint works but yarn up will erase node_modules and I have to reinstall the modules. If I don't install the modules : Error: An error occurred while generating your JavaScript config file. A config file was still generated, but the config file itself may not follow your linting rules. Error: Cannot read config file: C:\FrontApplication\Abc\Main\Source\myProject\.yarn\$$virtual\eslint-config-airbnb-virtual-094ee35fd8\6\Users\someone\AppData\Local\Yarn\Berry\cache\eslint-config-airbnb-npm-18.2.0-898fc49dc6-6.zip\node_modules\eslint-config-airbnb\index.js Error: Cannot find module 'C:\Projets\Abc\Main\Source\myProject\.yarn\$$virtual\eslint-config-airbnb-virtual-094ee35fd8\6\Users\someone\AppData\Local\Yarn\Berry\cache\eslint-config-airbnb-npm-18.2.0-898fc49dc6-6.zip\node_modules\eslint-config-airbnb\index.js' Require stack: - C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\noop.js Require stack: - C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\noop.js Referenced from: BaseConfig at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.external_module_.Module._resolveFilename (C:\FrontApplication\Abc\Main\Source\myProject\.pnp.js:10974:54) at resolveFileName (C:\Users\someone\AppData\Local\Yarn\Berry\cache\resolve-from-npm-4.0.0-f758ec21bf-6.zip\node_modules\resolve-from\index.js:29:39) at resolveFrom (C:\Users\someone\AppData\Local\Yarn\Berry\cache\resolve-from-npm-4.0.0-f758ec21bf-6.zip\node_modules\resolve-from\index.js:43:9) at module.exports (C:\Users\someone\AppData\Local\Yarn\Berry\cache\resolve-from-npm-4.0.0-f758ec21bf-6.zip\node_modules\resolve-from\index.js:46:41) at module.exports (C:\Users\someone\AppData\Local\Yarn\Berry\cache\import-fresh-npm-3.2.1-b4f6711244-6.zip\node_modules\import-fresh\index.js:13:19) at loadJSConfigFile (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:225:16) at loAbconfigFile (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:308:20) at ConfigArrayFactory._loAbconfigData (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:608:42) at ConfigArrayFactory._loadExtendedShareableConfig (C:\Users\someone\AppData\Local\Yarn\Berry\cache\@eslint-eslintrc-npm-0.2.1-88318143fb-6.zip\node_modules\@eslint\eslintrc\lib\config-array-factory.js:883:21)
[ "Do not install packages individually\nuse : yarn dlx @yarnpkg/sdks vscode\nhttps://yarnpkg.com/getting-started/editor-sdks\nGlobal cache works fine afterwards\n" ]
[ 0 ]
[]
[]
[ "eslint", "visual_studio_code", "yarnpkg", "yarnpkg_v2" ]
stackoverflow_0064605525_eslint_visual_studio_code_yarnpkg_yarnpkg_v2.txt
Q: Open and Repair Multiple excel Files using VBA I am using Google Sheets since couple of years and making reports in Microsoft excel. I am working on almost 50+ Sheets each week i copy and paste the data into Excel one by one to keep the cells formatting. I have tried to donwload the entire folder which contains Google Sheets then open it in Microsoft Excel which give me an error while opening each and every file that is: [![enter image description here][1]][1] once i click OK then it populates the one more error that is: [![![enter image description here][2]][2] I am looking for a way to to fix this error insteaded of opening each file separatly then save it to make it repairbale one (so the error could not appear again). I have tried with below code but it does not work i do not know why. I need to apply this methoed on entire folder to repair all excel files and save them. Your help will be much appreciated Sub Folder() Dim strFolder As String Dim strFile As String Dim wbk As Workbook Dim wsh As Worksheet Dim I As Long With Application.FileDialog(4) If .Show Then strFolder = .SelectedItems(1) Else MsgBox "You haven't selected a folder!", vbExclamation Exit Sub End If End With If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\" End If Application.ScreenUpdating = False strFile = Dir(strFolder & "*.xlsx*") Do While strFile <> "" Set wbk = Workbooks.Open(strFolder & strFile, CorruptLoad:=XlCorruptLoad.xlRepairFile) For Each wsh In wbk.Worksheets Next wsh wbk.Close SaveChanges:=True strFile = Dir Exit Sub Err_Open: Err.Clear Loop Application.ScreenUpdating = True End Sub [1]: https://i.stack.imgur.com/ofXMK.png [2]: https://i.stack.imgur.com/PlHxX.png A: Please, test the next code. It will create a subfolder "RecoveredWB" in the selected folder to be processed and all processed files will be saved in this one: Sub Folder() Dim strFolder As String, strFile As String, wbk As Workbook Dim wsh As Worksheet, I As Long With Application.FileDialog(4) If .Show Then strFolder = .SelectedItems(1) Else MsgBox "You haven't selected a folder!", vbExclamation Exit Sub End If End With If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\" End If Dim wbName As String, arrWb, subFoldNew As String subFoldNew = strFolder & "RecoveredWB" Application.ScreenUpdating = False strFile = Dir(strFolder & "*.xlsx") Do While strFile <> "" Set wbk = Workbooks.Open(strFolder & strFile, CorruptLoad:=xlRepairFile) For Each wsh In wbk.Worksheets Next wsh arrWb = Split(wbk.fullname, "\") 'place the full name in an array split by "\" wbName = arrWb(UBound(arrWb)) 'the workbook name (without path) 'create RecoveredWB folder if not existing: If Dir(subFoldNew, vbDirectory) = "" Then MkDir subFoldNew wbk.SaveCopyAs subFoldNew & "\" & wbName wbk.Close False strFile = Dir Loop Application.ScreenUpdating = True Exit Sub Err_Open: err.Clear Application.ScreenUpdating = True End Sub The code is not tested, I cannot reproduce the situation, not having corrupted workbooks... If something goes wrong, please explain which error on which code line, or waht it does not against what it should.
Open and Repair Multiple excel Files using VBA
I am using Google Sheets since couple of years and making reports in Microsoft excel. I am working on almost 50+ Sheets each week i copy and paste the data into Excel one by one to keep the cells formatting. I have tried to donwload the entire folder which contains Google Sheets then open it in Microsoft Excel which give me an error while opening each and every file that is: [![enter image description here][1]][1] once i click OK then it populates the one more error that is: [![![enter image description here][2]][2] I am looking for a way to to fix this error insteaded of opening each file separatly then save it to make it repairbale one (so the error could not appear again). I have tried with below code but it does not work i do not know why. I need to apply this methoed on entire folder to repair all excel files and save them. Your help will be much appreciated Sub Folder() Dim strFolder As String Dim strFile As String Dim wbk As Workbook Dim wsh As Worksheet Dim I As Long With Application.FileDialog(4) If .Show Then strFolder = .SelectedItems(1) Else MsgBox "You haven't selected a folder!", vbExclamation Exit Sub End If End With If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\" End If Application.ScreenUpdating = False strFile = Dir(strFolder & "*.xlsx*") Do While strFile <> "" Set wbk = Workbooks.Open(strFolder & strFile, CorruptLoad:=XlCorruptLoad.xlRepairFile) For Each wsh In wbk.Worksheets Next wsh wbk.Close SaveChanges:=True strFile = Dir Exit Sub Err_Open: Err.Clear Loop Application.ScreenUpdating = True End Sub [1]: https://i.stack.imgur.com/ofXMK.png [2]: https://i.stack.imgur.com/PlHxX.png
[ "Please, test the next code. It will create a subfolder \"RecoveredWB\" in the selected folder to be processed and all processed files will be saved in this one:\nSub Folder()\n Dim strFolder As String, strFile As String, wbk As Workbook\n Dim wsh As Worksheet, I As Long\n \n With Application.FileDialog(4)\n If .Show Then\n strFolder = .SelectedItems(1)\n Else\n MsgBox \"You haven't selected a folder!\", vbExclamation\n Exit Sub\n End If\n End With\n \n If Right(strFolder, 1) <> \"\\\" Then\n strFolder = strFolder & \"\\\"\n End If\n \n Dim wbName As String, arrWb, subFoldNew As String\n subFoldNew = strFolder & \"RecoveredWB\"\n \n Application.ScreenUpdating = False\n strFile = Dir(strFolder & \"*.xlsx\")\n Do While strFile <> \"\"\n Set wbk = Workbooks.Open(strFolder & strFile, CorruptLoad:=xlRepairFile)\n For Each wsh In wbk.Worksheets\n Next wsh\n \n arrWb = Split(wbk.fullname, \"\\\") 'place the full name in an array split by \"\\\"\n wbName = arrWb(UBound(arrWb)) 'the workbook name (without path)\n \n 'create RecoveredWB folder if not existing:\n If Dir(subFoldNew, vbDirectory) = \"\" Then MkDir subFoldNew\n wbk.SaveCopyAs subFoldNew & \"\\\" & wbName\n \n wbk.Close False\n \n strFile = Dir\n Loop\n Application.ScreenUpdating = True\n \n Exit Sub\nErr_Open:\n err.Clear\n Application.ScreenUpdating = True\nEnd Sub\n\nThe code is not tested, I cannot reproduce the situation, not having corrupted workbooks...\nIf something goes wrong, please explain which error on which code line, or waht it does not against what it should.\n" ]
[ 1 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074627944_excel_vba.txt
Q: How can I create my data class for my json file? I am a new kotlin programmer and I cant create data class for json file. I always run into a problem. I've worked with simple json files before, but this confused me a bit. How can I convert this json file to data class. By the way, I tried the json to data class, which is an extension of kotlin, then it outputs a data class like this, frankly, this is not a very readable data class, does anyone have a better idea? my json file { "result":"success", "documentation":"https://www.exchangerate-api.com/docs", "terms_of_use":"https://www.exchangerate-api.com/terms", "time_last_update_unix":1669939202, "time_last_update_utc":"Fri, 02 Dec 2022 00:00:02 +0000", "time_next_update_unix":1670025602, "time_next_update_utc":"Sat, 03 Dec 2022 00:00:02 +0000", "base_code":"USD", "conversion_rates":{ "USD":1, "AED":3.6725, "AFN":88.0236, "ALL":112.3100, "AMD":395.3092, "ANG":1.7900, "AOA":509.4547, "ARS":166.9052, "AUD":1.4696, "AWG":1.7900, "AZN":1.6980, "BAM":1.8638, "BBD":2.0000, "BDT":101.4835, "BGN":1.8647, "BHD":0.3760, "BIF":2053.3857, "BMD":1.0000, "BND":1.3561, "BOB":6.9195, "BRL":5.1984, "BSD":1.0000, "BTN":81.0572, "BWP":13.0619, "BYN":2.6482, "BZD":2.0000, "CAD":1.3433, "CDF":2054.6915, "CHF":0.9394, "CLP":890.3480, "CNY":7.0548, "COP":4815.7969, "CRC":601.6168, "CUP":24.0000, "CVE":105.0763, "CZK":23.2743, "DJF":177.7210, "DKK":7.1093, "DOP":54.3860, "DZD":138.5331, "EGP":24.5835, "ERN":15.0000, "ETB":53.4963, "EUR":0.9530, "FJD":2.1960, "FKP":0.8183, "FOK":7.1093, "GBP":0.8183, "GEL":2.7103, "GGP":0.8183, "GHS":14.1003, "GIP":0.8183, "GMD":63.3901, "GNF":8622.0204, "GTQ":7.8232, "GYD":209.1401, "HKD":7.7836, "HNL":24.6064, "HRK":7.1800, "HTG":140.8970, "HUF":392.6534, "IDR":15442.8385, "ILS":3.4027, "IMP":0.8183, "INR":81.0584, "IQD":1458.8962, "IRR":42036.3612, "ISK":142.4758, "JEP":0.8183, "JMD":153.8702, "JOD":0.7090, "JPY":135.7224, "KES":123.1351, "KGS":84.4410, "KHR":4125.2930, "KID":1.4694, "KMF":468.8174, "KRW":1303.6280, "KWD":0.2996, "KYD":0.8333, "KZT":468.1697, "LAK":17248.0199, "LBP":1507.5000, "LKR":363.4521, "LRD":153.9744, "LSL":17.5733, "LYD":4.8894, "MAD":10.6209, "MDL":19.4574, "MGA":4349.9903, "MKD":59.4362, "MMK":2552.4090, "MNT":3422.5815, "MOP":8.0171, "MRU":38.0126, "MUR":43.4017, "MVR":15.4048, "MWK":1032.9387, "MXN":19.1778, "MYR":4.4020, "MZN":63.9513, "NAD":17.5733, "NGN":443.8839, "NIO":36.3799, "NOK":9.7593, "NPR":129.6915, "NZD":1.5722, "OMR":0.3845, "PAB":1.0000, "PEN":3.8347, "PGK":3.5199, "PHP":56.1010, "PKR":224.1295, "PLN":4.4704, "PYG":7217.3743, "QAR":3.6400, "RON":4.6970, "RSD":112.1709, "RUB":61.1764, "RWF":1114.9049, "SAR":3.7500, "SBD":8.1036, "SCR":13.0656, "SDG":568.0316, "SEK":10.3601, "SGD":1.3561, "SHP":0.8183, "SLE":18.6210, "SLL":18620.9957, "SOS":568.2695, "SRD":30.9539, "SSP":644.4877, "STN":23.3471, "SYP":2504.9740, "SZL":17.5733, "THB":34.8989, "TJS":10.1357, "TMT":3.4988, "TND":2.9893, "TOP":2.3706, "TRY":18.6279, "TTD":6.7555, "TVD":1.4694, "TWD":30.4630, "TZS":2334.9042, "UAH":36.4641, "UGX":3745.5147, "UYU":39.4017, "UZS":11238.8195, "VES":11.2548, "VND":24496.1101, "VUV":120.8927, "WST":2.7081, "XAF":625.0899, "XCD":2.7000, "XDR":0.7578, "XOF":625.0899, "XPF":113.7166, "YER":250.1010, "ZAR":17.5753, "ZMW":17.0952, "ZWL":654.0107 } } json to data class kotlin plugin @Serializable data class ExchangeDto( val base_code: String, val conversion_rates: ConversionRates, val documentation: String, val result: String, val terms_of_use: String, val time_last_update_unix: Int, val time_last_update_utc: String, val time_next_update_unix: Int, val time_next_update_utc: String ) @Serializable data class ConversionRates( val AED: Double, val AFN: Double, val ALL: Double, val AMD: Double, val ANG: Double, val AOA: Double, val ARS: Double, val AUD: Double, val AWG: Double, val AZN: Double, val BAM: Double, val BBD: Double, val BDT: Double, val BGN: Double, val BHD: Double, val BIF: Double, val BMD: Double, val BND: Double, val BOB: Double, val BRL: Double, val BSD: Double, val BTN: Double, val BWP: Double, val BYN: Double, val BZD: Double, val CAD: Double, val CDF: Double, val CHF: Double, val CLP: Double, val CNY: Double, val COP: Double, val CRC: Double, val CUP: Double, val CVE: Double, val CZK: Double, val DJF: Double, val DKK: Double, val DOP: Double, val DZD: Double, val EGP: Double, val ERN: Double, val ETB: Double, val EUR: Double, val FJD: Double, val FKP: Double, val FOK: Double, val GBP: Double, val GEL: Double, val GGP: Double, val GHS: Double, val GIP: Double, val GMD: Double, val GNF: Double, val GTQ: Double, val GYD: Double, val HKD: Double, val HNL: Double, val HRK: Double, val HTG: Double, val HUF: Double, val IDR: Double, val ILS: Double, val IMP: Double, val INR: Double, val IQD: Double, val IRR: Double, val ISK: Double, val JEP: Double, val JMD: Double, val JOD: Double, val JPY: Double, val KES: Double, val KGS: Double, val KHR: Double, val KID: Double, val KMF: Double, val KRW: Double, val KWD: Double, val KYD: Double, val KZT: Double, val LAK: Double, val LBP: Double, val LKR: Double, val LRD: Double, val LSL: Double, val LYD: Double, val MAD: Double, val MDL: Double, val MGA: Double, val MKD: Double, val MMK: Double, val MNT: Double, val MOP: Double, val MRU: Double, val MUR: Double, val MVR: Double, val MWK: Double, val MXN: Double, val MYR: Double, val MZN: Double, val NAD: Double, val NGN: Double, val NIO: Double, val NOK: Double, val NPR: Double, val NZD: Double, val OMR: Double, val PAB: Double, val PEN: Double, val PGK: Double, val PHP: Double, val PKR: Double, val PLN: Double, val PYG: Double, val QAR: Double, val RON: Double, val RSD: Double, val RUB: Double, val RWF: Double, val SAR: Double, val SBD: Double, val SCR: Double, val SDG: Double, val SEK: Double, val SGD: Double, val SHP: Double, val SLE: Double, val SLL: Double, val SOS: Double, val SRD: Double, val SSP: Double, val STN: Double, val SYP: Double, val SZL: Double, val THB: Double, val TJS: Double, val TMT: Double, val TND: Double, val TOP: Double, val TRY: Double, val TTD: Double, val TVD: Double, val TWD: Double, val TZS: Double, val UAH: Double, val UGX: Double, val USD: Int, val UYU: Double, val UZS: Double, val VES: Double, val VND: Double, val VUV: Double, val WST: Double, val XAF: Double, val XCD: Double, val XDR: Double, val XOF: Double, val XPF: Double, val YER: Double, val ZAR: Double, val ZMW: Double, val ZWL: Double ) I think it's a bad translation when it's like this. How can I improve this or how can I create my own data class A: You can do it like this. Instead of having each field for each currencies, you can make coversion_rates as Map , so currency will be the key and value will the currency value. So it will be easier for iterating all currencies, getting value from currency name and so on... @Serializable data class ExchangeDto( val base_code: String, @TypeConverters(MapTypeConverter::class) //Add annotation val conversion_rates: Map<String,Double>, val documentation: String, val result: String, val terms_of_use: String, val time_last_update_unix: Int, val time_last_update_utc: String, val time_next_update_unix: Int, val time_next_update_utc: String ) Edit: Type converter for currency map: object MapTypeConverter { @TypeConverter @JvmStatic fun covertStringToMap(value: String): Map<String, String> { return Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type) } @TypeConverter @JvmStatic fun mapToString(value: Map<String, String>?): String { return if(value == null) "" else Gson().toJson(value) } }
How can I create my data class for my json file?
I am a new kotlin programmer and I cant create data class for json file. I always run into a problem. I've worked with simple json files before, but this confused me a bit. How can I convert this json file to data class. By the way, I tried the json to data class, which is an extension of kotlin, then it outputs a data class like this, frankly, this is not a very readable data class, does anyone have a better idea? my json file { "result":"success", "documentation":"https://www.exchangerate-api.com/docs", "terms_of_use":"https://www.exchangerate-api.com/terms", "time_last_update_unix":1669939202, "time_last_update_utc":"Fri, 02 Dec 2022 00:00:02 +0000", "time_next_update_unix":1670025602, "time_next_update_utc":"Sat, 03 Dec 2022 00:00:02 +0000", "base_code":"USD", "conversion_rates":{ "USD":1, "AED":3.6725, "AFN":88.0236, "ALL":112.3100, "AMD":395.3092, "ANG":1.7900, "AOA":509.4547, "ARS":166.9052, "AUD":1.4696, "AWG":1.7900, "AZN":1.6980, "BAM":1.8638, "BBD":2.0000, "BDT":101.4835, "BGN":1.8647, "BHD":0.3760, "BIF":2053.3857, "BMD":1.0000, "BND":1.3561, "BOB":6.9195, "BRL":5.1984, "BSD":1.0000, "BTN":81.0572, "BWP":13.0619, "BYN":2.6482, "BZD":2.0000, "CAD":1.3433, "CDF":2054.6915, "CHF":0.9394, "CLP":890.3480, "CNY":7.0548, "COP":4815.7969, "CRC":601.6168, "CUP":24.0000, "CVE":105.0763, "CZK":23.2743, "DJF":177.7210, "DKK":7.1093, "DOP":54.3860, "DZD":138.5331, "EGP":24.5835, "ERN":15.0000, "ETB":53.4963, "EUR":0.9530, "FJD":2.1960, "FKP":0.8183, "FOK":7.1093, "GBP":0.8183, "GEL":2.7103, "GGP":0.8183, "GHS":14.1003, "GIP":0.8183, "GMD":63.3901, "GNF":8622.0204, "GTQ":7.8232, "GYD":209.1401, "HKD":7.7836, "HNL":24.6064, "HRK":7.1800, "HTG":140.8970, "HUF":392.6534, "IDR":15442.8385, "ILS":3.4027, "IMP":0.8183, "INR":81.0584, "IQD":1458.8962, "IRR":42036.3612, "ISK":142.4758, "JEP":0.8183, "JMD":153.8702, "JOD":0.7090, "JPY":135.7224, "KES":123.1351, "KGS":84.4410, "KHR":4125.2930, "KID":1.4694, "KMF":468.8174, "KRW":1303.6280, "KWD":0.2996, "KYD":0.8333, "KZT":468.1697, "LAK":17248.0199, "LBP":1507.5000, "LKR":363.4521, "LRD":153.9744, "LSL":17.5733, "LYD":4.8894, "MAD":10.6209, "MDL":19.4574, "MGA":4349.9903, "MKD":59.4362, "MMK":2552.4090, "MNT":3422.5815, "MOP":8.0171, "MRU":38.0126, "MUR":43.4017, "MVR":15.4048, "MWK":1032.9387, "MXN":19.1778, "MYR":4.4020, "MZN":63.9513, "NAD":17.5733, "NGN":443.8839, "NIO":36.3799, "NOK":9.7593, "NPR":129.6915, "NZD":1.5722, "OMR":0.3845, "PAB":1.0000, "PEN":3.8347, "PGK":3.5199, "PHP":56.1010, "PKR":224.1295, "PLN":4.4704, "PYG":7217.3743, "QAR":3.6400, "RON":4.6970, "RSD":112.1709, "RUB":61.1764, "RWF":1114.9049, "SAR":3.7500, "SBD":8.1036, "SCR":13.0656, "SDG":568.0316, "SEK":10.3601, "SGD":1.3561, "SHP":0.8183, "SLE":18.6210, "SLL":18620.9957, "SOS":568.2695, "SRD":30.9539, "SSP":644.4877, "STN":23.3471, "SYP":2504.9740, "SZL":17.5733, "THB":34.8989, "TJS":10.1357, "TMT":3.4988, "TND":2.9893, "TOP":2.3706, "TRY":18.6279, "TTD":6.7555, "TVD":1.4694, "TWD":30.4630, "TZS":2334.9042, "UAH":36.4641, "UGX":3745.5147, "UYU":39.4017, "UZS":11238.8195, "VES":11.2548, "VND":24496.1101, "VUV":120.8927, "WST":2.7081, "XAF":625.0899, "XCD":2.7000, "XDR":0.7578, "XOF":625.0899, "XPF":113.7166, "YER":250.1010, "ZAR":17.5753, "ZMW":17.0952, "ZWL":654.0107 } } json to data class kotlin plugin @Serializable data class ExchangeDto( val base_code: String, val conversion_rates: ConversionRates, val documentation: String, val result: String, val terms_of_use: String, val time_last_update_unix: Int, val time_last_update_utc: String, val time_next_update_unix: Int, val time_next_update_utc: String ) @Serializable data class ConversionRates( val AED: Double, val AFN: Double, val ALL: Double, val AMD: Double, val ANG: Double, val AOA: Double, val ARS: Double, val AUD: Double, val AWG: Double, val AZN: Double, val BAM: Double, val BBD: Double, val BDT: Double, val BGN: Double, val BHD: Double, val BIF: Double, val BMD: Double, val BND: Double, val BOB: Double, val BRL: Double, val BSD: Double, val BTN: Double, val BWP: Double, val BYN: Double, val BZD: Double, val CAD: Double, val CDF: Double, val CHF: Double, val CLP: Double, val CNY: Double, val COP: Double, val CRC: Double, val CUP: Double, val CVE: Double, val CZK: Double, val DJF: Double, val DKK: Double, val DOP: Double, val DZD: Double, val EGP: Double, val ERN: Double, val ETB: Double, val EUR: Double, val FJD: Double, val FKP: Double, val FOK: Double, val GBP: Double, val GEL: Double, val GGP: Double, val GHS: Double, val GIP: Double, val GMD: Double, val GNF: Double, val GTQ: Double, val GYD: Double, val HKD: Double, val HNL: Double, val HRK: Double, val HTG: Double, val HUF: Double, val IDR: Double, val ILS: Double, val IMP: Double, val INR: Double, val IQD: Double, val IRR: Double, val ISK: Double, val JEP: Double, val JMD: Double, val JOD: Double, val JPY: Double, val KES: Double, val KGS: Double, val KHR: Double, val KID: Double, val KMF: Double, val KRW: Double, val KWD: Double, val KYD: Double, val KZT: Double, val LAK: Double, val LBP: Double, val LKR: Double, val LRD: Double, val LSL: Double, val LYD: Double, val MAD: Double, val MDL: Double, val MGA: Double, val MKD: Double, val MMK: Double, val MNT: Double, val MOP: Double, val MRU: Double, val MUR: Double, val MVR: Double, val MWK: Double, val MXN: Double, val MYR: Double, val MZN: Double, val NAD: Double, val NGN: Double, val NIO: Double, val NOK: Double, val NPR: Double, val NZD: Double, val OMR: Double, val PAB: Double, val PEN: Double, val PGK: Double, val PHP: Double, val PKR: Double, val PLN: Double, val PYG: Double, val QAR: Double, val RON: Double, val RSD: Double, val RUB: Double, val RWF: Double, val SAR: Double, val SBD: Double, val SCR: Double, val SDG: Double, val SEK: Double, val SGD: Double, val SHP: Double, val SLE: Double, val SLL: Double, val SOS: Double, val SRD: Double, val SSP: Double, val STN: Double, val SYP: Double, val SZL: Double, val THB: Double, val TJS: Double, val TMT: Double, val TND: Double, val TOP: Double, val TRY: Double, val TTD: Double, val TVD: Double, val TWD: Double, val TZS: Double, val UAH: Double, val UGX: Double, val USD: Int, val UYU: Double, val UZS: Double, val VES: Double, val VND: Double, val VUV: Double, val WST: Double, val XAF: Double, val XCD: Double, val XDR: Double, val XOF: Double, val XPF: Double, val YER: Double, val ZAR: Double, val ZMW: Double, val ZWL: Double ) I think it's a bad translation when it's like this. How can I improve this or how can I create my own data class
[ "You can do it like this. Instead of having each field for each currencies, you can make coversion_rates as Map , so currency will be the key and value will the currency value. So it will be easier for iterating all currencies, getting value from currency name and so on...\n@Serializable\ndata class ExchangeDto(\n val base_code: String,\n\n @TypeConverters(MapTypeConverter::class) //Add annotation\n val conversion_rates: Map<String,Double>,\n\n val documentation: String,\n val result: String,\n val terms_of_use: String,\n val time_last_update_unix: Int,\n val time_last_update_utc: String,\n val time_next_update_unix: Int,\n val time_next_update_utc: String\n) \n\nEdit:\nType converter for currency map:\nobject MapTypeConverter {\n\n@TypeConverter\n@JvmStatic\nfun covertStringToMap(value: String): Map<String, String> {\n return Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)\n}\n\n@TypeConverter\n@JvmStatic\nfun mapToString(value: Map<String, String>?): String {\n return if(value == null) \"\" else Gson().toJson(value)\n}\n\n}\n" ]
[ 3 ]
[]
[]
[ "json", "kotlin" ]
stackoverflow_0074656943_json_kotlin.txt
Q: check occurence of a timestamp in a column of timestamps I have a column with timestamps formatted like this printing one row it looks like this for example: "2022-09-21 02:02:03 UTC" There are many rows that have the same timestamp, but I want another column with the first timestamp after a specific times based on a vector that looks like this: start_1 <- strptime("07:15:00, format= "%H:%M:%S") start_2 <- strptime("09:15:00, format= "%H:%M:%S") Based on my start_1 timestamp I want to check in my df below which is the first timestamp after start_1 and mark that one in another column called start_datetime. I only want to mark the first timestamp after the start in my dataset, this is crucial for what I am trying to do, since many of the rows have exactly the same timestamp. Datetime start_datetime 2022-09-21 07:02:03 NA 2022-09-21 07:02:03 NA 2022-09-21 07:14:03 NA 2022-09-21 07:16:03 07:16 2022-09-21 07:16:03 NA 2022-09-21 09:19:03 09:19 I've explored multiple options, but so far I've been struggling to find a solution. A: Try something like this using dplyr and lubridate. To use a variable from the Global Environment "start_1" and "start_2" try .env or !! library(dplyr) library(lubridate) start_1 <- hms("07:15:00") start_2 <- hms("09:15:00") df %>% mutate(time = hms(sapply(strsplit(Datetime, " "), "[", 2)), d1 = time > .env$start_1, d2 = time > .env$start_2, start_datetime = case_when(lag(d1) != d1 ~ paste0(hour(time), ":", minute(time)), lag(d2) != d2 ~ paste0(hour(time), ":", minute(time)))) %>% select(Datetime, start_datetime) Datetime start_datetime 1 2022-09-21 07:02:03 <NA> 2 2022-09-21 07:02:03 <NA> 3 2022-09-21 07:14:03 <NA> 4 2022-09-21 07:16:03 7:16 5 2022-09-21 07:16:03 <NA> 6 2022-09-21 09:19:03 9:19 Data df <- structure(list(Datetime = c("2022-09-21 07:02:03", "2022-09-21 07:02:03", "2022-09-21 07:14:03", "2022-09-21 07:16:03", "2022-09-21 07:16:03", "2022-09-21 09:19:03")), class = "data.frame", row.names = c(NA, -6L)) A: I'm assuming that this is a "per day" thing, meaning that your start_1 and start_2 just reflect time-of-day (which means strptime is not doing what you want). If your Datetime column is class character, then we can make some assumptions about lexicographic sorting and do something like this: start_1 <- "07:15:00"; start_2 <- "09:15:00" library(dplyr) # library(purrr) # map_dfc quux %>% mutate( Date = substring(Datetime, 1, 10), purrr::map_dfc(list(s1 = start_1, s2 = start_2), ~ if_else(substring(Datetime, nchar(Datetime) - 7, nchar(Datetime)) > ., ., .[NA])) ) %>% group_by(Date) %>% mutate( across(c(s1, s2), ~ replace(., duplicated(.), NA)), start_datetime = coalesce(s1, s2) ) %>% ungroup() %>% select(-Date, -s1, -s2) # # A tibble: 6 x 2 # Datetime start_datetime # <chr> <chr> # 1 2022-09-21 07:02:03 NA # 2 2022-09-21 07:02:03 NA # 3 2022-09-21 07:14:03 NA # 4 2022-09-21 07:16:03 07:15:00 # 5 2022-09-21 07:16:03 NA # 6 2022-09-21 09:19:03 09:15:00 In fact, we can generalize this to any number of starts. fun <- function(time, starts) { tmp <- which( apply(outer(time, starts, `>`), 2, function(z) replace(z, c(FALSE, z[-length(z)]), FALSE)), arr.ind = TRUE) replace(time[NA], tmp[,"row"], starts[tmp[,"col"]]) } starts <- c("07:15:00", "09:15:00") quux %>% mutate( Date = substring(Datetime, 1, 10), Time = substring(Datetime, 12, 19) ) %>% group_by(Date) %>% mutate(start_datetime = fun(Time, starts)) %>% ungroup() %>% select(-Date, -Time) # # A tibble: 6 x 2 # Datetime start_datetime # <chr> <chr> # 1 2022-09-21 07:02:03 NA # 2 2022-09-21 07:02:03 NA # 3 2022-09-21 07:14:03 NA # 4 2022-09-21 07:16:03 07:15:00 # 5 2022-09-21 07:16:03 NA # 6 2022-09-21 09:19:03 09:15:00
check occurence of a timestamp in a column of timestamps
I have a column with timestamps formatted like this printing one row it looks like this for example: "2022-09-21 02:02:03 UTC" There are many rows that have the same timestamp, but I want another column with the first timestamp after a specific times based on a vector that looks like this: start_1 <- strptime("07:15:00, format= "%H:%M:%S") start_2 <- strptime("09:15:00, format= "%H:%M:%S") Based on my start_1 timestamp I want to check in my df below which is the first timestamp after start_1 and mark that one in another column called start_datetime. I only want to mark the first timestamp after the start in my dataset, this is crucial for what I am trying to do, since many of the rows have exactly the same timestamp. Datetime start_datetime 2022-09-21 07:02:03 NA 2022-09-21 07:02:03 NA 2022-09-21 07:14:03 NA 2022-09-21 07:16:03 07:16 2022-09-21 07:16:03 NA 2022-09-21 09:19:03 09:19 I've explored multiple options, but so far I've been struggling to find a solution.
[ "Try something like this using dplyr and lubridate. To use a variable from the Global Environment \"start_1\" and \"start_2\" try .env or !!\nlibrary(dplyr)\nlibrary(lubridate)\n\nstart_1 <- hms(\"07:15:00\")\nstart_2 <- hms(\"09:15:00\")\n\ndf %>% \n mutate(time = hms(sapply(strsplit(Datetime, \" \"), \"[\", 2)), \n d1 = time > .env$start_1, \n d2 = time > .env$start_2, \n start_datetime = \n case_when(lag(d1) != d1 ~ paste0(hour(time), \":\", minute(time)), \n lag(d2) != d2 ~ paste0(hour(time), \":\", minute(time)))) %>% \n select(Datetime, start_datetime)\n Datetime start_datetime\n1 2022-09-21 07:02:03 <NA>\n2 2022-09-21 07:02:03 <NA>\n3 2022-09-21 07:14:03 <NA>\n4 2022-09-21 07:16:03 7:16\n5 2022-09-21 07:16:03 <NA>\n6 2022-09-21 09:19:03 9:19\n\nData\ndf <- structure(list(Datetime = c(\"2022-09-21 07:02:03\", \"2022-09-21 07:02:03\",\n\"2022-09-21 07:14:03\", \"2022-09-21 07:16:03\", \"2022-09-21 07:16:03\",\n\"2022-09-21 09:19:03\")), class = \"data.frame\", row.names = c(NA,\n-6L))\n\n", "I'm assuming that this is a \"per day\" thing, meaning that your start_1 and start_2 just reflect time-of-day (which means strptime is not doing what you want).\nIf your Datetime column is class character, then we can make some assumptions about lexicographic sorting and do something like this:\nstart_1 <- \"07:15:00\"; start_2 <- \"09:15:00\"\nlibrary(dplyr)\n# library(purrr) # map_dfc\nquux %>%\n mutate(\n Date = substring(Datetime, 1, 10),\n purrr::map_dfc(list(s1 = start_1, s2 = start_2),\n ~ if_else(substring(Datetime, nchar(Datetime) - 7, nchar(Datetime)) > .,\n ., .[NA]))\n ) %>%\n group_by(Date) %>%\n mutate(\n across(c(s1, s2), ~ replace(., duplicated(.), NA)), \n start_datetime = coalesce(s1, s2)\n ) %>%\n ungroup() %>%\n select(-Date, -s1, -s2)\n# # A tibble: 6 x 2\n# Datetime start_datetime\n# <chr> <chr> \n# 1 2022-09-21 07:02:03 NA \n# 2 2022-09-21 07:02:03 NA \n# 3 2022-09-21 07:14:03 NA \n# 4 2022-09-21 07:16:03 07:15:00 \n# 5 2022-09-21 07:16:03 NA \n# 6 2022-09-21 09:19:03 09:15:00 \n\nIn fact, we can generalize this to any number of starts.\nfun <- function(time, starts) {\n tmp <- which(\n apply(outer(time, starts, `>`), 2, function(z) replace(z, c(FALSE, z[-length(z)]), FALSE)),\n arr.ind = TRUE)\n replace(time[NA], tmp[,\"row\"], starts[tmp[,\"col\"]])\n}\nstarts <- c(\"07:15:00\", \"09:15:00\")\n\nquux %>%\n mutate(\n Date = substring(Datetime, 1, 10),\n Time = substring(Datetime, 12, 19)\n ) %>%\n group_by(Date) %>%\n mutate(start_datetime = fun(Time, starts)) %>%\n ungroup() %>%\n select(-Date, -Time)\n# # A tibble: 6 x 2\n# Datetime start_datetime\n# <chr> <chr> \n# 1 2022-09-21 07:02:03 NA \n# 2 2022-09-21 07:02:03 NA \n# 3 2022-09-21 07:14:03 NA \n# 4 2022-09-21 07:16:03 07:15:00 \n# 5 2022-09-21 07:16:03 NA \n# 6 2022-09-21 09:19:03 09:15:00 \n\n" ]
[ 0, 0 ]
[]
[]
[ "lubridate", "posixct", "r" ]
stackoverflow_0074655168_lubridate_posixct_r.txt
Q: Why does this error appear when building release build and causes crash but not with emulator or usb debug? I am having an issue where the application that is build using ./gradlew bundleRelease (aab) or ./gradlew assembleRelease (apk). At the moment when user clicks the application it crashes straightaway and this issue doesn't happen on emulator when building the application using npx react-native run-android or using the real device through usb debugging. In the google play developer console I got the following error that shows up FATAL EXCEPTION: create_react_context Process: com.vahingonsattuessa, PID: 18803 java.lang.RuntimeException: Unable to load script. Make sure you're either running Metro (run 'npx react-native start') or that your bundle 'index.android.bundle' is packaged correctly for release. at com.facebook.react.bridge.CatalystInstanceImpl.jniLoadScriptFromAssets(Native Method) at com.facebook.react.bridge.CatalystInstanceImpl.loadScriptFromAssets(CatalystInstanceImpl.java:248) at com.facebook.react.bridge.JSBundleLoader$1.loadScript(JSBundleLoader.java:29) at com.facebook.react.bridge.CatalystInstanceImpl.runJSBundle(CatalystInstanceImpl.java:277) at com.facebook.react.ReactInstanceManager.createReactContext(ReactInstanceManager.java:1408) at com.facebook.react.ReactInstanceManager.access$1200(ReactInstanceManager.java:138) at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:1104) at java.lang.Thread.run(Thread.java:764) And java.lang.RuntimeException: at com.facebook.react.bridge.CatalystInstanceImpl.jniLoadScriptFromAssets (Native Method) at com.facebook.react.bridge.CatalystInstanceImpl.loadScriptFromAssets (CatalystInstanceImpl.java:248) at com.facebook.react.bridge.JSBundleLoader$1.loadScript (JSBundleLoader.java:29) at com.facebook.react.bridge.CatalystInstanceImpl.runJSBundle (CatalystInstanceImpl.java:277) at com.facebook.react.ReactInstanceManager.createReactContext (ReactInstanceManager.java:1408) at com.facebook.react.ReactInstanceManager.access$1200 (ReactInstanceManager.java:138) at com.facebook.react.ReactInstanceManager$5.run (ReactInstanceManager.java:1104) at java.lang.Thread.run (Thread.java:923) Any ideas why this happens and how would I be able to fix this? A: The same here. I don't know why. I already ammend the build.gradle adding project.ext.react = [ enableHermes: false, // clean and rebuild if changing root: "../../", entryFile: "index.js", cliPath: "node_modules/haul/bin/cli.js", devDisabledInAppDev: true, devDisabledInAppTest: true, devDisabledInRelease: true, bundleInAppDev: true, bundleInAppTest: true, bundleInRelease: true, ] But, didn't work yet. Even after this fix I'm getting the crash. I keep going looking for the issue.
Why does this error appear when building release build and causes crash but not with emulator or usb debug?
I am having an issue where the application that is build using ./gradlew bundleRelease (aab) or ./gradlew assembleRelease (apk). At the moment when user clicks the application it crashes straightaway and this issue doesn't happen on emulator when building the application using npx react-native run-android or using the real device through usb debugging. In the google play developer console I got the following error that shows up FATAL EXCEPTION: create_react_context Process: com.vahingonsattuessa, PID: 18803 java.lang.RuntimeException: Unable to load script. Make sure you're either running Metro (run 'npx react-native start') or that your bundle 'index.android.bundle' is packaged correctly for release. at com.facebook.react.bridge.CatalystInstanceImpl.jniLoadScriptFromAssets(Native Method) at com.facebook.react.bridge.CatalystInstanceImpl.loadScriptFromAssets(CatalystInstanceImpl.java:248) at com.facebook.react.bridge.JSBundleLoader$1.loadScript(JSBundleLoader.java:29) at com.facebook.react.bridge.CatalystInstanceImpl.runJSBundle(CatalystInstanceImpl.java:277) at com.facebook.react.ReactInstanceManager.createReactContext(ReactInstanceManager.java:1408) at com.facebook.react.ReactInstanceManager.access$1200(ReactInstanceManager.java:138) at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:1104) at java.lang.Thread.run(Thread.java:764) And java.lang.RuntimeException: at com.facebook.react.bridge.CatalystInstanceImpl.jniLoadScriptFromAssets (Native Method) at com.facebook.react.bridge.CatalystInstanceImpl.loadScriptFromAssets (CatalystInstanceImpl.java:248) at com.facebook.react.bridge.JSBundleLoader$1.loadScript (JSBundleLoader.java:29) at com.facebook.react.bridge.CatalystInstanceImpl.runJSBundle (CatalystInstanceImpl.java:277) at com.facebook.react.ReactInstanceManager.createReactContext (ReactInstanceManager.java:1408) at com.facebook.react.ReactInstanceManager.access$1200 (ReactInstanceManager.java:138) at com.facebook.react.ReactInstanceManager$5.run (ReactInstanceManager.java:1104) at java.lang.Thread.run (Thread.java:923) Any ideas why this happens and how would I be able to fix this?
[ "The same here. I don't know why. I already ammend the build.gradle adding\nproject.ext.react = [\n enableHermes: false, // clean and rebuild if changing\n root: \"../../\",\n entryFile: \"index.js\",\n cliPath: \"node_modules/haul/bin/cli.js\",\n devDisabledInAppDev: true,\n devDisabledInAppTest: true,\n devDisabledInRelease: true,\n bundleInAppDev: true,\n bundleInAppTest: true,\n bundleInRelease: true,\n]\n\nBut, didn't work yet. Even after this fix I'm getting the crash.\nI keep going looking for the issue.\n" ]
[ 0 ]
[]
[]
[ "react_native" ]
stackoverflow_0071569887_react_native.txt
Q: JSeparator dashed style I am using a JSeparator in my java swing application. The normal implementation makes the separator normal line; but what I need is the separator should be dashed(like we create dashed border). Is there any way we can do that? Thanks A: To create a custom JSeparator, you can override the paint() method of BasicSeparatorUI, discussed here, and draw the line using a dashed Stroke, illustrated here. Addendum: A more familiar approach overrides paintComponent(), as shown in the accepted answer and encapsulated conveniently in this StrokedSeparator. The variation below replaces drawLine() with draw() using a Line2D, which takes advantage of the stroke's geometry. import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Stroke; import java.awt.geom.Line2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSeparator; import static javax.swing.JSeparator.*; /** * @see https://stackoverflow.com/a/74657060/230513 */ public class StrokeSepTest { private static final int N = 10; private void display() { var f = new JFrame("StrokeSepTest"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); var stroke = new BasicStroke(8.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{5.0f}, 0.0f); var panel = new JPanel(new GridLayout(0, 1)) { @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } }; panel.setBackground(Color.white); for (int i = 0; i < N; i++) { Color color = Color.getHSBColor((float) i / N, 1, 1); panel.add(new StrokedSeparator(stroke, HORIZONTAL, color)); } f.add(panel); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } // @see https://stackoverflow.com/a/74657060/230513 */ private static class StrokedSeparator extends JSeparator { private Stroke stroke; public StrokedSeparator() { this(new BasicStroke(1F), HORIZONTAL); } public StrokedSeparator(int orientation) { this(new BasicStroke(1F), orientation); } public StrokedSeparator(Stroke stroke) { this(stroke, HORIZONTAL); } public StrokedSeparator(Stroke stroke, int orientation) { super(orientation); this.stroke = stroke; } public StrokedSeparator(Stroke stroke, int orientation, Color color) { super(orientation); super.setForeground(color); this.stroke = stroke; } @Override public void paintComponent(Graphics g) { var graphics = (Graphics2D) g; var s = getSize(); graphics.setStroke(stroke); graphics.setColor(getForeground()); if (getOrientation() == JSeparator.VERTICAL) { graphics.draw(new Line2D.Double(0, 0, 0, s.height)); } else // HORIZONTAL { graphics.draw(new Line2D.Double(0, 0, s.width, 0)); } } } public static void main(String[] args) { EventQueue.invokeLater(new StrokeSepTest()::display); } } A: You can use the following code snippet to create a dashed line. import java.awt.Container; import java.awt.Graphics; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JSeparator; public class SeparatorSample { public static void main(String args[]) { JFrame f = new JFrame("JSeparator Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = f.getContentPane(); content.setLayout(new GridLayout(0, 1)); JLabel above = new JLabel("Above Separator"); content.add(above); JSeparator separator = new JSeparator() { private static final long serialVersionUID = 1L; public void paintComponent(Graphics g) { for (int x = 0; x < 300; x += 15) g.drawLine(x, 0, x + 10, 0); } }; content.add(separator); JLabel below = new JLabel("Below Separator"); content.add(below); f.setSize(300, 100); f.setVisible(true); } } A: With a slight modification to trashgod's answer, I found that using paintComponent() rather than paint() works very well for me: Stroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] { 5.0f }, 0.0f); JSeparator separator = new StrokedSeparator(stroke); // Add separator to container And here's the StrokedSeparator class: import java.awt.BasicStroke; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Stroke; import javax.swing.JSeparator; public class StrokedSeparator extends JSeparator { private static final long serialVersionUID = 1L; private Stroke stroke; public StrokedSeparator() { this(new BasicStroke(1F), HORIZONTAL); } public StrokedSeparator(int orientation) { this(new BasicStroke(1F), orientation); } public StrokedSeparator(Stroke stroke) { this(stroke, HORIZONTAL); } public StrokedSeparator(Stroke stroke, int orientation) { super(orientation); this.stroke = stroke; } @Override public void paintComponent(Graphics g) { Dimension s = getSize(); Graphics2D graphics = (Graphics2D) g.create(); graphics.setStroke(stroke); if (getOrientation() == JSeparator.VERTICAL) { graphics.setColor(getForeground()); graphics.drawLine(0, 0, 0, s.height); graphics.setColor(getBackground()); graphics.drawLine(1, 0, 1, s.height); } else // HORIZONTAL { graphics.setColor(getForeground()); graphics.drawLine(0, 0, s.width, 0); graphics.setColor(getBackground()); graphics.drawLine(0, 1, s.width, 1); } } }
JSeparator dashed style
I am using a JSeparator in my java swing application. The normal implementation makes the separator normal line; but what I need is the separator should be dashed(like we create dashed border). Is there any way we can do that? Thanks
[ "To create a custom JSeparator, you can override the paint() method of BasicSeparatorUI, discussed here, and draw the line using a dashed Stroke, illustrated here.\nAddendum: A more familiar approach overrides paintComponent(), as shown in the accepted answer and encapsulated conveniently in this StrokedSeparator. The variation below replaces drawLine() with draw() using a Line2D, which takes advantage of the stroke's geometry.\n\nimport java.awt.BasicStroke;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.EventQueue;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.GridLayout;\nimport java.awt.Stroke;\nimport java.awt.geom.Line2D;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JSeparator;\nimport static javax.swing.JSeparator.*;\n\n/**\n * @see https://stackoverflow.com/a/74657060/230513\n */\npublic class StrokeSepTest {\n\n private static final int N = 10;\n\n private void display() {\n var f = new JFrame(\"StrokeSepTest\");\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n var stroke = new BasicStroke(8.0f, BasicStroke.CAP_BUTT,\n BasicStroke.JOIN_MITER, 10.0f, new float[]{5.0f}, 0.0f);\n var panel = new JPanel(new GridLayout(0, 1)) {\n @Override\n public Dimension getPreferredSize() {\n return new Dimension(320, 240);\n }\n };\n panel.setBackground(Color.white);\n for (int i = 0; i < N; i++) {\n Color color = Color.getHSBColor((float) i / N, 1, 1);\n panel.add(new StrokedSeparator(stroke, HORIZONTAL, color));\n }\n f.add(panel);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n }\n\n // @see https://stackoverflow.com/a/74657060/230513 */\n private static class StrokedSeparator extends JSeparator {\n\n private Stroke stroke;\n\n public StrokedSeparator() {\n this(new BasicStroke(1F), HORIZONTAL);\n }\n\n public StrokedSeparator(int orientation) {\n this(new BasicStroke(1F), orientation);\n }\n\n public StrokedSeparator(Stroke stroke) {\n this(stroke, HORIZONTAL);\n }\n\n public StrokedSeparator(Stroke stroke, int orientation) {\n super(orientation);\n this.stroke = stroke;\n }\n\n public StrokedSeparator(Stroke stroke, int orientation, Color color) {\n super(orientation);\n super.setForeground(color);\n this.stroke = stroke;\n }\n\n @Override\n public void paintComponent(Graphics g) {\n var graphics = (Graphics2D) g;\n var s = getSize();\n graphics.setStroke(stroke);\n graphics.setColor(getForeground());\n if (getOrientation() == JSeparator.VERTICAL) {\n graphics.draw(new Line2D.Double(0, 0, 0, s.height));\n } else // HORIZONTAL\n {\n graphics.draw(new Line2D.Double(0, 0, s.width, 0));\n }\n }\n }\n\n public static void main(String[] args) {\n EventQueue.invokeLater(new StrokeSepTest()::display);\n }\n}\n\n", "You can use the following code snippet to create a dashed line.\nimport java.awt.Container;\nimport java.awt.Graphics;\nimport java.awt.GridLayout;\n\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JSeparator;\n\npublic class SeparatorSample {\n public static void main(String args[]) {\n JFrame f = new JFrame(\"JSeparator Sample\");\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n Container content = f.getContentPane();\n content.setLayout(new GridLayout(0, 1));\n JLabel above = new JLabel(\"Above Separator\");\n content.add(above);\n JSeparator separator = new JSeparator() {\n private static final long serialVersionUID = 1L;\n\n public void paintComponent(Graphics g) {\n for (int x = 0; x < 300; x += 15)\n g.drawLine(x, 0, x + 10, 0);\n }\n };\n content.add(separator);\n JLabel below = new JLabel(\"Below Separator\");\n content.add(below);\n f.setSize(300, 100);\n f.setVisible(true);\n }\n}\n\n", "With a slight modification to trashgod's answer, I found that using paintComponent() rather than paint() works very well for me:\nStroke stroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] { 5.0f },\n 0.0f);\nJSeparator separator = new StrokedSeparator(stroke);\n// Add separator to container\n\nAnd here's the StrokedSeparator class:\nimport java.awt.BasicStroke;\nimport java.awt.Dimension;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Stroke;\n\nimport javax.swing.JSeparator;\n\npublic class StrokedSeparator extends JSeparator {\n\n private static final long serialVersionUID = 1L;\n\n private Stroke stroke;\n\n public StrokedSeparator() {\n this(new BasicStroke(1F), HORIZONTAL);\n }\n\n public StrokedSeparator(int orientation) {\n this(new BasicStroke(1F), orientation);\n }\n\n public StrokedSeparator(Stroke stroke) {\n this(stroke, HORIZONTAL);\n }\n\n public StrokedSeparator(Stroke stroke, int orientation) {\n super(orientation);\n this.stroke = stroke;\n }\n\n @Override\n public void paintComponent(Graphics g) {\n Dimension s = getSize();\n\n Graphics2D graphics = (Graphics2D) g.create();\n graphics.setStroke(stroke);\n\n if (getOrientation() == JSeparator.VERTICAL) {\n graphics.setColor(getForeground());\n graphics.drawLine(0, 0, 0, s.height);\n\n graphics.setColor(getBackground());\n graphics.drawLine(1, 0, 1, s.height);\n } else // HORIZONTAL\n {\n graphics.setColor(getForeground());\n graphics.drawLine(0, 0, s.width, 0);\n\n graphics.setColor(getBackground());\n graphics.drawLine(0, 1, s.width, 1);\n }\n }\n}\n\n" ]
[ 3, 2, 1 ]
[]
[]
[ "java", "jseparator", "swing" ]
stackoverflow_0027077372_java_jseparator_swing.txt
Q: Mapbox-gl - How can I allow text/icon overlap without causing text mixtures? click here to see the issue with the text overlap The texts are on top of each other (click on image link above). "mapbox-gl": "^2.4.1", Layer : { type: 'symbol', layout: { 'text-field': '{nextShow}', 'icon-image':'assets/map/queue-bubble.png', 'icon-allow-overlap': true, 'icon-ignore-placement': true, 'text-allow-overlap': true, }, paint: { 'icon-translate': [-25, -25], 'text-translate': [-28, -28], 'text-color': 'black', 'text-halo-color': 'white', 'text-halo-blur': 1, 'text-halo-width': 5, } } thank you. A: The way you could achieve this is by allowing icon overlap only. That way the icons will always be visible, but the labels will be visible only when they do not collide with the labels of the other markers. To achieve this just add the following properties to your layout object: 'layout': { 'icon-allow-overlap': true, // The icon will be visible even if it collides with other previously drawn symbols. 'icon-ignore-placement': true, // Other symbols can be visible even if they collide with the icon. 'text-optional': true // Label will be hidden if it collides with other labels }
Mapbox-gl - How can I allow text/icon overlap without causing text mixtures?
click here to see the issue with the text overlap The texts are on top of each other (click on image link above). "mapbox-gl": "^2.4.1", Layer : { type: 'symbol', layout: { 'text-field': '{nextShow}', 'icon-image':'assets/map/queue-bubble.png', 'icon-allow-overlap': true, 'icon-ignore-placement': true, 'text-allow-overlap': true, }, paint: { 'icon-translate': [-25, -25], 'text-translate': [-28, -28], 'text-color': 'black', 'text-halo-color': 'white', 'text-halo-blur': 1, 'text-halo-width': 5, } } thank you.
[ "The way you could achieve this is by allowing icon overlap only. That way the icons will always be visible, but the labels will be visible only when they do not collide with the labels of the other markers. To achieve this just add the following properties to your layout object:\n 'layout': {\n 'icon-allow-overlap': true, // The icon will be visible even if it collides with other previously drawn symbols.\n 'icon-ignore-placement': true, // Other symbols can be visible even if they collide with the icon.\n 'text-optional': true // Label will be hidden if it collides with other labels\n }\n\n" ]
[ 0 ]
[ "You can set order symbol-z-order to \"source\" and then use your list index to reorder your marker with symbol-sort-key\nIn your example:\n{\n type: 'symbol',\n layout: {\n 'text-field': '{nextShow}',\n 'icon-image':'assets/map/queue-bubble.png',\n 'icon-allow-overlap': true,\n 'icon-ignore-placement': true,\n 'text-allow-overlap': true,\n 'symbol-z-order': 'source', // to order by symbol-sort-key\n 'symbol-sort-key': ['get', 'index'], //index should be defined in source feature properties\n },\n paint: {\n 'icon-translate': [-25, -25],\n 'text-translate': [-28, -28],\n 'text-color': 'black',\n 'text-halo-color': 'white',\n 'text-halo-blur': 1,\n 'text-halo-width': 5,\n }\n }\n\n" ]
[ -1 ]
[ "mapbox", "mapbox_gl" ]
stackoverflow_0070215271_mapbox_mapbox_gl.txt
Q: Getting 401 with ASP.NET Core with Bearer this is my first time using ASP and doing this kind of things. I'm trying to do a Back for a Unity proto I did with Mirror. Right now I have the Authentification with JwtBearer (settings.Bearer is where my BearerKey is) builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(settings.Bearer)), ValidateIssuerSigningKey = true, ValidateAudience = false, ValidateIssuer = false }; }); I'm telling to use Authoritation and Authentication app.UseAuthorization(); app.UseAuthentication(); Then I have the Controller of the Auth that returns you the jwt when you login [HttpPost("login")] public IActionResult Login(AuthRequests req) { var (success, content) = _authService.Login(req.Username, req.Password); if (!success) return BadRequest(content); return Ok(new AuthResponse(){token = content}); } And last the controller of Player itself that needs to be Authorized to use [Authorize] [ApiController] [Route("[controller]")] public class PlayerController : ControllerBase { //... [HttpPost] public Player Register(CreatePlayerRequest req) { var userId = int.Parse(User.FindFirst("id").Value); var user = context.users.First(u => u.Id == userId); var player = new Player() { Name = req.Name, Level = 1, Experience = 0, User = user }; context.Add(player); context.SaveChanges(); return player; } } With all this when I want to access to Register of player and send on Header "Authorization : Bearer <key>" it returns me a 401 Unauthorized. I'm still new to this and been searching for a whole day but still didn't found nothing that works :( A: found that in Core 3.0 or greatter you need app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); In this specific order
Getting 401 with ASP.NET Core with Bearer
this is my first time using ASP and doing this kind of things. I'm trying to do a Back for a Unity proto I did with Mirror. Right now I have the Authentification with JwtBearer (settings.Bearer is where my BearerKey is) builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o => { o.TokenValidationParameters = new TokenValidationParameters() { IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(settings.Bearer)), ValidateIssuerSigningKey = true, ValidateAudience = false, ValidateIssuer = false }; }); I'm telling to use Authoritation and Authentication app.UseAuthorization(); app.UseAuthentication(); Then I have the Controller of the Auth that returns you the jwt when you login [HttpPost("login")] public IActionResult Login(AuthRequests req) { var (success, content) = _authService.Login(req.Username, req.Password); if (!success) return BadRequest(content); return Ok(new AuthResponse(){token = content}); } And last the controller of Player itself that needs to be Authorized to use [Authorize] [ApiController] [Route("[controller]")] public class PlayerController : ControllerBase { //... [HttpPost] public Player Register(CreatePlayerRequest req) { var userId = int.Parse(User.FindFirst("id").Value); var user = context.users.First(u => u.Id == userId); var player = new Player() { Name = req.Name, Level = 1, Experience = 0, User = user }; context.Add(player); context.SaveChanges(); return player; } } With all this when I want to access to Register of player and send on Header "Authorization : Bearer <key>" it returns me a 401 Unauthorized. I'm still new to this and been searching for a whole day but still didn't found nothing that works :(
[ "found that in Core 3.0 or greatter you need\napp.UseAuthentication();\napp.UseRouting();\napp.UseAuthorization();\napp.UseEndpoints(endpoints => {\n endpoints.MapControllers();\n});\n\nIn this specific order\n" ]
[ 1 ]
[]
[]
[ "asp.net", "asp.net_core", "asp.net_web_api", "bearer_token", "unity3d" ]
stackoverflow_0074656624_asp.net_asp.net_core_asp.net_web_api_bearer_token_unity3d.txt
Q: Windows 11 pycocotools package installation error error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe' failed with exit code 2 I have installed C++ build tools and more. Install Visual C++ 2015 Build Tools from https://go.microsoft.com/fwlink/?LinkId=691126 with default selection. This cannot be install. Thank you for solutions. A: I assume you have already installed Visual C++ Latest Build Tools from Visual Studio 2022 Build Tools: https://aka.ms/vs/17/release/vs_buildtools.exe Now, Check the Pycocotools/PythonAPI folder and modify the setup.py file change these couple of lines as the following code and run this command again Previously : extra_compile_args=['-Wno-cpp', '-Wno-unused-function', '-std=c99'] Remove '-Wno-cpp', '-Wno-unused-function' from the ext_modules Extension in setup.py Only keep '-std=c99', and it will look like this. extra_compile_args=['-std=c99'] Now run this command once again. python setup.py build_ext --inplace this should successfully build the pycocotools in windows 11.
Windows 11 pycocotools package installation error
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe' failed with exit code 2 I have installed C++ build tools and more. Install Visual C++ 2015 Build Tools from https://go.microsoft.com/fwlink/?LinkId=691126 with default selection. This cannot be install. Thank you for solutions.
[ "I assume you have already installed Visual C++ Latest Build Tools\nfrom Visual Studio 2022 Build Tools: https://aka.ms/vs/17/release/vs_buildtools.exe\nNow, Check the Pycocotools/PythonAPI folder and modify the setup.py file\nchange these couple of lines as the following code and run this command again\nPreviously :\nextra_compile_args=['-Wno-cpp', '-Wno-unused-function', '-std=c99']\nRemove '-Wno-cpp', '-Wno-unused-function' from the ext_modules Extension in setup.py\nOnly keep '-std=c99', and it will look like this.\nextra_compile_args=['-std=c99']\nNow run this command once again.\npython setup.py build_ext --inplace\nthis should successfully build the pycocotools in windows 11.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074596492_python.txt
Q: How to pick a random item from an input list? I am making a program that asks how many players are playing, and then asks to input the names of those players. Then, I want it to print a random player, but I can't figure it out how. The code right now prints a random letter from the last name given, I think: import random player_numberCount = input("How many players are there: ") player_number = int(player_numberCount) for i in range(player_number): ask_player = input("name the players: ") print(random.choice(ask_player)) A: You need to add each player name entered to a list. Here is a starting point of what you need in your code: from random import choice number_of_players = int(input("How many players are there: ")) players = [] for _ in range(number_of_players): players.append(input("name the players: ")) print(choice(players)) A: That loop reassigns the ask_player variable on each iteration, erasing the previous value. Presumably you meant to save each value in a list: players = [] for i in range(player_number): players.append(input("Player name: ")) print(random.choice(players)) A: The problem is that in each for-loop iteration, you are reassigning the ask_player var to a string. When you pass a string to random.choice(...), it picks a random letter of that string (since strings can be indexed like arrays). Just define an array before the loop and append on each iteration: import random player_numberCount = input("How many players are there: ") player_number = int(player_numberCount) players = [] for i in range(player_number): players.append(input(f"name player {i + 1}: ")) print(random.choice(players)) A: import random player_number = int(input("How many players are there: ")) player_list = [] for _ in range(player_number): ask_player = input("name the players: ") player_list.append(ask_player) print(player_list[random.randint(0, player_number)])
How to pick a random item from an input list?
I am making a program that asks how many players are playing, and then asks to input the names of those players. Then, I want it to print a random player, but I can't figure it out how. The code right now prints a random letter from the last name given, I think: import random player_numberCount = input("How many players are there: ") player_number = int(player_numberCount) for i in range(player_number): ask_player = input("name the players: ") print(random.choice(ask_player))
[ "You need to add each player name entered to a list. Here is a starting point of what you need in your code:\nfrom random import choice\n\nnumber_of_players = int(input(\"How many players are there: \"))\nplayers = []\n\nfor _ in range(number_of_players):\n players.append(input(\"name the players: \"))\n\nprint(choice(players))\n\n", "That loop reassigns the ask_player variable on each iteration, erasing the previous value.\nPresumably you meant to save each value in a list:\nplayers = []\nfor i in range(player_number):\n players.append(input(\"Player name: \"))\n\nprint(random.choice(players))\n\n", "The problem is that in each for-loop iteration, you are reassigning the ask_player var to a string. When you pass a string to random.choice(...), it picks a random letter of that string (since strings can be indexed like arrays). Just define an array before the loop and append on each iteration:\nimport random\n\nplayer_numberCount = input(\"How many players are there: \")\nplayer_number = int(player_numberCount)\n\nplayers = []\nfor i in range(player_number):\n players.append(input(f\"name player {i + 1}: \"))\n\nprint(random.choice(players))\n\n", "import random\n\nplayer_number = int(input(\"How many players are there: \"))\nplayer_list = []\n\n\nfor _ in range(player_number):\n ask_player = input(\"name the players: \")\n player_list.append(ask_player)\n\nprint(player_list[random.randint(0, player_number)])\n\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "input", "python" ]
stackoverflow_0074651157_input_python.txt
Q: AttributeError: type Object 'Widget' has no attribute '_ipython_display_' In one of my python test case I have mockcomm object and in the mockcomm function I am using ipywidgets. Recently Upgraded ipywidgets version from 7 to 8. The code is working fine in version 7 of ipywidgets but when upgraded I am facing the below error. Saying Object has not attribute defined. did any one faced the error can help me. A: According to this issue, from ipywidgets 8, widgets uses _repr_mimebundle_ instead of _ipython_display_. So _widget_attrs['_ipython_display_'] will raise KeyError. Use _repr_mimebundle_ as key will sovle problem.
AttributeError: type Object 'Widget' has no attribute '_ipython_display_'
In one of my python test case I have mockcomm object and in the mockcomm function I am using ipywidgets. Recently Upgraded ipywidgets version from 7 to 8. The code is working fine in version 7 of ipywidgets but when upgraded I am facing the below error. Saying Object has not attribute defined. did any one faced the error can help me.
[ "According to this issue, from ipywidgets 8, widgets uses _repr_mimebundle_ instead of _ipython_display_.\nSo _widget_attrs['_ipython_display_'] will raise KeyError. Use _repr_mimebundle_ as key will sovle problem.\n" ]
[ 0 ]
[]
[]
[ "ipywidgets", "jupyter_notebook", "python" ]
stackoverflow_0073578290_ipywidgets_jupyter_notebook_python.txt
Q: How can we add confidence intervals to plots of effects from multinomial logistic regression models in R? I need to add confidence intervals (or eyes) to a plot of the effect(s) of multinomial logistic regression models. Here is a toy reproducible example of the kinds of data, logit model, and plot I am working with: install.packages("effects") library("effects") ToyData2 <- data.table(Answer = c("Remained incorrect", "Changed to correct", "Changed to correct", "Remained incorrect", "Remained correct", "Changed to incorrect", "Remained correct", "Changed to correct", "Changed to correct", "Changed to incorrect", "Remained incorrect", "Remained incorrect", "Remained correct", "Changed to incorrect", "Remained correct", "Changed to correct"), Sex = c("Male", "Male", "Female", "Male", "Female", "Female", "Male", "Male", "Female", "Male", "Female", "Female", NA, "Male", "Female", "Male"), Education = c("Less than Bachelors", "Less than Bachelors", "Bachelors",NA, "Post Bachelors","Post Bachelors","Bachelors", "Less than Bachelors", "Bachelors",NA,"Post Bachelors","Post Bachelors", "Post Bachelors", "Less than Bachelors", "Bachelors","Post Bachelors"), Minutes = c(1, 5, 1, 29, NA, 2, 1, 3, 4, 5, 1, 2, 2, 1, 3, 4), Problem = c("A","A","A","A", "B","B","B","B", "C","C","C","C", "D","D","D","D")) ToyData2 ToyData2$Answer <- factor(ToyData2$Answer, ordered = FALSE) summary(ToyData2$Answer) ToyData2$Answer <- relevel(ToyData2$Answer, ref = 'Changed to incorrect') ToyData2$Education <- factor(ToyData2$Education, levels = c("Less than Bachelors","Bachelors","Post Bachelors")) ToyOutcomeLogit <- multinom(Answer ~ Sex + Education + Minutes + Problem, data = ToyData2) summary(ToyOutcomeLogit) table(ToyData2$Minutes) plot(Effect('Minutes', ToyOutcomeLogit), multiline=T) table(ToyData2$Education) plot(Effect('Sex', ToyOutcomeLogit), multiline=T) Here are the plots that are produced by lines that begin with "plot": Effect of time (Minutes) Effect of (Bachelors) education Here are some of the libraries I am using (in the rest of my R file) in case you need them: library('pacman') p_load( 'data.table', 'DescTools', 'effects', 'ggpubr', 'ggsignif', 'glue', 'Hmisc', 'irr', 'lm.beta', 'nnet', 'openxlsx', 'psych', 'scales', 'sjPlot', 'stats', 'tidyr', 'tidyverse' ) How can get confidence intervals on plots like these? Or, more specifically: A. How can I tweak the existing code to add confidence intervals? B. What other functions could I use to plot these effects with confidence intervals? C. What other package's functions should I use? (Note: I am currently running R 4.2.2 in case that is relevant.) A: Apparently replacing multiline=T with confint=T in the plot command will add CIs—bands or bars. Bands: Bars: Alas, I have not found out how to add CIs to the collapsed multiline plot itself.
How can we add confidence intervals to plots of effects from multinomial logistic regression models in R?
I need to add confidence intervals (or eyes) to a plot of the effect(s) of multinomial logistic regression models. Here is a toy reproducible example of the kinds of data, logit model, and plot I am working with: install.packages("effects") library("effects") ToyData2 <- data.table(Answer = c("Remained incorrect", "Changed to correct", "Changed to correct", "Remained incorrect", "Remained correct", "Changed to incorrect", "Remained correct", "Changed to correct", "Changed to correct", "Changed to incorrect", "Remained incorrect", "Remained incorrect", "Remained correct", "Changed to incorrect", "Remained correct", "Changed to correct"), Sex = c("Male", "Male", "Female", "Male", "Female", "Female", "Male", "Male", "Female", "Male", "Female", "Female", NA, "Male", "Female", "Male"), Education = c("Less than Bachelors", "Less than Bachelors", "Bachelors",NA, "Post Bachelors","Post Bachelors","Bachelors", "Less than Bachelors", "Bachelors",NA,"Post Bachelors","Post Bachelors", "Post Bachelors", "Less than Bachelors", "Bachelors","Post Bachelors"), Minutes = c(1, 5, 1, 29, NA, 2, 1, 3, 4, 5, 1, 2, 2, 1, 3, 4), Problem = c("A","A","A","A", "B","B","B","B", "C","C","C","C", "D","D","D","D")) ToyData2 ToyData2$Answer <- factor(ToyData2$Answer, ordered = FALSE) summary(ToyData2$Answer) ToyData2$Answer <- relevel(ToyData2$Answer, ref = 'Changed to incorrect') ToyData2$Education <- factor(ToyData2$Education, levels = c("Less than Bachelors","Bachelors","Post Bachelors")) ToyOutcomeLogit <- multinom(Answer ~ Sex + Education + Minutes + Problem, data = ToyData2) summary(ToyOutcomeLogit) table(ToyData2$Minutes) plot(Effect('Minutes', ToyOutcomeLogit), multiline=T) table(ToyData2$Education) plot(Effect('Sex', ToyOutcomeLogit), multiline=T) Here are the plots that are produced by lines that begin with "plot": Effect of time (Minutes) Effect of (Bachelors) education Here are some of the libraries I am using (in the rest of my R file) in case you need them: library('pacman') p_load( 'data.table', 'DescTools', 'effects', 'ggpubr', 'ggsignif', 'glue', 'Hmisc', 'irr', 'lm.beta', 'nnet', 'openxlsx', 'psych', 'scales', 'sjPlot', 'stats', 'tidyr', 'tidyverse' ) How can get confidence intervals on plots like these? Or, more specifically: A. How can I tweak the existing code to add confidence intervals? B. What other functions could I use to plot these effects with confidence intervals? C. What other package's functions should I use? (Note: I am currently running R 4.2.2 in case that is relevant.)
[ "Apparently replacing multiline=T with confint=T in the plot command will add CIs—bands or bars.\nBands:\nBars:\nAlas, I have not found out how to add CIs to the collapsed multiline plot itself.\n" ]
[ 0 ]
[]
[]
[ "confidence_interval", "ggplot2", "logistic_regression", "plot", "r" ]
stackoverflow_0074634329_confidence_interval_ggplot2_logistic_regression_plot_r.txt
Q: Same objects merged one array I have input like this. I tried some solutions. But it doesn't work. I need to merge same invoice_nr objects to one array. Also I need other objects another array. All arrays must be another array. const result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ]; But, I need output like this. How can I achieve that in javascript? Array must be like this. const result = [ [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' } ], [ { invoice_nr: 17, order_id: 5574, color: 'green' } ], [ { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ] ]; A: You can use .reduce() to build a lookup object where key is the invoice_nr and value is an array. In every iteration look for a key is already exists in lookup object if it is then push to the existing list, if it's not add a new property in the lookup object. const result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ]; const res = result.reduce((a,b) => ((a[b.invoice_nr] ??= []).push(b),a),{}); console.log(Object.values(res)); .as-console-wrapper { max-height: 100% !important } A: const result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ]; let uniq = []; let res = []; // get unique ID result.forEach(i => !uniq.includes(i.invoice_nr) ? uniq.push(i.invoice_nr) : '' ); // filter by ID uniq.forEach(id => { res.push(result.filter(o => o.invoice_nr === id)) }) // that you need in res console.log(res); A: If they're in order, then I'd reduce like this: result.reduce((arr, item) => { const group = arr.at(-1), prevItem = group?.at(-1); if (prevItem?.invoice_nr === item.invoice_nr) { group.push(item); } else { arr.push([item]); } return arr; }, []);
Same objects merged one array
I have input like this. I tried some solutions. But it doesn't work. I need to merge same invoice_nr objects to one array. Also I need other objects another array. All arrays must be another array. const result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ]; But, I need output like this. How can I achieve that in javascript? Array must be like this. const result = [ [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' } ], [ { invoice_nr: 17, order_id: 5574, color: 'green' } ], [ { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ] ];
[ "You can use .reduce() to build a lookup object where key is the invoice_nr and value is an array. In every iteration look for a key is already exists in lookup object if it is then push to the existing list, if it's not add a new property in the lookup object.\n\n\nconst result = [ { invoice_nr: 16, order_id: 5577, color: 'red' }, { invoice_nr: 16, order_id: 5577, color: 'yellow' }, { invoice_nr: 17, order_id: 5574, color: 'green' }, { invoice_nr: 18, order_id: 5578, color: 'yellow' }, { invoice_nr: 18, order_id: 5578, color: 'blue' } ];\n\nconst res = result.reduce((a,b) => ((a[b.invoice_nr] ??= []).push(b),a),{});\nconsole.log(Object.values(res));\n.as-console-wrapper { max-height: 100% !important }\n\n\n\n", "\n\nconst result = [\n {\n invoice_nr: 16,\n order_id: 5577,\n color: 'red'\n },\n {\n invoice_nr: 16,\n order_id: 5577,\n color: 'yellow'\n },\n {\n invoice_nr: 17,\n order_id: 5574,\n color: 'green'\n },\n {\n invoice_nr: 18,\n order_id: 5578,\n color: 'yellow'\n },\n {\n invoice_nr: 18,\n order_id: 5578,\n color: 'blue'\n }\n];\n\nlet uniq = [];\nlet res = [];\n// get unique ID\nresult.forEach(i => !uniq.includes(i.invoice_nr) ? uniq.push(i.invoice_nr) : '' );\n// filter by ID\nuniq.forEach(id => {\n res.push(result.filter(o => o.invoice_nr === id))\n})\n// that you need in res\nconsole.log(res);\n\n\n\n", "If they're in order, then I'd reduce like this:\nresult.reduce((arr, item) => {\n const group = arr.at(-1), prevItem = group?.at(-1);\n if (prevItem?.invoice_nr === item.invoice_nr) {\n group.push(item);\n } else {\n arr.push([item]);\n }\n return arr;\n}, []);\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "arrays", "javascript", "merge", "node.js", "object" ]
stackoverflow_0074656498_arrays_javascript_merge_node.js_object.txt
Q: Error: 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions I have the following code in playground (Xcode 13.0): protocol Summable { static func +(lhs: Self, rhs: Self) -> Self } extension Int: Summable {} extension Double: Summable {} extension String: Summable {} struct Print { func printSummable(x: some Summable) { print(x) } } But I am getting the error 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions I want to print only the objects that conform to Summable. Do "some"/"any" keywords only work on protocols with associated types? A: It works on Swift version 5.7.1. I had to update my code :)
Error: 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions
I have the following code in playground (Xcode 13.0): protocol Summable { static func +(lhs: Self, rhs: Self) -> Self } extension Int: Summable {} extension Double: Summable {} extension String: Summable {} struct Print { func printSummable(x: some Summable) { print(x) } } But I am getting the error 'some' types are only implemented for the declared type of properties and subscripts and the return type of functions I want to print only the objects that conform to Summable. Do "some"/"any" keywords only work on protocols with associated types?
[ "It works on Swift version 5.7.1. I had to update my code :)\n" ]
[ 0 ]
[]
[]
[ "generics", "ios", "swift" ]
stackoverflow_0074618977_generics_ios_swift.txt
Q: Regex pattern to replace date and time node in xml of word document I need to replace the date and time in xml file using regex pattern. xml text would contain: w:date="2022-12-01T01:17:00Z" w:date="2022-12-01T02:17:00Z" w:date="2022-12-02T03:17:00Z" possible regex pattern for the above would be: w:date="[\d\W]\w[\d\W]\w" but it is not replacing anything and the resulted string remain intact in the following VBA code: Sub ChangeDateTime() Dim sWOOXML As String Set objRegEx = CreateObject("vbscript.regexp") objRegEx.Global = True objRegEx.IgnoreCase = True objRegEx.MultiLine = True objRegEx.Pattern = "w:date=" & Chr(34) & "[\d\W]\w[\d\W]\w" & Chr(34) sWOOXML = ActiveDocument.Content.WordOpenXML sWOOXML = objRegEx.Replace(sWOOXML, "") ActiveDocument.Content.InsertXML sWOOXML Beep End Sub A: Your [\d\W]\w[\d\W]\w regex prevents from matching since it only finds two repetitions of a digit or non-word char + a word char sequence between two double quotes, while you have many more chars there. You can use objRegEx.Pattern = "w:date=""\d{4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}Z""" See the regex demo. Note you may add a double quote to the string using a doubled ", no need to use Chr(34). This is a verbose pattern where \d{1,2} matches one or two digits and \d{4} matches four digits, the rest is self-explanatory.
Regex pattern to replace date and time node in xml of word document
I need to replace the date and time in xml file using regex pattern. xml text would contain: w:date="2022-12-01T01:17:00Z" w:date="2022-12-01T02:17:00Z" w:date="2022-12-02T03:17:00Z" possible regex pattern for the above would be: w:date="[\d\W]\w[\d\W]\w" but it is not replacing anything and the resulted string remain intact in the following VBA code: Sub ChangeDateTime() Dim sWOOXML As String Set objRegEx = CreateObject("vbscript.regexp") objRegEx.Global = True objRegEx.IgnoreCase = True objRegEx.MultiLine = True objRegEx.Pattern = "w:date=" & Chr(34) & "[\d\W]\w[\d\W]\w" & Chr(34) sWOOXML = ActiveDocument.Content.WordOpenXML sWOOXML = objRegEx.Replace(sWOOXML, "") ActiveDocument.Content.InsertXML sWOOXML Beep End Sub
[ "Your [\\d\\W]\\w[\\d\\W]\\w regex prevents from matching since it only finds two repetitions of a digit or non-word char + a word char sequence between two double quotes, while you have many more chars there.\nYou can use\nobjRegEx.Pattern = \"w:date=\"\"\\d{4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}Z\"\"\"\n\nSee the regex demo. Note you may add a double quote to the string using a doubled \", no need to use Chr(34).\nThis is a verbose pattern where \\d{1,2} matches one or two digits and \\d{4} matches four digits, the rest is self-explanatory.\n" ]
[ 0 ]
[]
[]
[ "ms_word", "regex", "vba", "xml" ]
stackoverflow_0074657017_ms_word_regex_vba_xml.txt
Q: After Effects Add To Media Encoder Not Working I'm trying to use the after effect and i try to use Media Encoder to eksport composition to mp4 but always show error like this here i solution i had try https://community.adobe.com/t5/adobe-media-encoder-discussions/media-encoder-not-connecting-with-dynamic-link/td-p/10946429 but i don't understand about "Finder menu, Press Option Key then click Go, pick Library" and i already delete adobe folder on document folder i also had installed the same version of after effects and Media Encoder Am I missing something?? I would be glad for any help. A: One solution would be to export the project as a MOV file directly from the render queue, and then use Media Encoder to convert the file to MP4.
After Effects Add To Media Encoder Not Working
I'm trying to use the after effect and i try to use Media Encoder to eksport composition to mp4 but always show error like this here i solution i had try https://community.adobe.com/t5/adobe-media-encoder-discussions/media-encoder-not-connecting-with-dynamic-link/td-p/10946429 but i don't understand about "Finder menu, Press Option Key then click Go, pick Library" and i already delete adobe folder on document folder i also had installed the same version of after effects and Media Encoder Am I missing something?? I would be glad for any help.
[ "One solution would be to export the project as a MOV file directly from the render queue, and then use Media Encoder to convert the file to MP4.\n" ]
[ 0 ]
[]
[]
[ "adobe", "after_effects", "encoder" ]
stackoverflow_0073264658_adobe_after_effects_encoder.txt
Q: User Login Authentication using Django Model and form I am trying to setup user authentication for the login page using forms and comparing it to my database value but it does not work. I also tried using this particular questions User Login Authentication using forms and Django logic to solve my problem but it didn't help. Models.py from django.db import models from django.contrib.auth.password_validation import validate_password class student(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) matric_number = models.CharField(max_length=9) email = models.EmailField(max_length=50) password1 = models.CharField(max_length=255, validators=[validate_password]) password2 = models.CharField(max_length=255) def __str__(self): return (self.matric_number) This view saves user info to database def student(request): if request.method == 'POST': form = studentForm(request.POST) if form.is_valid(): sign_up = form.save(commit=False) #sign_up.password1 = make_password(form.cleaned_data['password1']) #sign_up.password2 = make_password(form.cleaned_data['password2']) sign_up.status = 1 sign_up.save() user = form.cleaned_data.get('matric_number') messages.success(request, "Account was created for "+str(user)) return redirect(signin) else: form = studentForm() return render(request, 'Student.html',{ "form": form }) This is the signin view def signin(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') try: student = student.object.get(username=username, password=password) return redirect(files) except: messages.success(request, "Error") else: form = LoginForm() return render(request, "SignIn.html",{ "form":form }) This is my form.py class studentForm(forms.ModelForm): class Meta: model=student fields="__all__" widgets={ 'first_name':forms.TextInput(attrs={'placeholder': 'Enter Your First Name'}), 'last_name':forms.TextInput(attrs={'placeholder': 'Enter Your Last Name'}), 'matric_number':forms.TextInput(attrs={'placeholder': 'Enter Your Matric Number'}), 'email':forms.EmailInput(attrs={'placeholder': '[email protected]'}), 'password1':forms.PasswordInput(attrs={'placeholder': 'Enter Your Preferred Password','id':'password'}), 'password2':forms.PasswordInput(attrs={'placeholder':'Confirm Your Password', 'id':'password1'}) } def clean(self): super(studentForm, self).clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') matric_number = self.cleaned_data.get('matric_number') email = self.cleaned_data.get('email') try: if password1 != password2: self.errors[''] = self.error_class(["The two password fields must match"]) elif len(matric_number) != 9: self.errors[''] = self.error_class(["You have entered an invalid matric number"]) elif len(matric_number) == 9: matric_number = int(matric_number) except ValueError: self.errors[''] = self.error_class(["You have entered an invalid matric number"]) for instance in student.objects.all(): if instance.matric_number == str(matric_number): self.errors[''] = self.error_class(["Matric number already exist"]) elif instance.email == email: self.errors[''] = self.error_class(["E-mail address already exist"]) class LoginForm(forms.Form): matric_number = forms.CharField(max_length=9, widget=forms.TextInput(attrs={'id': 'username', 'placeholder': 'Enter Your Staff Id Or Matric Number'})) password1 = forms.CharField(max_length=9, widget=forms.PasswordInput(attrs={'id': 'password', 'placeholder':'Enter Your password'})) A: Stop reinventing the wheel. Also, class names are supposed to be named with PascalCase. Use AbstractUser model: from django.contrib.auth.models import AbstractUser class Student(AbstractUser): ... and in your main urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ ... path('login/', auth_views.LoginView.as_view(), name='login'), ... ] It is much faster and SAFER way to create new user. A: So I figured out out how to solve my problem. By using the AbstractUser model,i was able to create a custom user and then create another model which i extended a ForeignKey on the User model therefore allowing me to tie every user to their profile. Here is my models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): pass def __str__(self): return self.username class UserProfile(models.Model): """ This is the one for model.py """ username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default="") profile_picture = models.ImageField(blank=True, null=True, default="") matricno = models.CharField(max_length=9, default="", primary_key=True) email = models.EmailField(default="") first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Users Profile" def __str__(self): return self.first_name+ " "+self.last_name And here is my views.py def signup(request): if request.method == "POST": form = Signup(request.POST) if form.is_valid(): username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] password2 = request.POST["password2"] user = User.objects.create_user( username=username, password=password, email=email, ) user.save() login(request, user) messages.success(request, "Account Created successfully for " + username) return redirect(details) else: form = Signup() return render(request, "accounts/register.html", {"form": form}) def details(request, username): user = User.objects.get(username=username) form = Details() if request.method == "POST": form = Details(request.POST, request.FILES) if form.is_valid(): detail = form.save(commit=False) detail.username = request.user detail.save() return redirect(success, pk=detail.pk) else: form = Details(initial={"matricno":request.user.username}) return render(request, "details.html", {"form":form}) And finally my forms.py that i use in creating a signup form and perfoming validation class Signup(forms.Form): username = forms.CharField( max_length=9, widget=forms.TextInput(attrs={"placeholder": "Enter Your Matric Number"}), ) email = forms.EmailField( max_length=255, widget=forms.EmailInput(attrs={"placeholder": "Enter Your E-mail Address"}), ) password = forms.CharField( max_length=255, widget=forms.PasswordInput( attrs={"placeholder": "Enter Your Password", "id": "password"} ), ) password2 = forms.CharField( max_length=255, widget=forms.PasswordInput( attrs={"placeholder": "Confirm Your Password", "id": "password2"} ), ) def clean(self): super(Signup, self).clean() password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") username = self.cleaned_data.get("username") email = self.cleaned_data.get("email") if password != password2: self.errors[""] = self.error_class(["The two password fields must match"]) for instance in User.objects.all(): if instance.username == str(username): self.errors[""] = self.error_class(["User already exist"]) elif instance.email == email: self.errors[""] = self.error_class(["E-mail already in use"]) else: pass return self.cleaned_data
User Login Authentication using Django Model and form
I am trying to setup user authentication for the login page using forms and comparing it to my database value but it does not work. I also tried using this particular questions User Login Authentication using forms and Django logic to solve my problem but it didn't help. Models.py from django.db import models from django.contrib.auth.password_validation import validate_password class student(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) matric_number = models.CharField(max_length=9) email = models.EmailField(max_length=50) password1 = models.CharField(max_length=255, validators=[validate_password]) password2 = models.CharField(max_length=255) def __str__(self): return (self.matric_number) This view saves user info to database def student(request): if request.method == 'POST': form = studentForm(request.POST) if form.is_valid(): sign_up = form.save(commit=False) #sign_up.password1 = make_password(form.cleaned_data['password1']) #sign_up.password2 = make_password(form.cleaned_data['password2']) sign_up.status = 1 sign_up.save() user = form.cleaned_data.get('matric_number') messages.success(request, "Account was created for "+str(user)) return redirect(signin) else: form = studentForm() return render(request, 'Student.html',{ "form": form }) This is the signin view def signin(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') try: student = student.object.get(username=username, password=password) return redirect(files) except: messages.success(request, "Error") else: form = LoginForm() return render(request, "SignIn.html",{ "form":form }) This is my form.py class studentForm(forms.ModelForm): class Meta: model=student fields="__all__" widgets={ 'first_name':forms.TextInput(attrs={'placeholder': 'Enter Your First Name'}), 'last_name':forms.TextInput(attrs={'placeholder': 'Enter Your Last Name'}), 'matric_number':forms.TextInput(attrs={'placeholder': 'Enter Your Matric Number'}), 'email':forms.EmailInput(attrs={'placeholder': '[email protected]'}), 'password1':forms.PasswordInput(attrs={'placeholder': 'Enter Your Preferred Password','id':'password'}), 'password2':forms.PasswordInput(attrs={'placeholder':'Confirm Your Password', 'id':'password1'}) } def clean(self): super(studentForm, self).clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') matric_number = self.cleaned_data.get('matric_number') email = self.cleaned_data.get('email') try: if password1 != password2: self.errors[''] = self.error_class(["The two password fields must match"]) elif len(matric_number) != 9: self.errors[''] = self.error_class(["You have entered an invalid matric number"]) elif len(matric_number) == 9: matric_number = int(matric_number) except ValueError: self.errors[''] = self.error_class(["You have entered an invalid matric number"]) for instance in student.objects.all(): if instance.matric_number == str(matric_number): self.errors[''] = self.error_class(["Matric number already exist"]) elif instance.email == email: self.errors[''] = self.error_class(["E-mail address already exist"]) class LoginForm(forms.Form): matric_number = forms.CharField(max_length=9, widget=forms.TextInput(attrs={'id': 'username', 'placeholder': 'Enter Your Staff Id Or Matric Number'})) password1 = forms.CharField(max_length=9, widget=forms.PasswordInput(attrs={'id': 'password', 'placeholder':'Enter Your password'}))
[ "Stop reinventing the wheel. Also, class names are supposed to be named with PascalCase.\nUse AbstractUser model:\nfrom django.contrib.auth.models import AbstractUser\n\nclass Student(AbstractUser):\n ...\n\nand in your main urls.py:\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n ...\n path('login/', auth_views.LoginView.as_view(), name='login'),\n ...\n]\n\nIt is much faster and SAFER way to create new user.\n", "So I figured out out how to solve my problem. By using the AbstractUser model,i was able to create a custom user and then create another model which i extended a ForeignKey on the User model therefore allowing me to tie every user to their profile.\nHere is my models.py\nfrom django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\n\n# Create your models here.\nclass User(AbstractUser):\n pass\n def __str__(self):\n return self.username\n\nclass UserProfile(models.Model):\n \"\"\"\n This is the one for model.py\n \"\"\"\n username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=\"\")\n profile_picture = models.ImageField(blank=True, null=True, default=\"\")\n matricno = models.CharField(max_length=9, default=\"\", primary_key=True)\n email = models.EmailField(default=\"\")\n first_name = models.CharField(max_length=200, default=\"\")\n last_name = models.CharField(max_length=255, default=\"\")\n\n class Meta:\n verbose_name_plural = \"Users Profile\"\n\n def __str__(self):\n return self.first_name+ \" \"+self.last_name\n\nAnd here is my views.py\ndef signup(request):\n if request.method == \"POST\":\n form = Signup(request.POST)\n if form.is_valid():\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n password = request.POST[\"password\"]\n password2 = request.POST[\"password2\"]\n\n user = User.objects.create_user(\n username=username,\n password=password,\n email=email,\n )\n user.save()\n login(request, user)\n messages.success(request, \"Account Created successfully for \" + username)\n return redirect(details)\n else:\n form = Signup()\n return render(request, \"accounts/register.html\", {\"form\": form})\n\ndef details(request, username):\n user = User.objects.get(username=username)\n form = Details()\n if request.method == \"POST\":\n form = Details(request.POST, request.FILES)\n if form.is_valid():\n detail = form.save(commit=False)\n detail.username = request.user\n detail.save()\n return redirect(success, pk=detail.pk)\n else:\n form = Details(initial={\"matricno\":request.user.username})\n return render(request, \"details.html\", {\"form\":form})\n\nAnd finally my forms.py that i use in creating a signup form and perfoming validation\nclass Signup(forms.Form):\n username = forms.CharField(\n max_length=9,\n widget=forms.TextInput(attrs={\"placeholder\": \"Enter Your Matric Number\"}),\n )\n\n email = forms.EmailField(\n max_length=255,\n widget=forms.EmailInput(attrs={\"placeholder\": \"Enter Your E-mail Address\"}),\n )\n\n password = forms.CharField(\n max_length=255,\n widget=forms.PasswordInput(\n attrs={\"placeholder\": \"Enter Your Password\", \"id\": \"password\"}\n ),\n )\n\n password2 = forms.CharField(\n max_length=255,\n widget=forms.PasswordInput(\n attrs={\"placeholder\": \"Confirm Your Password\", \"id\": \"password2\"}\n ),\n )\n \n def clean(self):\n super(Signup, self).clean()\n password = self.cleaned_data.get(\"password\")\n password2 = self.cleaned_data.get(\"password2\")\n username = self.cleaned_data.get(\"username\")\n email = self.cleaned_data.get(\"email\")\n\n if password != password2:\n self.errors[\"\"] = self.error_class([\"The two password fields must match\"])\n\n for instance in User.objects.all():\n if instance.username == str(username):\n self.errors[\"\"] = self.error_class([\"User already exist\"])\n elif instance.email == email:\n self.errors[\"\"] = self.error_class([\"E-mail already in use\"])\n else:\n pass\n\n return self.cleaned_data\n\n" ]
[ 0, 0 ]
[]
[]
[ "authentication", "django", "django_forms", "django_models", "python" ]
stackoverflow_0073978305_authentication_django_django_forms_django_models_python.txt
Q: CUDA_HOME environment variable is not set I have a working environment for using pytorch deep learning with gpu, and i ran into a problem when i tried using mmcv.ops.point_sample, which returned : ModuleNotFoundError: No module named 'mmcv._ext' I have read that you should actually use mmcv-full to solve it, but i got another error when i tried to install it: pip install mmcv-full OSError: CUDA_HOME environment variable is not set. Please set it to your CUDA install root. Which seems logic enough since i never installed cuda on my ubuntu machine(i am not the administrator), but it still ran deep learning training fine on models i built myself, and i'm guessing the package came in with minimal code required for running cuda tensors operations. So my main question is where is cuda installed when used through pytorch package, and can i use the same path as the environment variable for cuda_home? Additionaly if anyone knows some nice sources for gaining insights on the internals of cuda with pytorch/tensorflow I'd like to take a look (I have been reading cudatoolkit documentation which is cool but this seems more targeted at c++ cuda developpers than the internal working between python and the library) A: you can chek it and check the paths with these commands : which nvidia-smi which nvcc cat /usr/local/cuda/version.txt
CUDA_HOME environment variable is not set
I have a working environment for using pytorch deep learning with gpu, and i ran into a problem when i tried using mmcv.ops.point_sample, which returned : ModuleNotFoundError: No module named 'mmcv._ext' I have read that you should actually use mmcv-full to solve it, but i got another error when i tried to install it: pip install mmcv-full OSError: CUDA_HOME environment variable is not set. Please set it to your CUDA install root. Which seems logic enough since i never installed cuda on my ubuntu machine(i am not the administrator), but it still ran deep learning training fine on models i built myself, and i'm guessing the package came in with minimal code required for running cuda tensors operations. So my main question is where is cuda installed when used through pytorch package, and can i use the same path as the environment variable for cuda_home? Additionaly if anyone knows some nice sources for gaining insights on the internals of cuda with pytorch/tensorflow I'd like to take a look (I have been reading cudatoolkit documentation which is cool but this seems more targeted at c++ cuda developpers than the internal working between python and the library)
[ "you can chek it and check the paths with these commands :\n\nwhich nvidia-smi\nwhich nvcc\ncat /usr/local/cuda/version.txt\n\n" ]
[ 0 ]
[]
[]
[ "python", "pytorch" ]
stackoverflow_0074656874_python_pytorch.txt
Q: How do I make this VBA-code function properly in my Excelfile? I was trying to make the current date in the file (Sheet 1, cell I3) update every 10 seconds, but after trying multiple things, it just won't work. My plan was to make the time in the cell update every 10 seconds, instead of having to edit the file to update the time. I am not familiar with VBA, could anyone explain what I'm doing wrong? Code: Sub Calculate_Range() Worksheets("Display").Range(I3).Calculate Application.OnTime DateAdd("s", 10, Now), "Calculate_Range" End Sub A: You can play around with this. Dim TimeRQ As Date Sub RQ() With Sheet1.Range("I3") .Value = Format(Time, "hh:mm:ss AM/PM") End With Call DeffTime End Sub Sub DeffTime() TimeRQ = Now + TimeValue("00:00:01") Application.OnTime TimeRQ, "RQ" End Sub Sub Disable() On Error Resume Next Application.OnTime EarliestTime:=TimeRQ, Procedure:="RQ", Schedule:=False End Sub
How do I make this VBA-code function properly in my Excelfile?
I was trying to make the current date in the file (Sheet 1, cell I3) update every 10 seconds, but after trying multiple things, it just won't work. My plan was to make the time in the cell update every 10 seconds, instead of having to edit the file to update the time. I am not familiar with VBA, could anyone explain what I'm doing wrong? Code: Sub Calculate_Range() Worksheets("Display").Range(I3).Calculate Application.OnTime DateAdd("s", 10, Now), "Calculate_Range" End Sub
[ "You can play around with this.\nDim TimeRQ As Date\nSub RQ()\nWith Sheet1.Range(\"I3\")\n.Value = Format(Time, \"hh:mm:ss AM/PM\")\nEnd With\nCall DeffTime\nEnd Sub\nSub DeffTime()\nTimeRQ = Now + TimeValue(\"00:00:01\")\nApplication.OnTime TimeRQ, \"RQ\"\nEnd Sub\nSub Disable()\nOn Error Resume Next\nApplication.OnTime EarliestTime:=TimeRQ, Procedure:=\"RQ\", Schedule:=False\nEnd Sub\n\n" ]
[ 1 ]
[]
[]
[ "excel", "vba" ]
stackoverflow_0074655671_excel_vba.txt
Q: Use a value from a line before in SQL? I have a query with a few columns of a table and now I want a new column that offsets the value of two columns with the value of the row above. The first line is the base value for the calculation. ID date val1 val2 1 2022-01-11 12000 NULL 2 2022-02-11 500 NULL 3 2022-02-11 NULL 200 4 2022-03-11 NULL 400 So in this example 12000 is the first line therefore the base value. The second line should take the base value (from the line above) and add the 500. So the result is 12500 in this line. The third line should take the result from above 12500 and subtract the 200 from v2. So the result in this line is 12300. And so on.. The formula is therefore: result (from line above) + v1 - v2 What I expect is this: ID date val1 val2 result 1 2022-01-11 12000 NULL 12000 2 2022-02-11 500 NULL 12500 3 2022-02-11 NULL 200 12300 4 2022-03-11 NULL 400 11900 The query so far is: SELECT ID, date, val1, val2 FROM Table ORDER BY ID How can I get the result column to this select-query? Could anyone help me please? I didn't really try anything because I absolutely don't know how to get a value from a line above. A: You can use the SUM() function to do a running total over the entire query results. Here I'm using the SUM() and specifying val1 - val2 inside the function. Reference learning material: https://codingsight.com/calculating-running-total-with-over-clause-and-partition-by-clause-in-sql-server/ CREATE TABLE dataTable ( ID int not null , [date] datetime not null , val1 int null , val2 int null ); INSERT INTO dataTable (ID, [date], val1, val2) VALUES (1, '2022-01-11', 12000, null) , (2, '2022-02-11', 500, null) , (3, '2022-02-11', null, 200) , (4, '2022-03-11', null, 400) ; SELECT ID, date, val1, val2 , SUM (ISNULL(val1,0) - ISNULL(val2,0)) OVER (ORDER BY ID) AS result FROM dataTable ORDER BY ID ID date val1 val2 result 1 2022-01-11 00:00:00.000 12000 null 12000 2 2022-02-11 00:00:00.000 500 null 12500 3 2022-02-11 00:00:00.000 null 200 12300 4 2022-03-11 00:00:00.000 null 400 11900 fiddle
Use a value from a line before in SQL?
I have a query with a few columns of a table and now I want a new column that offsets the value of two columns with the value of the row above. The first line is the base value for the calculation. ID date val1 val2 1 2022-01-11 12000 NULL 2 2022-02-11 500 NULL 3 2022-02-11 NULL 200 4 2022-03-11 NULL 400 So in this example 12000 is the first line therefore the base value. The second line should take the base value (from the line above) and add the 500. So the result is 12500 in this line. The third line should take the result from above 12500 and subtract the 200 from v2. So the result in this line is 12300. And so on.. The formula is therefore: result (from line above) + v1 - v2 What I expect is this: ID date val1 val2 result 1 2022-01-11 12000 NULL 12000 2 2022-02-11 500 NULL 12500 3 2022-02-11 NULL 200 12300 4 2022-03-11 NULL 400 11900 The query so far is: SELECT ID, date, val1, val2 FROM Table ORDER BY ID How can I get the result column to this select-query? Could anyone help me please? I didn't really try anything because I absolutely don't know how to get a value from a line above.
[ "You can use the SUM() function to do a running total over the entire query results. Here I'm using the SUM() and specifying val1 - val2 inside the function. Reference learning material: https://codingsight.com/calculating-running-total-with-over-clause-and-partition-by-clause-in-sql-server/\nCREATE TABLE dataTable (\n ID int not null\n , [date] datetime not null\n , val1 int null\n , val2 int null\n);\n\nINSERT INTO dataTable (ID, [date], val1, val2)\nVALUES (1, '2022-01-11', 12000, null)\n , (2, '2022-02-11', 500, null)\n , (3, '2022-02-11', null, 200)\n , (4, '2022-03-11', null, 400)\n;\n\nSELECT ID, date, val1, val2\n , SUM (ISNULL(val1,0) - ISNULL(val2,0)) OVER (ORDER BY ID) AS result\nFROM dataTable\nORDER BY ID\n\n\n\n\n\n\nID\ndate\nval1\nval2\nresult\n\n\n\n\n1\n2022-01-11 00:00:00.000\n12000\nnull\n12000\n\n\n2\n2022-02-11 00:00:00.000\n500\nnull\n12500\n\n\n3\n2022-02-11 00:00:00.000\nnull\n200\n12300\n\n\n4\n2022-03-11 00:00:00.000\nnull\n400\n11900\n\n\n\n\nfiddle\n" ]
[ 1 ]
[]
[]
[ "select", "sql", "sql_server" ]
stackoverflow_0074656865_select_sql_sql_server.txt
Q: How to make a loop that changes values in specific rows from a dictionary I'm new and can't figure it out how to solve this problem. I have a data.frame = schedule Week_number Start End 1 09:00 15:00 1 09:00 15:00 1 09:00 15:00 1 09:00 15:00 1 09:00 15:00 1 NA NA 1 NA NA 2 09:00 15:00 2 09:00 15:00 2 09:00 15:00 2 09:00 15:00 2 09:00 15:00 2 NA NA 2 NA NA 3 09:00 15:00 3 09:00 15:00 3 09:00 15:00 3 09:00 15:00 3 09:00 15:00 3 NA NA 3 NA NA ----------------------------- .. 52 ----------------------------- I have a shift dictionary : > start_vec <- c("06:00", "08:00", "14:00") > end_vec <- c("14:00", "16:00", "22:00") My loop is to go through all 52 weeks and replace 9am and 3pm with a dictionary value. But the problem is that the values should not be repeated, i.e. each week should be different. For example, I start the year with : 08:00 - 16:00. The year can start with any shift. Please find an example below : Week_number Start End 1 08:00 16:00 1 08:00 16:00 1 08:00 16:00 1 08:00 16:00 1 08:00 16:00 1 NA NA 1 NA NA 2 14:00 22:00 2 14:00 22:00 2 14:00 22:00 2 14:00 22:00 2 14:00 22:00 2 NA NA 2 NA NA 3 06:00 14:00 3 06:00 14:00 3 06:00 14:00 3 06:00 14:00 3 06:00 14:00 3 NA NA 3 NA NA ----------------------------- .. 52 ----------------------------- I tryed to make nest loop, or make week_number vector to be able replace all 1 without NA with specific value. > rd_dt <- data.frame() > for (i in 1:length(schedule$Week_number)){ > for (s in start_vec){ > for (e in end_vec){ > dt <- schedule[i,] > if (schedule$Start == NA){ > next > else { Thanks in advance for any hint. A: I think you do not need a loop to do this. Here is one approach that may be helpful. Using ifelse check for NA - if not NA, then refer to start_vec and end_vec for substitute values. It will use the Week_number as an index in your vector, and uses the %% modulus operator where 3 is the length of your vectors, so it will restart at beginning if exceeds the length of the vectors. library(dplyr) df %>% mutate(Start = ifelse(is.na(Start), NA, start_vec[1 + Week_number %% 3]), End = ifelse(is.na(End), NA, end_vec[1 + Week_number %% 3])) Output Week_number Start End 1 1 08:00 16:00 2 1 08:00 16:00 3 1 08:00 16:00 4 1 08:00 16:00 5 1 08:00 16:00 6 1 <NA> <NA> 7 1 <NA> <NA> 8 2 14:00 22:00 9 2 14:00 22:00 10 2 14:00 22:00 11 2 14:00 22:00 12 2 14:00 22:00 13 2 <NA> <NA> 14 2 <NA> <NA> 15 3 06:00 14:00 16 3 06:00 14:00 17 3 06:00 14:00 18 3 06:00 14:00 19 3 06:00 14:00 20 3 <NA> <NA> 21 3 <NA> <NA>
How to make a loop that changes values in specific rows from a dictionary
I'm new and can't figure it out how to solve this problem. I have a data.frame = schedule Week_number Start End 1 09:00 15:00 1 09:00 15:00 1 09:00 15:00 1 09:00 15:00 1 09:00 15:00 1 NA NA 1 NA NA 2 09:00 15:00 2 09:00 15:00 2 09:00 15:00 2 09:00 15:00 2 09:00 15:00 2 NA NA 2 NA NA 3 09:00 15:00 3 09:00 15:00 3 09:00 15:00 3 09:00 15:00 3 09:00 15:00 3 NA NA 3 NA NA ----------------------------- .. 52 ----------------------------- I have a shift dictionary : > start_vec <- c("06:00", "08:00", "14:00") > end_vec <- c("14:00", "16:00", "22:00") My loop is to go through all 52 weeks and replace 9am and 3pm with a dictionary value. But the problem is that the values should not be repeated, i.e. each week should be different. For example, I start the year with : 08:00 - 16:00. The year can start with any shift. Please find an example below : Week_number Start End 1 08:00 16:00 1 08:00 16:00 1 08:00 16:00 1 08:00 16:00 1 08:00 16:00 1 NA NA 1 NA NA 2 14:00 22:00 2 14:00 22:00 2 14:00 22:00 2 14:00 22:00 2 14:00 22:00 2 NA NA 2 NA NA 3 06:00 14:00 3 06:00 14:00 3 06:00 14:00 3 06:00 14:00 3 06:00 14:00 3 NA NA 3 NA NA ----------------------------- .. 52 ----------------------------- I tryed to make nest loop, or make week_number vector to be able replace all 1 without NA with specific value. > rd_dt <- data.frame() > for (i in 1:length(schedule$Week_number)){ > for (s in start_vec){ > for (e in end_vec){ > dt <- schedule[i,] > if (schedule$Start == NA){ > next > else { Thanks in advance for any hint.
[ "I think you do not need a loop to do this. Here is one approach that may be helpful. Using ifelse check for NA - if not NA, then refer to start_vec and end_vec for substitute values. It will use the Week_number as an index in your vector, and uses the %% modulus operator where 3 is the length of your vectors, so it will restart at beginning if exceeds the length of the vectors.\nlibrary(dplyr)\n\ndf %>%\n mutate(Start = ifelse(is.na(Start), NA, start_vec[1 + Week_number %% 3]),\n End = ifelse(is.na(End), NA, end_vec[1 + Week_number %% 3]))\n\nOutput\n Week_number Start End\n1 1 08:00 16:00\n2 1 08:00 16:00\n3 1 08:00 16:00\n4 1 08:00 16:00\n5 1 08:00 16:00\n6 1 <NA> <NA>\n7 1 <NA> <NA>\n8 2 14:00 22:00\n9 2 14:00 22:00\n10 2 14:00 22:00\n11 2 14:00 22:00\n12 2 14:00 22:00\n13 2 <NA> <NA>\n14 2 <NA> <NA>\n15 3 06:00 14:00\n16 3 06:00 14:00\n17 3 06:00 14:00\n18 3 06:00 14:00\n19 3 06:00 14:00\n20 3 <NA> <NA>\n21 3 <NA> <NA>\n\n" ]
[ 0 ]
[]
[]
[ "data_manipulation", "dplyr", "nested_loops", "r", "stringr" ]
stackoverflow_0074648843_data_manipulation_dplyr_nested_loops_r_stringr.txt
Q: Python JSON serialize a Decimal object I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'x': 3.8999999999999999} which is wrong, and will be a big waste of bandwidth. A: Simplejson 2.1 and higher has native support for Decimal type: >>> json.dumps(Decimal('3.9'), use_decimal=True) '3.9' Note that use_decimal is True by default: def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, for_json=False, ignore_nan=False, **kw): So: >>> json.dumps(Decimal('3.9')) '3.9' Hopefully, this feature will be included in standard library. A: I would like to let everyone know that I tried Michał Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with: import decimal class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return str(o) return super(DecimalEncoder, self).default(o) Note that this will convert the decimal to its string representation (e.g.; "1.2300") to a. not lose significant digits and b. prevent rounding errors. This should hopefully help anyone who is having problems with Python 2.7. I tested it and it seems to work fine. If anyone notices any bugs in my solution or comes up with a better way, please let me know. Usage example: json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder) A: How about subclassing json.JSONEncoder? class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): # wanted a simple yield str(o) in the next line, # but that would mean a yield on the line with super(...), # which wouldn't work (see my comment below), so... return (str(o) for o in [o]) return super(DecimalEncoder, self).default(o) Then use it like so: json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder) A: The native Django option is missing so I'll add it for the next guy/gall that looks for it. Starting on Django 1.7.x there is a built-in DjangoJSONEncoder that you can get it from django.core.serializers.json. import json from django.core.serializers.json import DjangoJSONEncoder from django.forms.models import model_to_dict model_instance = YourModel.object.first() model_dict = model_to_dict(model_instance) json.dumps(model_dict, cls=DjangoJSONEncoder) Presto! A: In my Flask app, Which uses python 2.7.11, flask alchemy(with 'db.decimal' types), and Flask Marshmallow ( for 'instant' serializer and deserializer), i had this error, every time i did a GET or POST. The serializer and deserializer, failed to convert Decimal types into any JSON identifiable format. I did a "pip install simplejson", then Just by adding import simplejson as json the serializer and deserializer starts to purr again. I did nothing else... DEciamls are displayed as '234.00' float format. A: I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because _iterencode calls _iterencode on the results of default), and float(o) would remove trailing 0. If default returns an object of a class that inherits from float (or anything that calls repr without additional formatting) and has a custom __repr__ method, it seems to work like I want it to. import json from decimal import Decimal class fakefloat(float): def __init__(self, value): self._value = value def __repr__(self): return str(self._value) def defaultencode(o): if isinstance(o, Decimal): # Subclass float with custom repr? return fakefloat(o) raise TypeError(repr(o) + " is not JSON serializable") json.dumps([10.20, "10.20", Decimal('10.20')], default=defaultencode) '[10.2, "10.20", 10.20]' A: For Django users: Recently came across TypeError: Decimal('2337.00') is not JSON serializable while JSON encoding i.e. json.dumps(data) Solution: # converts Decimal, Datetime, UUIDs to str for Encoding from django.core.serializers.json import DjangoJSONEncoder json.dumps(response.data, cls=DjangoJSONEncoder) But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads: import decimal data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str) A: 3.9 can not be exactly represented in IEEE floats, it will always come as 3.8999999999999999, e.g. try print repr(3.9), you can read more about it here: http://en.wikipedia.org/wiki/Floating_point http://docs.sun.com/source/806-3568/ncg_goldberg.html So if you don't want float, only option you have to send it as string, and to allow automatic conversion of decimal objects to JSON, do something like this: import decimal from django.utils import simplejson def json_encode_decimal(obj): if isinstance(obj, decimal.Decimal): return str(obj) raise TypeError(repr(obj) + " is not JSON serializable") d = decimal.Decimal('3.5') print simplejson.dumps([d], default=json_encode_decimal) A: My $.02! I extend a bunch of the JSON encoder since I am serializing tons of data for my web server. Here's some nice code. Note that it's easily extendable to pretty much any data format you feel like and will reproduce 3.9 as "thing": 3.9 JSONEncoder_olddefault = json.JSONEncoder.default def JSONEncoder_newdefault(self, o): if isinstance(o, UUID): return str(o) if isinstance(o, datetime): return str(o) if isinstance(o, time.struct_time): return datetime.fromtimestamp(time.mktime(o)) if isinstance(o, decimal.Decimal): return str(o) return JSONEncoder_olddefault(self, o) json.JSONEncoder.default = JSONEncoder_newdefault Makes my life so much easier... A: For those who don't want to use a third-party library... An issue with Elias Zamaria's answer is that it converts to float, which can run into problems. For example: >>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder) '{"x": 1e-07}' >>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder) '{"x": 100000000000.01733}' The JSONEncoder.encode() method lets you return the literal json content, unlike JSONEncoder.default(), which has you return a json compatible type (like float) that then gets encoded in the normal way. The problem with encode() is that it (normally) only works at the top level. But it's still usable, with a little extra work (python 3.x): import json from collections.abc import Mapping, Iterable from decimal import Decimal class DecimalEncoder(json.JSONEncoder): def encode(self, obj): if isinstance(obj, Mapping): return '{' + ', '.join(f'{self.encode(k)}: {self.encode(v)}' for (k, v) in obj.items()) + '}' if isinstance(obj, Iterable) and (not isinstance(obj, str)): return '[' + ', '.join(map(self.encode, obj)) + ']' if isinstance(obj, Decimal): return f'{obj.normalize():f}' # using normalize() gets rid of trailing 0s, using ':f' prevents scientific notation return super().encode(obj) Which gives you: >>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder) '{"x": 0.0000001}' >>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder) '{"x": 100000000000.01734}' A: From the JSON Standard Document, as linked in json.org: JSON is agnostic about the semantics of numbers. In any programming language, there can be a variety of number types of various capacities and complements, fixed or floating, binary or decimal. That can make interchange between different programming languages difficult. JSON instead offers only the representation of numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit sequences even if they disagree on internal representations. That is enough to allow interchange. So it's actually accurate to represent Decimals as numbers (rather than strings) in JSON. Bellow lies a possible solution to the problem. Define a custom JSON encoder: import json class CustomJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return float(obj) return super(CustomJsonEncoder, self).default(obj) Then use it when serializing your data: json.dumps(data, cls=CustomJsonEncoder) As noted from comments on the other answers, older versions of python might mess up the representation when converting to float, but that's not the case anymore. To get the decimal back in Python: Decimal(str(value)) This solution is hinted in Python 3.0 documentation on decimals: To create a Decimal from a float, first convert it to a string. A: This is what I have, extracted from our class class CommonJSONEncoder(json.JSONEncoder): """ Common JSON Encoder json.dumps(myString, cls=CommonJSONEncoder) """ def default(self, obj): if isinstance(obj, decimal.Decimal): return {'type{decimal}': str(obj)} class CommonJSONDecoder(json.JSONDecoder): """ Common JSON Encoder json.loads(myString, cls=CommonJSONEncoder) """ @classmethod def object_hook(cls, obj): for key in obj: if isinstance(key, six.string_types): if 'type{decimal}' == key: try: return decimal.Decimal(obj[key]) except: pass def __init__(self, **kwargs): kwargs['object_hook'] = self.object_hook super(CommonJSONDecoder, self).__init__(**kwargs) Which passes unittest: def test_encode_and_decode_decimal(self): obj = Decimal('1.11') result = json.dumps(obj, cls=CommonJSONEncoder) self.assertTrue('type{decimal}' in result) new_obj = json.loads(result, cls=CommonJSONDecoder) self.assertEqual(new_obj, obj) obj = {'test': Decimal('1.11')} result = json.dumps(obj, cls=CommonJSONEncoder) self.assertTrue('type{decimal}' in result) new_obj = json.loads(result, cls=CommonJSONDecoder) self.assertEqual(new_obj, obj) obj = {'test': {'abc': Decimal('1.11')}} result = json.dumps(obj, cls=CommonJSONEncoder) self.assertTrue('type{decimal}' in result) new_obj = json.loads(result, cls=CommonJSONDecoder) self.assertEqual(new_obj, obj) A: You can create a custom JSON encoder as per your requirement. import json from datetime import datetime, date from time import time, struct_time, mktime import decimal class CustomJSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, datetime): return str(o) if isinstance(o, date): return str(o) if isinstance(o, decimal.Decimal): return float(o) if isinstance(o, struct_time): return datetime.fromtimestamp(mktime(o)) # Any other serializer if needed return super(CustomJSONEncoder, self).default(o) The Decoder can be called like this, import json from decimal import Decimal json.dumps({'x': Decimal('3.9')}, cls=CustomJSONEncoder) and the output will be: >>'{"x": 3.9}' A: Based on stdOrgnlDave answer I have defined this wrapper that it can be called with optional kinds so the encoder will work only for certain kinds inside your projects. I believe the work should be done inside your code and not to use this "default" encoder since "it is better explicit than implicit", but I understand using this will save some of your time. :-) import time import json import decimal from uuid import UUID from datetime import datetime def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']): ''' JSON Encoder newdfeault is a wrapper capable of encoding several kinds Use it anywhere on your code to make the full system to work with this defaults: JSONEncoder_newdefault() # for everything JSONEncoder_newdefault(['decimal']) # only for Decimal ''' JSONEncoder_olddefault = json.JSONEncoder.default def JSONEncoder_wrapped(self, o): ''' json.JSONEncoder.default = JSONEncoder_newdefault ''' if ('uuid' in kind) and isinstance(o, uuid.UUID): return str(o) if ('datetime' in kind) and isinstance(o, datetime): return str(o) if ('time' in kind) and isinstance(o, time.struct_time): return datetime.fromtimestamp(time.mktime(o)) if ('decimal' in kind) and isinstance(o, decimal.Decimal): return str(o) return JSONEncoder_olddefault(self, o) json.JSONEncoder.default = JSONEncoder_wrapped # Example if __name__ == '__main__': JSONEncoder_newdefault() A: If someone is still looking for the answer, it is most probably you have a 'NaN' in your data that you are trying to encode. Because NaN is considered as float by Python. A: If you want to pass a dictionary containing decimals to the requests library (using the json keyword argument), you simply need to install simplejson: $ pip3 install simplejson $ python3 >>> import requests >>> from decimal import Decimal >>> # This won't error out: >>> requests.post('https://www.google.com', json={'foo': Decimal('1.23')}) The reason of the problem is that requests uses simplejson only if it is present, and falls back to the built-in json if it is not installed. A: For anybody that wants a quick solution here is how I removed Decimal from my queries in Django total_development_cost_var = process_assumption_objects.values('total_development_cost').aggregate(sum_dev = Sum('total_development_cost', output_field=FloatField())) total_development_cost_var = list(total_development_cost_var.values()) Step 1: use , output_field=FloatField() in you r query Step 2: use list eg list(total_development_cost_var.values()) Hope it helps A: This question is old, but there seems to be a better and much simpler solution in Python3 for most use-cases: number = Decimal(0.55) converted_number = float(number) # Returns: 0.55 (as type float) You can just convert Decimal to float. A: My 2 cents for easy solution, if you're sure Decimal is the only bad guy on your json dumps method: print(json.loads(json.dumps({ 'a': Decimal(1230), 'b': Decimal(11111111123.22), }, default=lambda x: eval(str(x))))) >>> {'a': 1230, 'b': 11111111123.22} The "smart" thing here is using default to convert Decimal to int or float, automatically, taking advantage of eval function: default=lambda x: eval(str(x)) But always be careful using eval on your code as it can lead to security issues ;) A: Decimal is not suitable to be converted through: float due to precision problems str due to openapi restrictions We still need direct decimal to a number json serialisation. Here is our extension of @tesdal 's fakefloat solution (closed in v3.5.2rc1). It uses fakestr + monkeypatching to avoid quotation and "floatation" of decimals. import json.encoder from decimal import Decimal def encode_fakestr(func): def wrap(s): if isinstance(s, fakestr): return repr(s) return func(s) return wrap json.encoder.encode_basestring = encode_fakestr(json.encoder.encode_basestring) json.encoder.encode_basestring_ascii = encode_fakestr(json.encoder.encode_basestring_ascii) class fakestr(str): def __init__(self, value): self._value = value def __repr__(self): return str(self._value) class DecimalJsonEncoder(json.encoder.JSONEncoder): def default(self, o): if isinstance(o, Decimal): return fakestr(o) return super().default(o) json.dumps([Decimal('1.1')], cls=DecimalJsonEncoder) [1.1] I don't understand why python developers force us using floats in places where it is not suitable. A: I will share what worked for me with flask 2.1.0 When I was creating the dictionary which had to be used from jsonify I used rounding: json_dict['price'] = round(self.price, ndigits=2) if self.price else 0 So this way I could return D.DD number or 0 without using some global configuration. And this is nice because some Decimals has to be bigger, like latitude and longitude coordinates. return jsonify(json_dict)
Python JSON serialize a Decimal object
I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine. Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'x': 3.8999999999999999} which is wrong, and will be a big waste of bandwidth.
[ "Simplejson 2.1 and higher has native support for Decimal type:\n>>> json.dumps(Decimal('3.9'), use_decimal=True)\n'3.9'\n\nNote that use_decimal is True by default:\ndef dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,\n allow_nan=True, cls=None, indent=None, separators=None,\n encoding='utf-8', default=None, use_decimal=True,\n namedtuple_as_object=True, tuple_as_array=True,\n bigint_as_string=False, sort_keys=False, item_sort_key=None,\n for_json=False, ignore_nan=False, **kw):\n\nSo:\n>>> json.dumps(Decimal('3.9'))\n'3.9'\n\nHopefully, this feature will be included in standard library.\n", "I would like to let everyone know that I tried Michał Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with:\nimport decimal\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n return str(o)\n return super(DecimalEncoder, self).default(o)\n\nNote that this will convert the decimal to its string representation (e.g.; \"1.2300\") to a. not lose significant digits and b. prevent rounding errors.\nThis should hopefully help anyone who is having problems with Python 2.7. I tested it and it seems to work fine. If anyone notices any bugs in my solution or comes up with a better way, please let me know.\nUsage example:\njson.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)\n\n", "How about subclassing json.JSONEncoder?\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n # wanted a simple yield str(o) in the next line,\n # but that would mean a yield on the line with super(...),\n # which wouldn't work (see my comment below), so...\n return (str(o) for o in [o])\n return super(DecimalEncoder, self).default(o)\n\nThen use it like so:\njson.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)\n\n", "The native Django option is missing so I'll add it for the next guy/gall that looks for it.\nStarting on Django 1.7.x there is a built-in DjangoJSONEncoder that you can get it from django.core.serializers.json.\nimport json\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.forms.models import model_to_dict\n\nmodel_instance = YourModel.object.first()\nmodel_dict = model_to_dict(model_instance)\n\njson.dumps(model_dict, cls=DjangoJSONEncoder)\n\nPresto!\n", "In my Flask app, Which uses python 2.7.11, flask alchemy(with 'db.decimal' types), and Flask Marshmallow ( for 'instant' serializer and deserializer), i had this error, every time i did a GET or POST. The serializer and deserializer, failed to convert Decimal types into any JSON identifiable format. \nI did a \"pip install simplejson\", then \nJust by adding\nimport simplejson as json\n\nthe serializer and deserializer starts to purr again. I did nothing else...\nDEciamls are displayed as '234.00' float format.\n", "I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because _iterencode calls _iterencode on the results of default), and float(o) would remove trailing 0.\nIf default returns an object of a class that inherits from float (or anything that calls repr without additional formatting) and has a custom __repr__ method, it seems to work like I want it to.\nimport json\nfrom decimal import Decimal\n\nclass fakefloat(float):\n def __init__(self, value):\n self._value = value\n def __repr__(self):\n return str(self._value)\n\ndef defaultencode(o):\n if isinstance(o, Decimal):\n # Subclass float with custom repr?\n return fakefloat(o)\n raise TypeError(repr(o) + \" is not JSON serializable\")\n\njson.dumps([10.20, \"10.20\", Decimal('10.20')], default=defaultencode)\n'[10.2, \"10.20\", 10.20]'\n\n", "For Django users:\nRecently came across TypeError: Decimal('2337.00') is not JSON serializable\nwhile JSON encoding i.e. json.dumps(data)\nSolution:\n# converts Decimal, Datetime, UUIDs to str for Encoding\nfrom django.core.serializers.json import DjangoJSONEncoder \n\njson.dumps(response.data, cls=DjangoJSONEncoder)\n\nBut, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads:\nimport decimal \n\ndata = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)\n\n", "3.9 can not be exactly represented in IEEE floats, it will always come as 3.8999999999999999, e.g. try print repr(3.9), you can read more about it here: \nhttp://en.wikipedia.org/wiki/Floating_point\nhttp://docs.sun.com/source/806-3568/ncg_goldberg.html \nSo if you don't want float, only option you have to send it as string, and to allow automatic conversion of decimal objects to JSON, do something like this:\nimport decimal\nfrom django.utils import simplejson\n\ndef json_encode_decimal(obj):\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n raise TypeError(repr(obj) + \" is not JSON serializable\")\n\nd = decimal.Decimal('3.5')\nprint simplejson.dumps([d], default=json_encode_decimal)\n\n", "My $.02!\nI extend a bunch of the JSON encoder since I am serializing tons of data for my web server. Here's some nice code. Note that it's easily extendable to pretty much any data format you feel like and will reproduce 3.9 as \"thing\": 3.9\nJSONEncoder_olddefault = json.JSONEncoder.default\ndef JSONEncoder_newdefault(self, o):\n if isinstance(o, UUID): return str(o)\n if isinstance(o, datetime): return str(o)\n if isinstance(o, time.struct_time): return datetime.fromtimestamp(time.mktime(o))\n if isinstance(o, decimal.Decimal): return str(o)\n return JSONEncoder_olddefault(self, o)\njson.JSONEncoder.default = JSONEncoder_newdefault\n\nMakes my life so much easier...\n", "For those who don't want to use a third-party library... An issue with Elias Zamaria's answer is that it converts to float, which can run into problems. For example:\n>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)\n'{\"x\": 1e-07}'\n>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)\n'{\"x\": 100000000000.01733}'\n\nThe JSONEncoder.encode() method lets you return the literal json content, unlike JSONEncoder.default(), which has you return a json compatible type (like float) that then gets encoded in the normal way. The problem with encode() is that it (normally) only works at the top level. But it's still usable, with a little extra work (python 3.x):\nimport json\nfrom collections.abc import Mapping, Iterable\nfrom decimal import Decimal\n\nclass DecimalEncoder(json.JSONEncoder):\n def encode(self, obj):\n if isinstance(obj, Mapping):\n return '{' + ', '.join(f'{self.encode(k)}: {self.encode(v)}' for (k, v) in obj.items()) + '}'\n if isinstance(obj, Iterable) and (not isinstance(obj, str)):\n return '[' + ', '.join(map(self.encode, obj)) + ']'\n if isinstance(obj, Decimal):\n return f'{obj.normalize():f}' # using normalize() gets rid of trailing 0s, using ':f' prevents scientific notation\n return super().encode(obj)\n\nWhich gives you:\n>>> json.dumps({'x': Decimal('0.0000001')}, cls=DecimalEncoder)\n'{\"x\": 0.0000001}'\n>>> json.dumps({'x': Decimal('100000000000.01734')}, cls=DecimalEncoder)\n'{\"x\": 100000000000.01734}'\n\n", "From the JSON Standard Document, as linked in json.org:\n\nJSON is agnostic about the semantics of numbers. In any programming language, there can be a variety of\n number types of various capacities and complements, fixed or floating, binary or decimal. That can make\n interchange between different programming languages difficult. JSON instead offers only the representation of\n numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit\n sequences even if they disagree on internal representations. That is enough to allow interchange.\n\nSo it's actually accurate to represent Decimals as numbers (rather than strings) in JSON. Bellow lies a possible solution to the problem.\nDefine a custom JSON encoder:\nimport json\n\n\nclass CustomJsonEncoder(json.JSONEncoder):\n\n def default(self, obj):\n if isinstance(obj, Decimal):\n return float(obj)\n return super(CustomJsonEncoder, self).default(obj)\n\nThen use it when serializing your data:\njson.dumps(data, cls=CustomJsonEncoder)\n\nAs noted from comments on the other answers, older versions of python might mess up the representation when converting to float, but that's not the case anymore.\nTo get the decimal back in Python:\nDecimal(str(value))\n\nThis solution is hinted in Python 3.0 documentation on decimals:\n\nTo create a Decimal from a float, first convert it to a string.\n\n", "This is what I have, extracted from our class\nclass CommonJSONEncoder(json.JSONEncoder):\n\n \"\"\"\n Common JSON Encoder\n json.dumps(myString, cls=CommonJSONEncoder)\n \"\"\"\n\n def default(self, obj):\n\n if isinstance(obj, decimal.Decimal):\n return {'type{decimal}': str(obj)}\n\nclass CommonJSONDecoder(json.JSONDecoder):\n\n \"\"\"\n Common JSON Encoder\n json.loads(myString, cls=CommonJSONEncoder)\n \"\"\"\n\n @classmethod\n def object_hook(cls, obj):\n for key in obj:\n if isinstance(key, six.string_types):\n if 'type{decimal}' == key:\n try:\n return decimal.Decimal(obj[key])\n except:\n pass\n\n def __init__(self, **kwargs):\n kwargs['object_hook'] = self.object_hook\n super(CommonJSONDecoder, self).__init__(**kwargs)\n\nWhich passes unittest:\ndef test_encode_and_decode_decimal(self):\n obj = Decimal('1.11')\n result = json.dumps(obj, cls=CommonJSONEncoder)\n self.assertTrue('type{decimal}' in result)\n new_obj = json.loads(result, cls=CommonJSONDecoder)\n self.assertEqual(new_obj, obj)\n\n obj = {'test': Decimal('1.11')}\n result = json.dumps(obj, cls=CommonJSONEncoder)\n self.assertTrue('type{decimal}' in result)\n new_obj = json.loads(result, cls=CommonJSONDecoder)\n self.assertEqual(new_obj, obj)\n\n obj = {'test': {'abc': Decimal('1.11')}}\n result = json.dumps(obj, cls=CommonJSONEncoder)\n self.assertTrue('type{decimal}' in result)\n new_obj = json.loads(result, cls=CommonJSONDecoder)\n self.assertEqual(new_obj, obj)\n\n", "You can create a custom JSON encoder as per your requirement.\nimport json\nfrom datetime import datetime, date\nfrom time import time, struct_time, mktime\nimport decimal\n\nclass CustomJSONEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, datetime):\n return str(o)\n if isinstance(o, date):\n return str(o)\n if isinstance(o, decimal.Decimal):\n return float(o)\n if isinstance(o, struct_time):\n return datetime.fromtimestamp(mktime(o))\n # Any other serializer if needed\n return super(CustomJSONEncoder, self).default(o)\n\nThe Decoder can be called like this,\nimport json\nfrom decimal import Decimal\njson.dumps({'x': Decimal('3.9')}, cls=CustomJSONEncoder)\n\nand the output will be:\n>>'{\"x\": 3.9}'\n\n", "Based on stdOrgnlDave answer I have defined this wrapper that it can be called with optional kinds so the encoder will work only for certain kinds inside your projects. I believe the work should be done inside your code and not to use this \"default\" encoder since \"it is better explicit than implicit\", but I understand using this will save some of your time. :-)\nimport time\nimport json\nimport decimal\nfrom uuid import UUID\nfrom datetime import datetime\n\ndef JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']):\n '''\n JSON Encoder newdfeault is a wrapper capable of encoding several kinds\n Use it anywhere on your code to make the full system to work with this defaults:\n JSONEncoder_newdefault() # for everything\n JSONEncoder_newdefault(['decimal']) # only for Decimal\n '''\n JSONEncoder_olddefault = json.JSONEncoder.default\n\n def JSONEncoder_wrapped(self, o):\n '''\n json.JSONEncoder.default = JSONEncoder_newdefault\n '''\n if ('uuid' in kind) and isinstance(o, uuid.UUID):\n return str(o)\n if ('datetime' in kind) and isinstance(o, datetime):\n return str(o)\n if ('time' in kind) and isinstance(o, time.struct_time):\n return datetime.fromtimestamp(time.mktime(o))\n if ('decimal' in kind) and isinstance(o, decimal.Decimal):\n return str(o)\n return JSONEncoder_olddefault(self, o)\n json.JSONEncoder.default = JSONEncoder_wrapped\n\n# Example\nif __name__ == '__main__':\n JSONEncoder_newdefault()\n\n", "If someone is still looking for the answer, it is most probably you have a 'NaN' in your data that you are trying to encode. Because NaN is considered as float by Python.\n", "If you want to pass a dictionary containing decimals to the requests library (using the json keyword argument), you simply need to install simplejson:\n$ pip3 install simplejson \n$ python3\n>>> import requests\n>>> from decimal import Decimal\n>>> # This won't error out:\n>>> requests.post('https://www.google.com', json={'foo': Decimal('1.23')})\n\nThe reason of the problem is that requests uses simplejson only if it is present, and falls back to the built-in json if it is not installed.\n", "For anybody that wants a quick solution here is how I removed Decimal from my queries in Django\ntotal_development_cost_var = process_assumption_objects.values('total_development_cost').aggregate(sum_dev = Sum('total_development_cost', output_field=FloatField()))\ntotal_development_cost_var = list(total_development_cost_var.values())\n\n\nStep 1: use , output_field=FloatField() in you r query\nStep 2: use list eg list(total_development_cost_var.values())\n\nHope it helps\n", "This question is old, but there seems to be a better and much simpler solution in Python3 for most use-cases:\nnumber = Decimal(0.55)\nconverted_number = float(number) # Returns: 0.55 (as type float)\n\nYou can just convert Decimal to float.\n", "My 2 cents for easy solution, if you're sure Decimal is the only bad guy on your json dumps method:\nprint(json.loads(json.dumps({\n 'a': Decimal(1230),\n 'b': Decimal(11111111123.22),\n}, default=lambda x: eval(str(x)))))\n\n>>> {'a': 1230, 'b': 11111111123.22}\n\nThe \"smart\" thing here is using default to convert Decimal to int or float, automatically, taking advantage of eval function: default=lambda x: eval(str(x))\nBut always be careful using eval on your code as it can lead to security issues ;)\n", "Decimal is not suitable to be converted through:\n\nfloat due to precision problems\nstr due to openapi restrictions\n\nWe still need direct decimal to a number json serialisation.\nHere is our extension of @tesdal 's fakefloat solution (closed in v3.5.2rc1).\nIt uses fakestr + monkeypatching to avoid quotation and \"floatation\" of decimals.\nimport json.encoder\nfrom decimal import Decimal\n\n\ndef encode_fakestr(func):\n def wrap(s):\n if isinstance(s, fakestr):\n return repr(s)\n return func(s)\n return wrap\n\n\njson.encoder.encode_basestring = encode_fakestr(json.encoder.encode_basestring)\njson.encoder.encode_basestring_ascii = encode_fakestr(json.encoder.encode_basestring_ascii)\n\n\nclass fakestr(str):\n def __init__(self, value):\n self._value = value\n def __repr__(self):\n return str(self._value)\n\n\nclass DecimalJsonEncoder(json.encoder.JSONEncoder):\n def default(self, o):\n if isinstance(o, Decimal):\n return fakestr(o)\n return super().default(o)\n\n\njson.dumps([Decimal('1.1')], cls=DecimalJsonEncoder)\n\n[1.1]\n\nI don't understand why python developers force us using floats in places where it is not suitable.\n", "I will share what worked for me with flask 2.1.0\nWhen I was creating the dictionary which had to be used from jsonify I used rounding:\njson_dict['price'] = round(self.price, ndigits=2) if self.price else 0\n\nSo this way I could return D.DD number or 0 without using some global configuration. And this is nice because some Decimals has to be bigger, like latitude and longitude coordinates.\nreturn jsonify(json_dict)\n\n" ]
[ 265, 239, 178, 64, 57, 38, 28, 14, 14, 13, 11, 7, 4, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "decimal", "floating_point", "json", "python" ]
stackoverflow_0001960516_decimal_floating_point_json_python.txt
Q: Read data from firebase document with sub collections >> sub documents Is it possible to get data of sub-documents by reading only the main document in Firestore? Basically, the Firebase listCollections() method gives the id of subcollections, but how can we get their data? I have tried for listCollections() to get the id of sub-collections, but have not found a way to get data sub-collections data. A: Is it possible to get data of sub-documents by reading only the main document in Firebase? In Firestore, the queries are shallow. This means that it can only return documents from the collection that the query is run against. So there is no way you can get documents along with the data that exists inside sub-collections in one go. A single query can only read fields of documents in a single collection. If you need to get documents from sub-collection, you need to perform separate queries. If you have collections or sub-collections that have the exact same name then you can use a collection group query. A: Firebase listCollectionIds(),Firebase listDocuments() are well documented by firebase but nobody use and write on it.... I think the best way is to list subcollection to your document throught the well-know get() and then process a foreach on result snapshot snapshot.forEach(doc =>{ console.log(doc.id) console.log(doc.data()) })
Read data from firebase document with sub collections >> sub documents
Is it possible to get data of sub-documents by reading only the main document in Firestore? Basically, the Firebase listCollections() method gives the id of subcollections, but how can we get their data? I have tried for listCollections() to get the id of sub-collections, but have not found a way to get data sub-collections data.
[ "\nIs it possible to get data of sub-documents by reading only the main document in Firebase?\n\nIn Firestore, the queries are shallow. This means that it can only return documents from the collection that the query is run against. So there is no way you can get documents along with the data that exists inside sub-collections in one go. A single query can only read fields of documents in a single collection.\nIf you need to get documents from sub-collection, you need to perform separate queries. If you have collections or sub-collections that have the exact same name then you can use a collection group query.\n", "Firebase listCollectionIds(),Firebase listDocuments() are well documented by firebase but nobody use and write on it....\nI think the best way is to list subcollection to your document throught the well-know get() and then process a foreach on result snapshot\nsnapshot.forEach(doc =>{\nconsole.log(doc.id)\nconsole.log(doc.data())\n})\n\n\n" ]
[ 1, 0 ]
[]
[]
[ "firebase", "google_cloud_firestore", "google_cloud_platform" ]
stackoverflow_0074656132_firebase_google_cloud_firestore_google_cloud_platform.txt
Q: Why is Mean Square error of a gamma variable not being calculated? So I have written this code that calculates mean square estimates of alpha and beta for different values of samples and betas. The value of alpha is 3, since we add three exponential distributions to create the gamma variable. However, this code isn't giving me any correct output. # include <stdio.h> # include <math.h> # include <stdlib.h> // Don't forget to include this main() { int n,N; // Sample size and number of simulations long double alpha=3,beta,suma=0.0,sumb=0.0,msea,mseb; int i,j,k; printf("Enter the number of simulations"); scanf("%d", &N); printf("Enter the sample size"); scanf("%d", &n); printf("Enter the value of beta"); scanf("%Lf", &beta); //Simulation starts to calculate MSE for(i=0;i<N;i++) { float msea=0.0,mseb=0.0,sum=0.0,sumsq=0.0; //Vlaue is reset at every iteration, so declared inside i loop for(j=0;j<n;j++)//each sample { float g; for(k=0;k<alpha;k++) g += (double)(-1/beta)*log(1-((double)rand()/RAND_MAX));//sum of exp is gamma sum += g; sumsq += g*g; } float xbar = sum/n; float var = sumsq/n - xbar*xbar; suma += pow ((xbar*xbar/var - alpha),2); sumb += pow ((xbar/var - beta),2); } msea = suma/n; mseb = sumb/n; printf("MSE of alpha is = %Lf", msea); printf("MSE of beta is = %Lf", mseb); return 0; } Can you help me find my error? A: Code has at least these problems: Uninitialized g float g; for (k = 0; k < alpha; k++) g += (double) (-1 / beta) * log(1 - ((double) rand() / RAND_MAX)); log(0) log(1-((double)rand()/RAND_MAX)) might deliver log(0). I suspect log(1 - (((double) rand() + 0.5)/ (RAND_MAX + 1u))) will provide better distribution. 3 FP types There is a lot of up converting, down converting going on with float, double, long double. Use double throughout until it is determined other widths are needed. Unused objects float msea=0.0,mseb=0.0 are not used. Tip: Enable all warnings and save time. Use %g "%g" is more informative. // printf("MSE of alpha is = %Lf", msea); printf("MSE of alpha is = %Lg", msea); OP reports "I made the changes, it's still giving nan output ". I get MSE of alpha is = 105.474 MSE of beta is = 31.4536 I suspect OP has not made all the changes. # include <stdio.h> # include <math.h> # include <stdlib.h> // Don't forget to include this int main() { int n, NN; // Sample size and number of simulations double alpha = 3, beta, suma = 0.0, sumb = 0.0, msea, mseb; int i, j, k; printf("Enter the number of simulations"); // scanf("%d", &NN); printf("Enter the sample size"); // scanf("%d", &n); printf("Enter the value of beta"); // scanf("%f", &beta); NN = 1000; n = 20; beta = 1.5; //Simulation starts to calculate MSE for (i = 0; i < NN; i++) { double sum = 0.0, sumsq = 0.0; //Vlaue is reset at every iteration, so declared inside i loop for (j = 0; j < n; j++) //each sample { double g = 0; for (k = 0; k < alpha; k++) g += (double) (-1 / beta) * log(1 - (((double) rand() + 0.5) / (RAND_MAX + 1u))); sum += g; sumsq += g * g; } double xbar = sum / n; double var = sumsq / n - xbar * xbar; suma += pow((xbar * xbar / var - alpha), 2); sumb += pow((xbar / var - beta), 2); } msea = suma / n; mseb = sumb / n; printf("MSE of alpha is = %g\n", msea); printf("MSE of beta is = %g\n", mseb); return 0; }
Why is Mean Square error of a gamma variable not being calculated?
So I have written this code that calculates mean square estimates of alpha and beta for different values of samples and betas. The value of alpha is 3, since we add three exponential distributions to create the gamma variable. However, this code isn't giving me any correct output. # include <stdio.h> # include <math.h> # include <stdlib.h> // Don't forget to include this main() { int n,N; // Sample size and number of simulations long double alpha=3,beta,suma=0.0,sumb=0.0,msea,mseb; int i,j,k; printf("Enter the number of simulations"); scanf("%d", &N); printf("Enter the sample size"); scanf("%d", &n); printf("Enter the value of beta"); scanf("%Lf", &beta); //Simulation starts to calculate MSE for(i=0;i<N;i++) { float msea=0.0,mseb=0.0,sum=0.0,sumsq=0.0; //Vlaue is reset at every iteration, so declared inside i loop for(j=0;j<n;j++)//each sample { float g; for(k=0;k<alpha;k++) g += (double)(-1/beta)*log(1-((double)rand()/RAND_MAX));//sum of exp is gamma sum += g; sumsq += g*g; } float xbar = sum/n; float var = sumsq/n - xbar*xbar; suma += pow ((xbar*xbar/var - alpha),2); sumb += pow ((xbar/var - beta),2); } msea = suma/n; mseb = sumb/n; printf("MSE of alpha is = %Lf", msea); printf("MSE of beta is = %Lf", mseb); return 0; } Can you help me find my error?
[ "Code has at least these problems:\nUninitialized g\n float g;\n for (k = 0; k < alpha; k++)\n g += (double) (-1 / beta) * log(1 - ((double) rand() / RAND_MAX)); \n\nlog(0)\nlog(1-((double)rand()/RAND_MAX)) might deliver log(0). I suspect log(1 - (((double) rand() + 0.5)/ (RAND_MAX + 1u))) will provide better distribution.\n3 FP types\nThere is a lot of up converting, down converting going on with float, double, long double.\nUse double throughout until it is determined other widths are needed.\nUnused objects\nfloat msea=0.0,mseb=0.0 are not used. Tip: Enable all warnings and save time.\nUse %g\n\"%g\" is more informative.\n// printf(\"MSE of alpha is = %Lf\", msea);\nprintf(\"MSE of alpha is = %Lg\", msea);\n\n\nOP reports \"I made the changes, it's still giving nan output \". I get\nMSE of alpha is = 105.474\nMSE of beta is = 31.4536\n\nI suspect OP has not made all the changes.\n# include <stdio.h>\n# include <math.h>\n# include <stdlib.h> // Don't forget to include this\n\nint main() {\n int n, NN; // Sample size and number of simulations\n double alpha = 3, beta, suma = 0.0, sumb = 0.0, msea, mseb;\n int i, j, k;\n printf(\"Enter the number of simulations\");\n// scanf(\"%d\", &NN);\n printf(\"Enter the sample size\");\n// scanf(\"%d\", &n);\n printf(\"Enter the value of beta\");\n// scanf(\"%f\", &beta);\n NN = 1000;\n n = 20;\n beta = 1.5;\n //Simulation starts to calculate MSE\n for (i = 0; i < NN; i++) {\n double sum = 0.0, sumsq = 0.0; //Vlaue is reset at every iteration, so declared inside i loop\n for (j = 0; j < n; j++) //each sample\n {\n double g = 0;\n for (k = 0; k < alpha; k++)\n g += (double) (-1 / beta)\n * log(1 - (((double) rand() + 0.5) / (RAND_MAX + 1u)));\n sum += g;\n sumsq += g * g;\n }\n double xbar = sum / n;\n double var = sumsq / n - xbar * xbar;\n suma += pow((xbar * xbar / var - alpha), 2);\n sumb += pow((xbar / var - beta), 2);\n }\n msea = suma / n;\n mseb = sumb / n;\n printf(\"MSE of alpha is = %g\\n\", msea);\n printf(\"MSE of beta is = %g\\n\", mseb);\n\n return 0;\n}\n\n" ]
[ 2 ]
[]
[]
[ "c", "gamma_distribution", "mean_square_error" ]
stackoverflow_0074656771_c_gamma_distribution_mean_square_error.txt
Q: AWS : Using EFS with Fargate/ECS Containers I am attempting to use EFS with Fargate/ECS containers. I have tested the EFS instance using multiple linux instances. I tried to follow the example at https://aws.amazon.com/premiumsupport/knowledge-center/ecs-fargate-mount-efs-containers-tasks/ The container throws this error. Resourceinitializationerror: failed to invoke EFS utils commands to set up EFS volumes: stderr: b'mount.nfs4: access denied by server while mounting 127.0.0.1:/' : unsuccessful EFS utils command execution; code: 32 The EFS SecurityGroup : Inbound: TCP--2049--10.0.0.0/16 (VPC CIDR) All--All--sg-0bd22... (Container SG ID) Outbound: All--All--0.0.0.0/0 The Container SecurityGroup Inbound: All--All--0.0.0.0/0 Outbound: All--All--0.0.0.0/0 This is my task definition: { "ipcMode": null, "executionRoleArn": "arn:aws:iam::327425660322:role/ecsTaskExecutionRole", "containerDefinitions": [ { "dnsSearchDomains": null, "environmentFiles": null, "logConfiguration": { "logDriver": "awslogs", "secretOptions": null, "options": { "awslogs-group": "/ecs/prefetch", "awslogs-region": "us-east-2", "awslogs-stream-prefix": "ecs" } }, "entryPoint": null, "portMappings": [ { "hostPort": 80, "protocol": "tcp", "containerPort": 80 } ], "command": null, "linuxParameters": null, "cpu": 0, "environment": [], "resourceRequirements": null, "ulimits": null, "dnsServers": null, "mountPoints": [ { "readOnly": null, "containerPath": "/usr/share/nginx/html", "sourceVolume": "efs-html" } ], "workingDirectory": null, "secrets": null, "dockerSecurityOptions": null, "memory": 128, "memoryReservation": null, "volumesFrom": [], "stopTimeout": null, "image": "nginx", "startTimeout": null, "firelensConfiguration": null, "dependsOn": null, "disableNetworking": null, "interactive": null, "healthCheck": null, "essential": true, "links": null, "hostname": null, "extraHosts": null, "pseudoTerminal": null, "user": null, "readonlyRootFilesystem": null, "dockerLabels": null, "systemControls": null, "privileged": null, "name": "nginx" } ], "memory": "512", "taskRoleArn": null, "family": "efs-tutorial", "pidMode": null, "requiresCompatibilities": [ "FARGATE" ], "networkMode": "awsvpc", "runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": null }, "cpu": "256", "inferenceAccelerators": [], "proxyConfiguration": null, "volumes": [ { "fsxWindowsFileServerVolumeConfiguration": null, "efsVolumeConfiguration": { "transitEncryptionPort": null, "fileSystemId": "fs-0d15c1e9184fffacd", "authorizationConfig": { "iam": "DISABLED", "accessPointId": "fsap-04a23206444492e37" }, "transitEncryption": "ENABLED", "rootDirectory": "/" }, "name": "efs-html", "host": null, "dockerVolumeConfiguration": null } ], "tags": [] } I also am using the following policies as the task Execution Role: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ecr:GetAuthorizationToken", "ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "*" } ] } And { "Version": "2012-10-17", "Statement": [ { "Action": [ "cloudwatch:DescribeAlarmsForMetric", "cloudwatch:GetMetricData", "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DescribeAvailabilityZones", "ec2:DescribeNetworkInterfaceAttribute", "ec2:DescribeNetworkInterfaces", "ec2:DescribeSecurityGroups", "ec2:DescribeSubnets", "ec2:DescribeVpcAttribute", "ec2:DescribeVpcs", "ec2:ModifyNetworkInterfaceAttribute", "elasticfilesystem:Backup", "elasticfilesystem:ClientRootAccess", "elasticfilesystem:ClientWrite", "elasticfilesystem:CreateFileSystem", "elasticfilesystem:ClientMount", "elasticfilesystem:CreateMountTarget", "elasticfilesystem:CreateTags", "elasticfilesystem:CreateAccessPoint", "elasticfilesystem:CreateReplicationConfiguration", "elasticfilesystem:DeleteFileSystem", "elasticfilesystem:DeleteMountTarget", "elasticfilesystem:DeleteTags", "elasticfilesystem:DeleteAccessPoint", "elasticfilesystem:DeleteFileSystemPolicy", "elasticfilesystem:DeleteReplicationConfiguration", "elasticfilesystem:DescribeAccountPreferences", "elasticfilesystem:DescribeBackupPolicy", "elasticfilesystem:DescribeFileSystems", "elasticfilesystem:DescribeFileSystemPolicy", "elasticfilesystem:DescribeLifecycleConfiguration", "elasticfilesystem:DescribeMountTargets", "elasticfilesystem:DescribeMountTargetSecurityGroups", "elasticfilesystem:DescribeReplicationConfigurations", "elasticfilesystem:DescribeTags", "elasticfilesystem:DescribeAccessPoints", "elasticfilesystem:ModifyMountTargetSecurityGroups", "elasticfilesystem:PutAccountPreferences", "elasticfilesystem:PutBackupPolicy", "elasticfilesystem:PutLifecycleConfiguration", "elasticfilesystem:PutFileSystemPolicy", "elasticfilesystem:UpdateFileSystem", "elasticfilesystem:TagResource", "elasticfilesystem:UntagResource", "elasticfilesystem:ListTagsForResource", "elasticfilesystem:Restore", "kms:DescribeKey", "kms:ListAliases" ], "Effect": "Allow", "Resource": "*" }, { "Action": "iam:CreateServiceLinkedRole", "Effect": "Allow", "Resource": "*", "Condition": { "StringEquals": { "iam:AWSServiceName": [ "elasticfilesystem.amazonaws.com" ] } } } ] } A: There are two things you need to fix: The IAM permissions for EFS access need to be on the ECS Task Role, not the ECS Execution Role. You need to enable IAM permission usage on the access point connection settings. You currently have this disabled "iam": "DISABLED",. That means that all the IAM permissions you are trying to set are being ignored, and only the EFS volume's resource policy is being evaluated.
AWS : Using EFS with Fargate/ECS Containers
I am attempting to use EFS with Fargate/ECS containers. I have tested the EFS instance using multiple linux instances. I tried to follow the example at https://aws.amazon.com/premiumsupport/knowledge-center/ecs-fargate-mount-efs-containers-tasks/ The container throws this error. Resourceinitializationerror: failed to invoke EFS utils commands to set up EFS volumes: stderr: b'mount.nfs4: access denied by server while mounting 127.0.0.1:/' : unsuccessful EFS utils command execution; code: 32 The EFS SecurityGroup : Inbound: TCP--2049--10.0.0.0/16 (VPC CIDR) All--All--sg-0bd22... (Container SG ID) Outbound: All--All--0.0.0.0/0 The Container SecurityGroup Inbound: All--All--0.0.0.0/0 Outbound: All--All--0.0.0.0/0 This is my task definition: { "ipcMode": null, "executionRoleArn": "arn:aws:iam::327425660322:role/ecsTaskExecutionRole", "containerDefinitions": [ { "dnsSearchDomains": null, "environmentFiles": null, "logConfiguration": { "logDriver": "awslogs", "secretOptions": null, "options": { "awslogs-group": "/ecs/prefetch", "awslogs-region": "us-east-2", "awslogs-stream-prefix": "ecs" } }, "entryPoint": null, "portMappings": [ { "hostPort": 80, "protocol": "tcp", "containerPort": 80 } ], "command": null, "linuxParameters": null, "cpu": 0, "environment": [], "resourceRequirements": null, "ulimits": null, "dnsServers": null, "mountPoints": [ { "readOnly": null, "containerPath": "/usr/share/nginx/html", "sourceVolume": "efs-html" } ], "workingDirectory": null, "secrets": null, "dockerSecurityOptions": null, "memory": 128, "memoryReservation": null, "volumesFrom": [], "stopTimeout": null, "image": "nginx", "startTimeout": null, "firelensConfiguration": null, "dependsOn": null, "disableNetworking": null, "interactive": null, "healthCheck": null, "essential": true, "links": null, "hostname": null, "extraHosts": null, "pseudoTerminal": null, "user": null, "readonlyRootFilesystem": null, "dockerLabels": null, "systemControls": null, "privileged": null, "name": "nginx" } ], "memory": "512", "taskRoleArn": null, "family": "efs-tutorial", "pidMode": null, "requiresCompatibilities": [ "FARGATE" ], "networkMode": "awsvpc", "runtimePlatform": { "operatingSystemFamily": "LINUX", "cpuArchitecture": null }, "cpu": "256", "inferenceAccelerators": [], "proxyConfiguration": null, "volumes": [ { "fsxWindowsFileServerVolumeConfiguration": null, "efsVolumeConfiguration": { "transitEncryptionPort": null, "fileSystemId": "fs-0d15c1e9184fffacd", "authorizationConfig": { "iam": "DISABLED", "accessPointId": "fsap-04a23206444492e37" }, "transitEncryption": "ENABLED", "rootDirectory": "/" }, "name": "efs-html", "host": null, "dockerVolumeConfiguration": null } ], "tags": [] } I also am using the following policies as the task Execution Role: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ecr:GetAuthorizationToken", "ecr:BatchCheckLayerAvailability", "ecr:GetDownloadUrlForLayer", "ecr:BatchGetImage", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "*" } ] } And { "Version": "2012-10-17", "Statement": [ { "Action": [ "cloudwatch:DescribeAlarmsForMetric", "cloudwatch:GetMetricData", "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DescribeAvailabilityZones", "ec2:DescribeNetworkInterfaceAttribute", "ec2:DescribeNetworkInterfaces", "ec2:DescribeSecurityGroups", "ec2:DescribeSubnets", "ec2:DescribeVpcAttribute", "ec2:DescribeVpcs", "ec2:ModifyNetworkInterfaceAttribute", "elasticfilesystem:Backup", "elasticfilesystem:ClientRootAccess", "elasticfilesystem:ClientWrite", "elasticfilesystem:CreateFileSystem", "elasticfilesystem:ClientMount", "elasticfilesystem:CreateMountTarget", "elasticfilesystem:CreateTags", "elasticfilesystem:CreateAccessPoint", "elasticfilesystem:CreateReplicationConfiguration", "elasticfilesystem:DeleteFileSystem", "elasticfilesystem:DeleteMountTarget", "elasticfilesystem:DeleteTags", "elasticfilesystem:DeleteAccessPoint", "elasticfilesystem:DeleteFileSystemPolicy", "elasticfilesystem:DeleteReplicationConfiguration", "elasticfilesystem:DescribeAccountPreferences", "elasticfilesystem:DescribeBackupPolicy", "elasticfilesystem:DescribeFileSystems", "elasticfilesystem:DescribeFileSystemPolicy", "elasticfilesystem:DescribeLifecycleConfiguration", "elasticfilesystem:DescribeMountTargets", "elasticfilesystem:DescribeMountTargetSecurityGroups", "elasticfilesystem:DescribeReplicationConfigurations", "elasticfilesystem:DescribeTags", "elasticfilesystem:DescribeAccessPoints", "elasticfilesystem:ModifyMountTargetSecurityGroups", "elasticfilesystem:PutAccountPreferences", "elasticfilesystem:PutBackupPolicy", "elasticfilesystem:PutLifecycleConfiguration", "elasticfilesystem:PutFileSystemPolicy", "elasticfilesystem:UpdateFileSystem", "elasticfilesystem:TagResource", "elasticfilesystem:UntagResource", "elasticfilesystem:ListTagsForResource", "elasticfilesystem:Restore", "kms:DescribeKey", "kms:ListAliases" ], "Effect": "Allow", "Resource": "*" }, { "Action": "iam:CreateServiceLinkedRole", "Effect": "Allow", "Resource": "*", "Condition": { "StringEquals": { "iam:AWSServiceName": [ "elasticfilesystem.amazonaws.com" ] } } } ] }
[ "There are two things you need to fix:\n\nThe IAM permissions for EFS access need to be on the ECS Task Role, not the ECS Execution Role.\n\nYou need to enable IAM permission usage on the access point connection settings. You currently have this disabled \"iam\": \"DISABLED\",. That means that all the IAM permissions you are trying to set are being ignored, and only the EFS volume's resource policy is being evaluated.\n\n\n" ]
[ 0 ]
[]
[]
[ "amazon_ecs", "amazon_efs", "amazon_web_services", "aws_fargate" ]
stackoverflow_0074652063_amazon_ecs_amazon_efs_amazon_web_services_aws_fargate.txt
Q: Some of ReSharper settings not visible I have downloaded ReSharper to Visual Studio 2022. I need to run code analysis to check if all varables are named correctly in camelCase. Also I want to implement custom rule that no double or float type variables would be used in the project. There should be an option Code Inspection | Custom Patterns in Extensions -> ReSharper -> Options. I cannot find this option. How do I configure custom rule and run code analysis? A: I have found out that my ReSharper was disabled. I had turn on trial version. I didt it clicking on Why is Resharper disabled:
Some of ReSharper settings not visible
I have downloaded ReSharper to Visual Studio 2022. I need to run code analysis to check if all varables are named correctly in camelCase. Also I want to implement custom rule that no double or float type variables would be used in the project. There should be an option Code Inspection | Custom Patterns in Extensions -> ReSharper -> Options. I cannot find this option. How do I configure custom rule and run code analysis?
[ "I have found out that my ReSharper was disabled. I had turn on trial version. I didt it clicking on Why is Resharper disabled:\n\n" ]
[ 0 ]
[]
[]
[ ".net", "c#", "code_analysis", "resharper", "visual_studio" ]
stackoverflow_0074656173_.net_c#_code_analysis_resharper_visual_studio.txt
Q: Window Function for First Instance in Repeating Time Periods I'm trying to translate the logic below into one or more SQL statements: Find the first occurrence of a given event for a user If the user has any additional events on that day or 30 days after, exclude those events. Keep only the first event. 30 days after the original event, you may consider new events, but the original logic applies. Take only the first new event, then exclude any other in the 30 days after the second event. Repeat for all events Finding the first event is easy, as is excluding all events that occur in the 30 days after it. I'm having trouble trying to identify all the following windows/events after the first without looping or scripting. My solution needs to support multiple RDBMS (MSSQL and Spark SQL at this time, potentially more), so the solution needs to be as close to standard SQL as possible, no platform-specific scripting. I also would like to avoid correlated subqueries if possible for performance reasons. But if that's the only way to solve the problem, I'm open to that as a solution. Example data: UserID EventDate 1 2022-01-02 1 2022-01-19 1 2022-02-01 1 2022-02-07 1 2022-02-08 1 2022-03-19 2 2022-01-04 2 2022-01-05 2 2022-01-06 2 2022-02-22 Desired output: UserID EventDate Include 1 2022-01-02 1 1 2022-01-19 0 1 2022-02-01 0 1 2022-02-07 1 1 2022-02-08 0 1 2022-03-19 1 2 2022-01-04 1 2 2022-01-05 0 2 2022-01-06 0 2 2022-02-22 1 Or: UserID EventDate 1 2022-01-02 1 2022-02-07 1 2022-03-19 2 2022-01-04 2 2022-02-22 A: This should work on most DB. drop table if exists #have; create table #have ( UserID [int] , date [date] ) ; insert into #have values (1, '2022-01-02') , (1, '2022-01-19') , (1, '2022-02-01') , (1, '2022-02-07') , (1, '2022-02-08') , (1, '2022-03-19') , (2, '2022-01-04') , (2, '2022-01-05') , (2, '2022-01-06') , (2, '2022-02-22') ; with c1 as ( select * , isnull(datediff(day, lag(date, 1) over(partition by UserID order by date), date), 0) as diff from #have ) , c2 as ( select *, sum(diff) over(partition by UserID order by date) as s , sum(diff) over(partition by UserID order by date) / 31 + 1 as thirty from c1 ) , c3 as ( select UserID , min(date) as date from c2 group by UserID, thirty ) select * from c3 order by UserID, date ;
Window Function for First Instance in Repeating Time Periods
I'm trying to translate the logic below into one or more SQL statements: Find the first occurrence of a given event for a user If the user has any additional events on that day or 30 days after, exclude those events. Keep only the first event. 30 days after the original event, you may consider new events, but the original logic applies. Take only the first new event, then exclude any other in the 30 days after the second event. Repeat for all events Finding the first event is easy, as is excluding all events that occur in the 30 days after it. I'm having trouble trying to identify all the following windows/events after the first without looping or scripting. My solution needs to support multiple RDBMS (MSSQL and Spark SQL at this time, potentially more), so the solution needs to be as close to standard SQL as possible, no platform-specific scripting. I also would like to avoid correlated subqueries if possible for performance reasons. But if that's the only way to solve the problem, I'm open to that as a solution. Example data: UserID EventDate 1 2022-01-02 1 2022-01-19 1 2022-02-01 1 2022-02-07 1 2022-02-08 1 2022-03-19 2 2022-01-04 2 2022-01-05 2 2022-01-06 2 2022-02-22 Desired output: UserID EventDate Include 1 2022-01-02 1 1 2022-01-19 0 1 2022-02-01 0 1 2022-02-07 1 1 2022-02-08 0 1 2022-03-19 1 2 2022-01-04 1 2 2022-01-05 0 2 2022-01-06 0 2 2022-02-22 1 Or: UserID EventDate 1 2022-01-02 1 2022-02-07 1 2022-03-19 2 2022-01-04 2 2022-02-22
[ "This should work on most DB.\ndrop table if exists #have;\n\ncreate table #have\n(\n UserID [int]\n, date [date]\n)\n;\n\ninsert into #have\nvalues\n (1, '2022-01-02')\n, (1, '2022-01-19')\n, (1, '2022-02-01')\n, (1, '2022-02-07')\n, (1, '2022-02-08')\n, (1, '2022-03-19')\n, (2, '2022-01-04')\n, (2, '2022-01-05')\n, (2, '2022-01-06')\n, (2, '2022-02-22')\n;\n\nwith c1 as\n(\nselect *\n , isnull(datediff(day, lag(date, 1) over(partition by UserID \n order by date), date), 0) as diff \n\nfrom #have\n)\n,\nc2 as\n(\nselect *, sum(diff) over(partition by UserID \n order by date) as s\n , sum(diff) over(partition by UserID \n order by date) / 31 + 1 as thirty\nfrom c1\n)\n,\nc3 as\n(\nselect UserID\n , min(date) as date\nfrom c2\ngroup by UserID, thirty\n)\n\nselect * from c3 \norder by UserID, date\n;\n\n" ]
[ 1 ]
[]
[]
[ "sql" ]
stackoverflow_0074655436_sql.txt
Q: Can't display fetched posts in AstroJS I am trying to build my website in AstroJS and I am not able to display the content I fetch inside the "Masonry" component, which is being rendered as an empty "div" in my browser. --- import BaseLayout from "../layouts/BaseLayout.astro"; import Masonry from "../components/Masonry.astro"; import ProjectThumbnail from "../components/ProjectThumbnail.astro"; const projects = await Astro.glob('./projects/*.md'); --- {console.log(projects.length)} <BaseLayout title="overview"> <Masonry title="grid"> {projects.map( (project)=>{ console.log(project); <ProjectThumbnail title={project.frontmatter.title} w_cols={project.frontmatter.width_cols} h_cols={project.frontmatter.height_cols} /> } )} </Masonry> </BaseLayout> As you see, there are two console logs: the first one outputs "2" as there are two .md files in the ./projects directory the second one ouputs: { frontmatter: [Getter], file: [Getter], url: [Getter], rawContent: [Getter], compiledContent: [Getter], getHeadings: [Getter], getHeaders: [Getter], Content: [Getter], default: [AsyncFunction: Content] { [Symbol(astro.needsHeadRendering)]: false }, [Symbol(Symbol.toStringTag)]: 'Module' } { frontmatter: [Getter], file: [Getter], url: [Getter], rawContent: [Getter], compiledContent: [Getter], getHeadings: [Getter], getHeaders: [Getter], Content: [Getter], default: [AsyncFunction: Content] { [Symbol(astro.needsHeadRendering)]: false }, [Symbol(Symbol.toStringTag)]: 'Module' } My .md files are named project-sample.md and project-sample-two.md, their content is this (title changes according to the file): --- title: 'Project sample' layout: '../../layouts/Project.astro' thumbnail: '/project-sample-img.jpg' excerpt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' height_cols: '1' width_cols: '2' --- Dolor sit amet Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. When I open the posts individualy by going to localhost:3001/projects/project-sample they both display their content as spected. I hope you can help me by telling me what I am missing here. Best regards! ps: I am following this reference from Astro's docs A: Fixed the problem by switching from this: (project)=>{ console.log(project); <ProjectThumbnail title={project.frontmatter.title} w_cols={project.frontmatter.width_cols} h_cols={project.frontmatter.height_cols} /> } to this: (project)=>( <ProjectThumbnail title={project.frontmatter.title} w_cols={project.frontmatter.width_cols} h_cols={project.frontmatter.height_cols} /> )
Can't display fetched posts in AstroJS
I am trying to build my website in AstroJS and I am not able to display the content I fetch inside the "Masonry" component, which is being rendered as an empty "div" in my browser. --- import BaseLayout from "../layouts/BaseLayout.astro"; import Masonry from "../components/Masonry.astro"; import ProjectThumbnail from "../components/ProjectThumbnail.astro"; const projects = await Astro.glob('./projects/*.md'); --- {console.log(projects.length)} <BaseLayout title="overview"> <Masonry title="grid"> {projects.map( (project)=>{ console.log(project); <ProjectThumbnail title={project.frontmatter.title} w_cols={project.frontmatter.width_cols} h_cols={project.frontmatter.height_cols} /> } )} </Masonry> </BaseLayout> As you see, there are two console logs: the first one outputs "2" as there are two .md files in the ./projects directory the second one ouputs: { frontmatter: [Getter], file: [Getter], url: [Getter], rawContent: [Getter], compiledContent: [Getter], getHeadings: [Getter], getHeaders: [Getter], Content: [Getter], default: [AsyncFunction: Content] { [Symbol(astro.needsHeadRendering)]: false }, [Symbol(Symbol.toStringTag)]: 'Module' } { frontmatter: [Getter], file: [Getter], url: [Getter], rawContent: [Getter], compiledContent: [Getter], getHeadings: [Getter], getHeaders: [Getter], Content: [Getter], default: [AsyncFunction: Content] { [Symbol(astro.needsHeadRendering)]: false }, [Symbol(Symbol.toStringTag)]: 'Module' } My .md files are named project-sample.md and project-sample-two.md, their content is this (title changes according to the file): --- title: 'Project sample' layout: '../../layouts/Project.astro' thumbnail: '/project-sample-img.jpg' excerpt: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' height_cols: '1' width_cols: '2' --- Dolor sit amet Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. When I open the posts individualy by going to localhost:3001/projects/project-sample they both display their content as spected. I hope you can help me by telling me what I am missing here. Best regards! ps: I am following this reference from Astro's docs
[ "Fixed the problem by switching from this:\n\n\n (project)=>{\n console.log(project);\n <ProjectThumbnail title={project.frontmatter.title} w_cols={project.frontmatter.width_cols} h_cols={project.frontmatter.height_cols} />\n }\n\n\n\nto this:\n (project)=>(\n <ProjectThumbnail title={project.frontmatter.title} w_cols={project.frontmatter.width_cols} h_cols={project.frontmatter.height_cols} />\n )\n\n" ]
[ 0 ]
[]
[]
[ "astrojs", "html", "jamstack", "javascript", "markdown" ]
stackoverflow_0074648396_astrojs_html_jamstack_javascript_markdown.txt
Q: dollar sign symbol is not working in React I am building a CRUD app with React. For the Product Edit page where I want to edit a specific product(clicked product), I need to grab the product's Id. I use the dollar symbol in the code but it doesn't get blue(it doesn't work). I need the URL to change the specific product showing its id when clicked. How to do that? What am I doing wrong? ` <Link className='btn btn-primary m-2'><i className="fa fa-eye" aria-hidden="true"></i></ Link> <Link className='btn btn-otline-primary m-2' to={"/product/edit/${product.id}"}>Edit</Link> <Link className='btn btn-danger m-2'>Delete</Link> ` const onSubmit = async e => { e.preventDefault(); await axios.put('http://localhost:3001/products/${id}', product); navigate.push("/"); }; `` I thought when I clicked the Edit button I could see the Edit page for the specific product but instead it shows like this: http://localhost:3000/product/edit/$%7Bproduct.id%7D. Not an id after the editing part. A: Should be `` not '' await axios.put(`http://localhost:3001/products/${id}`, product); A: Template literals are created using the ` symbol, this works: let x = "def" console.log(`abc${x}`); // Prints: "abcdef" But normal strings don't: let x = "def" console.log("abc${x}"); // Prints: "abc${x}" See MDN Reference to learn more about how template strings work.
dollar sign symbol is not working in React
I am building a CRUD app with React. For the Product Edit page where I want to edit a specific product(clicked product), I need to grab the product's Id. I use the dollar symbol in the code but it doesn't get blue(it doesn't work). I need the URL to change the specific product showing its id when clicked. How to do that? What am I doing wrong? ` <Link className='btn btn-primary m-2'><i className="fa fa-eye" aria-hidden="true"></i></ Link> <Link className='btn btn-otline-primary m-2' to={"/product/edit/${product.id}"}>Edit</Link> <Link className='btn btn-danger m-2'>Delete</Link> ` const onSubmit = async e => { e.preventDefault(); await axios.put('http://localhost:3001/products/${id}', product); navigate.push("/"); }; `` I thought when I clicked the Edit button I could see the Edit page for the specific product but instead it shows like this: http://localhost:3000/product/edit/$%7Bproduct.id%7D. Not an id after the editing part.
[ "Should be `` not ''\n await axios.put(`http://localhost:3001/products/${id}`, product);\n\n", "Template literals are created using the ` symbol, this works:\nlet x = \"def\"\nconsole.log(`abc${x}`);\n// Prints: \"abcdef\"\n\nBut normal strings don't:\nlet x = \"def\"\nconsole.log(\"abc${x}\");\n// Prints: \"abc${x}\"\n\nSee MDN Reference to learn more about how template strings work.\n" ]
[ 2, 1 ]
[]
[]
[ "crud", "dollar_sign", "reactjs" ]
stackoverflow_0074657065_crud_dollar_sign_reactjs.txt
Q: Bug Firebase sent event add_to_card with item_price I sent the item bundles with params from Google examples val itemJeggings = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_123") putString(FirebaseAnalytics.Param.ITEM_NAME, "jeggings") putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "pants") putString(FirebaseAnalytics.Param.ITEM_VARIANT, "black") putString(FirebaseAnalytics.Param.ITEM_BRAND, "Google") putDouble(FirebaseAnalytics.Param.PRICE, 9.99) } val itemJeggingsWithIndex = Bundle(itemJeggings).apply { putLong(FirebaseAnalytics.Param.INDEX, 1) } firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM_LIST) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, "L001") param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "Related products") param(FirebaseAnalytics.Param.ITEMS,arrayOf(itemJeggingsWithIndex))} and get results in the debug console like this: Why can't i get a normal double price? A: Firebaser here. It looks like the issue you've described is a known issue on our end. I've added another instance of the bug report to let our engineers know the growing numbers of the affected users. While our team continues to investigate this behavior, we've yet to provide details or timelines as to when the fix will be available. For now, I suggest keeping an eye out for updates on our official blog and release notes for any updates.
Bug Firebase sent event add_to_card with item_price
I sent the item bundles with params from Google examples val itemJeggings = Bundle().apply { putString(FirebaseAnalytics.Param.ITEM_ID, "SKU_123") putString(FirebaseAnalytics.Param.ITEM_NAME, "jeggings") putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "pants") putString(FirebaseAnalytics.Param.ITEM_VARIANT, "black") putString(FirebaseAnalytics.Param.ITEM_BRAND, "Google") putDouble(FirebaseAnalytics.Param.PRICE, 9.99) } val itemJeggingsWithIndex = Bundle(itemJeggings).apply { putLong(FirebaseAnalytics.Param.INDEX, 1) } firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM_LIST) { param(FirebaseAnalytics.Param.ITEM_LIST_ID, "L001") param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "Related products") param(FirebaseAnalytics.Param.ITEMS,arrayOf(itemJeggingsWithIndex))} and get results in the debug console like this: Why can't i get a normal double price?
[ "Firebaser here.\nIt looks like the issue you've described is a known issue on our end. I've added another instance of the bug report to let our engineers know the growing numbers of the affected users. While our team continues to investigate this behavior, we've yet to provide details or timelines as to when the fix will be available. For now, I suggest keeping an eye out for updates on our official blog and release notes for any updates.\n" ]
[ 0 ]
[]
[]
[ "android", "firebase", "firebase_analytics", "kotlin" ]
stackoverflow_0072887109_android_firebase_firebase_analytics_kotlin.txt
Q: How do I display an animated gif in React Native? How can I display an animated gif in react native. This is what I've tried. <Image source={{uri: "loading"}} /> It works fine with a .png file but when I use a .gif file it's blank. I read somewhere to try renaming the .gif to a .png but that just displays one frame of the animated gif with no animation. Any ideas? A: For RN < 0.60 By default the Gif images are not supported in android react native app. You need to set use Fresco to display the gif images. The code: Edit your android/app/build.gradle file and add the following code: dependencies: { ... compile 'com.facebook.fresco:fresco:1.+' // For animated GIF support compile 'com.facebook.fresco:animated-gif:1.+' // For WebP support, including animated WebP compile 'com.facebook.fresco:animated-webp:1.+' compile 'com.facebook.fresco:webpsupport:1.+' } then you need to bundle the app again, You can display the gif images in two ways like this. 1-> <Image source={require('./../images/load.gif')} style={{width: 100, height: 100 }} /> 2-> <Image source={{uri: 'http://www.clicktorelease.com/code/gif/1.gif'}} style={{width: 100, height:100 }} /> For RN >= 0.60 implementation 'com.facebook.fresco:animated-gif:1.12.0' //instead of implementation 'com.facebook.fresco:animated-gif:2.0.0' //use I hope it is helpful to others, A: You need to add the extension and require it this way : <Image source={require('./path/to/image/loading.gif')} /> or <Image source={{uri: 'http://www.urltogif/image.gif'}} /> A: For React Native 0.60 and higher Open your android/app/build.gradle file and add following lines to first of dependencies section implementation 'com.facebook.fresco:fresco:2.0.0' implementation 'com.facebook.fresco:animated-gif:2.0.0' And then cd android gradlew clean react-native run-android A: For me on React native 0.65.1 The solution in react-native docs did not work I had to use the latest version of Fresco: implementation 'com.facebook.fresco:animated-gif:2.5.0' Now GIF works on Android for me. You can check Fresco latest from their website. A: For Android You Need to Add Facebook's Fresco Library React Native does not come with Gif support out of the box but you can add Facebook's Fresco library to add this support. You should be able to simply add the following to your build.gradle file: compile 'com.facebook.fresco:animated-gif:0.+' Specific Version Compatibility If you are having troubles or you want to use a static version (highly recommended), you can simply go to the following React Native documentation page and replace the 0.46 in the URL with the version of React Native you're running: https://facebook.github.io/react-native/docs/0.46/image.html#gif-and-webp-support-on-android A: if you want to use gif as background image than you can use <ImageBackground source={yourSourceFile} > -- your content --- </ImageBackground> A: To add gif and WebP in your project you need some optional modules. If the RN version is <=0.59 then add the following lines in your android/app/build.gradle file. dependencies { // If your app supports Android versions before Ice Cream Sandwich (API level 14) compile 'com.facebook.fresco:animated-base-support:1.10.0' // For animated GIF support compile 'com.facebook.fresco:animated-gif:1.10.0' // For WebP support, including animated WebP compile 'com.facebook.fresco:animated-webp:1.10.0' compile 'com.facebook.fresco:webpsupport:1.10.0' // For WebP support, without animations compile 'com.facebook.fresco:webpsupport:1.10.0' } If the RN version is 0.60 and greater then add the following lines in android/app/build.gradle file dependencies { // If your app supports Android versions before Ice Cream Sandwich (API level 14) implementation 'com.facebook.fresco:animated-base-support:1.10.0' // For animated GIF support implementation 'com.facebook.fresco:animated-gif:1.12.0' // For WebP support, including animated WebP implementation 'com.facebook.fresco:animated-webp:1.10.0' implementation 'com.facebook.fresco:webpsupport:1.10.0' // For WebP support, without animations implementation 'com.facebook.fresco:webpsupport:1.10.0' } A: DylanVann / react-native-fast-image is a nice alternative that supports GIFs for both Android (based on glide rather than fresco) and iOS (SDWebImage) with additional features that looks like: const YourImage = () => ( <FastImage style={{ width: 200, height: 200 }} source={{ uri: 'https://unsplash.it/400/400?image=1', headers: { Authorization: 'someAuthToken' }, priority: FastImage.priority.normal, }} resizeMode={FastImage.resizeMode.contain} /> ) A: import React,{useState} from 'react'; **step1 import from react narive You Can Use (Image) Or (ImageBackground) ** import { StyleSheet, Text, View ,ImageBackground} from 'react-native'; function LoadingUsers() { return(<View style={styles.LoadingView}> **Step 2 require inside source ImageBackground ** <ImageBackground source={require('../assets/stickman.gif')} style={styles.Gif}><Text>Loading..</Text></ImageBackground> </View>) } **Step 3 Set Width ANd height ** const styles = StyleSheet.create({ LoadingView:{ flex:1, }, Gif:{ flex:1, width:"100%", height:"100%", justifyContent:"center", alignItems:"center", backgroundColor:'#000', } }); export default LoadingUsers ; A: For RN >= 0.66 Edit your android/app/build.gradle file and add the following code: implementation 'com.facebook.fresco:fresco:2.0.0' implementation 'com.facebook.fresco:animated-gif:2.6.0' A: In any case you need something else you could use also WebView for it render(props) { const width = 220; const height = 135; const borderRadius = 15; const uri = 'https://c.tenor.com/0wj4ApfUlWUAAAAM/whatever-bank-stare.gif'; // const uri = 'https://c.tenor.com/YwsCGem_MmQAAAAC/parks-and-rec-amy-poehler.gif',; // const uri = 'https://media.tenor.com/images/1c39f2d94b02d8c9366de265d0fba8a0/tenor.gif'; return ( <View style={{ width, height, borderRadius: 15, overflow: 'hidden', }}> <WebView source={{ uri }} style={{ flex: 1, width, height, borderRadius, }} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} injectedJavaScript={` document.body.style.width = "${width}px"; document.body.style.height = "${height}px"; document.body.style.backgroundColor = "${'#fff'}"; document.body.style.overflow = "hidden"; const img = document.querySelector("img"); img.style.position = "absolute"; img.style.top = 0; img.style.left = 0; img.style.margin = "auto"; img.style[img.offsetWidth > img.offsetHeight ? 'width' : 'height'] = "100%"; img.style.borderRadius = "${borderRadius}px"; `} /> </View> ); } It will preserves the gif aspect ratio Also, I did the same with the <Image />. For anyone need it: function ChatImageGIF(props) { const maxWidth = 220; const maxHeight = 135; const [width, setWidth] = useState(maxWidth); const [height, setHeight] = useState(maxHeight); const borderRadius = 15; Image.getSize(props.currentMessage.video, (w, h) => { const minWidth = Math.min(maxWidth, w); const minHeight = Math.min(maxHeight, h); const aspectRatio = (w < h ? w : h) / (w < h ? h : w); setWidth(w < h ? minHeight * aspectRatio : minWidth); setHeight(w > h ? minWidth * aspectRatio : minHeight); }); return ( <View style={{ width, height, borderRadius: 15, overflow: 'hidden', }}> <Image source={{ uri: props.currentMessage.video, }} style={{ width, height, borderRadius, resizeMode: 'contain', }} /> </View> ); } A: For react-native": "0.68.2" this version is working for me implementation 'com.facebook.fresco:animated-gif:2.6.0' A: To display an animated GIF in React Native, you can use the <Image> component and specify the animated prop. For example, you can use the following code to display an animated GIF in your React Native app: import React from 'react'; import { Image } from 'react-native'; const MyComponent = () => { return ( <Image source={require('./animated-image.gif')} style={{ width: 200, height: 200 }} animated /> ); }; export default MyComponent;
How do I display an animated gif in React Native?
How can I display an animated gif in react native. This is what I've tried. <Image source={{uri: "loading"}} /> It works fine with a .png file but when I use a .gif file it's blank. I read somewhere to try renaming the .gif to a .png but that just displays one frame of the animated gif with no animation. Any ideas?
[ "For RN < 0.60\nBy default the Gif images are not supported in android react native app.\nYou need to set use Fresco to display the gif images.\nThe code:\nEdit your android/app/build.gradle file and add the following code:\ndependencies: { \n\n ...\n\n compile 'com.facebook.fresco:fresco:1.+'\n\n // For animated GIF support\n compile 'com.facebook.fresco:animated-gif:1.+'\n\n // For WebP support, including animated WebP\n compile 'com.facebook.fresco:animated-webp:1.+'\n compile 'com.facebook.fresco:webpsupport:1.+' \n}\n\nthen you need to bundle the app again, You can display the gif images in two ways like this.\n1-> <Image \n source={require('./../images/load.gif')} \n style={{width: 100, height: 100 }}\n />\n\n2-> <Image \n source={{uri: 'http://www.clicktorelease.com/code/gif/1.gif'}} \n style={{width: 100, height:100 }} \n />\n\nFor RN >= 0.60\nimplementation 'com.facebook.fresco:animated-gif:1.12.0' //instead of\n\nimplementation 'com.facebook.fresco:animated-gif:2.0.0' //use\n\nI hope it is helpful to others,\n", "You need to add the extension and require it this way :\n<Image source={require('./path/to/image/loading.gif')} />\n\nor\n<Image source={{uri: 'http://www.urltogif/image.gif'}} />\n\n", "For React Native 0.60 and higher\nOpen your android/app/build.gradle file and add following lines to first of dependencies section\nimplementation 'com.facebook.fresco:fresco:2.0.0'\nimplementation 'com.facebook.fresco:animated-gif:2.0.0'\n\nAnd then\ncd android\ngradlew clean\nreact-native run-android\n\n", "For me on React native 0.65.1\nThe solution in react-native docs did not work\nI had to use the latest version of Fresco:\nimplementation 'com.facebook.fresco:animated-gif:2.5.0'\nNow GIF works on Android for me.\nYou can check Fresco latest from their website.\n", "For Android You Need to Add Facebook's Fresco Library\nReact Native does not come with Gif support out of the box but you can add Facebook's Fresco library to add this support.\nYou should be able to simply add the following to your build.gradle file: \ncompile 'com.facebook.fresco:animated-gif:0.+'\n\nSpecific Version Compatibility\nIf you are having troubles or you want to use a static version (highly recommended), you can simply go to the following React Native documentation page and replace the 0.46 in the URL with the version of React Native you're running: \nhttps://facebook.github.io/react-native/docs/0.46/image.html#gif-and-webp-support-on-android\n", "if you want to use gif as background image than you can use\n<ImageBackground\n source={yourSourceFile}\n> \n -- your content ---\n</ImageBackground>\n\n", "To add gif and WebP in your project you need some optional modules. If the RN version is <=0.59 then add the following lines in your android/app/build.gradle file.\ndependencies {\n // If your app supports Android versions before Ice Cream Sandwich (API level 14)\n compile 'com.facebook.fresco:animated-base-support:1.10.0'\n\n // For animated GIF support\n compile 'com.facebook.fresco:animated-gif:1.10.0'\n\n // For WebP support, including animated WebP\n compile 'com.facebook.fresco:animated-webp:1.10.0'\n compile 'com.facebook.fresco:webpsupport:1.10.0'\n\n // For WebP support, without animations\n compile 'com.facebook.fresco:webpsupport:1.10.0'\n}\n\nIf the RN version is 0.60 and greater then add the following lines in android/app/build.gradle file\ndependencies {\n // If your app supports Android versions before Ice Cream Sandwich (API level 14)\n implementation 'com.facebook.fresco:animated-base-support:1.10.0'\n\n // For animated GIF support\n implementation 'com.facebook.fresco:animated-gif:1.12.0'\n\n // For WebP support, including animated WebP\n implementation 'com.facebook.fresco:animated-webp:1.10.0'\n implementation 'com.facebook.fresco:webpsupport:1.10.0'\n\n // For WebP support, without animations\n implementation 'com.facebook.fresco:webpsupport:1.10.0'\n}\n\n", "DylanVann / react-native-fast-image is a nice alternative that supports GIFs for both Android (based on glide rather than fresco) and iOS (SDWebImage) with additional features that looks like:\nconst YourImage = () => (\n <FastImage\n style={{ width: 200, height: 200 }}\n source={{\n uri: 'https://unsplash.it/400/400?image=1',\n headers: { Authorization: 'someAuthToken' },\n priority: FastImage.priority.normal,\n }}\n resizeMode={FastImage.resizeMode.contain}\n />\n)\n\n", "\n\nimport React,{useState} from 'react';\r\n\r\n**step1 import from react narive You Can Use (Image) Or (ImageBackground) **\r\n\r\n\r\nimport { StyleSheet, Text, View ,ImageBackground} from 'react-native';\r\n\r\n\r\n\r\n\r\n\r\nfunction LoadingUsers() {\r\n return(<View style={styles.LoadingView}>\r\n\r\n\r\n\r\n**Step 2 require inside source ImageBackground **\r\n\r\n\r\n\r\n<ImageBackground source={require('../assets/stickman.gif')} style={styles.Gif}><Text>Loading..</Text></ImageBackground>\r\n</View>)\r\n}\r\n \r\n\r\n\r\n**Step 3 Set Width ANd height **\r\n\r\n\r\nconst styles = StyleSheet.create({\r\n LoadingView:{\r\n flex:1,\r\n },\r\n Gif:{\r\n flex:1,\r\n width:\"100%\",\r\n height:\"100%\",\r\n justifyContent:\"center\",\r\n alignItems:\"center\",\r\n backgroundColor:'#000',\r\n }\r\n \r\n });\r\n export default LoadingUsers ;\n\n\n\n", "For RN >= 0.66\nEdit your android/app/build.gradle file and add the following code:\nimplementation 'com.facebook.fresco:fresco:2.0.0'\nimplementation 'com.facebook.fresco:animated-gif:2.6.0'\n\n", "In any case you need something else you could use also WebView for it\nrender(props) {\n const width = 220;\n const height = 135;\n const borderRadius = 15;\n const uri = 'https://c.tenor.com/0wj4ApfUlWUAAAAM/whatever-bank-stare.gif';\n // const uri = 'https://c.tenor.com/YwsCGem_MmQAAAAC/parks-and-rec-amy-poehler.gif',;\n // const uri = 'https://media.tenor.com/images/1c39f2d94b02d8c9366de265d0fba8a0/tenor.gif';\n\n return (\n <View\n style={{\n width,\n height,\n borderRadius: 15,\n overflow: 'hidden',\n }}>\n <WebView\n source={{\n uri\n }}\n style={{\n flex: 1,\n width,\n height,\n borderRadius,\n }}\n showsHorizontalScrollIndicator={false}\n showsVerticalScrollIndicator={false}\n injectedJavaScript={`\n document.body.style.width = \"${width}px\";\n document.body.style.height = \"${height}px\";\n document.body.style.backgroundColor = \"${'#fff'}\";\n document.body.style.overflow = \"hidden\";\n const img = document.querySelector(\"img\");\n img.style.position = \"absolute\";\n img.style.top = 0;\n img.style.left = 0;\n img.style.margin = \"auto\";\n img.style[img.offsetWidth > img.offsetHeight ? 'width' : 'height'] = \"100%\";\n img.style.borderRadius = \"${borderRadius}px\";\n `}\n />\n </View>\n );\n}\n\nIt will preserves the gif aspect ratio\nAlso, I did the same with the <Image />. For anyone need it:\nfunction ChatImageGIF(props) {\n const maxWidth = 220;\n const maxHeight = 135;\n const [width, setWidth] = useState(maxWidth);\n const [height, setHeight] = useState(maxHeight);\n const borderRadius = 15;\n\n Image.getSize(props.currentMessage.video, (w, h) => {\n const minWidth = Math.min(maxWidth, w);\n const minHeight = Math.min(maxHeight, h);\n const aspectRatio = (w < h ? w : h) / (w < h ? h : w);\n setWidth(w < h ? minHeight * aspectRatio : minWidth);\n setHeight(w > h ? minWidth * aspectRatio : minHeight);\n });\n\n return (\n <View\n style={{\n width,\n height,\n borderRadius: 15,\n overflow: 'hidden',\n }}>\n <Image\n source={{\n uri: props.currentMessage.video,\n }}\n style={{\n width,\n height,\n borderRadius,\n resizeMode: 'contain',\n }}\n />\n </View>\n );\n}\n\n", "For react-native\": \"0.68.2\" this version is working for me\n\n\nimplementation 'com.facebook.fresco:animated-gif:2.6.0'\n\n\n\n", "To display an animated GIF in React Native, you can use the <Image> component and specify the animated prop. For example, you can use the following code to display an animated GIF in your React Native app:\nimport React from 'react';\nimport { Image } from 'react-native';\n\nconst MyComponent = () => {\n return (\n <Image\n source={require('./animated-image.gif')}\n style={{ width: 200, height: 200 }}\n animated\n />\n );\n};\n\nexport default MyComponent;\n\n" ]
[ 131, 38, 32, 22, 12, 3, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "react_native" ]
stackoverflow_0035594783_react_native.txt
Q: PHP DOMDocument fails if 'table' is inside 'a' I am parsing a website's HTML and there is a 'table' inside an 'a': <?php $dom = new DOMDocument; $dom->loadHTML("<!DOCTYPE html> <html> <head></head> <body> <a> <table><tr><td></td></tr></table> </a> </body> </html>"); if ($dom->getElementsByTagName("table")->item(0)->parentNode->nodeName == "body") echo "Why is table a child of 'body'? It should be a child of 'a'."; I also get this warning: PHP Warning: DOMDocument::loadHTML(): Unexpected end tag : a in Entity, line: ... I am using PHP 7.4. I know 'table's are not officially allowed inside 'a's. BUT: The warning is a completely different message. Making the 'table' a child of 'body' because I've put it inside an 'a' does not make sense. What can I do? I want that at least the table is not a child of body. Because like this I cannot parse sites properly. Edit: Please read the comments under this question. Tables are allowed inside 'a's in this case in HTML5. So this behavior is even more strange. A: When loading HTML content, DOMDocument "fixes" your document. You can see by printing the parsed HTML that the <table> has been moved outside the <a>: echo $dom->saveHTML(); Output (not formatted): <!DOCTYPE html> <html><head></head><body> <a> </a><table><tr><td></td></tr></table></body></html> You can try loading your document as XML instead: $dom->loadXml('your HTML string'); Calling $dom->saveXml() shows the document structure has not changed. You get the correct parent node when fetching the <table>: echo $dom->getElementsByTagName("table")->item(0)->parentNode->nodeName; // Output: a Wild guess about the warning you got (I don't know how it works internally, I can't be sure): The parser sees the opening <a> and then the opening <table>: ...<body><a><table> As it considers having a <table> inside a <a> is "wrong", it closes the <a> before the opening <table>: ...<body><a></a><table> Later in the document, it finds your original closing </a>, alone, which throws the error of "Unexpected end tag" ...<body><a></a><table>...</table></a>
PHP DOMDocument fails if 'table' is inside 'a'
I am parsing a website's HTML and there is a 'table' inside an 'a': <?php $dom = new DOMDocument; $dom->loadHTML("<!DOCTYPE html> <html> <head></head> <body> <a> <table><tr><td></td></tr></table> </a> </body> </html>"); if ($dom->getElementsByTagName("table")->item(0)->parentNode->nodeName == "body") echo "Why is table a child of 'body'? It should be a child of 'a'."; I also get this warning: PHP Warning: DOMDocument::loadHTML(): Unexpected end tag : a in Entity, line: ... I am using PHP 7.4. I know 'table's are not officially allowed inside 'a's. BUT: The warning is a completely different message. Making the 'table' a child of 'body' because I've put it inside an 'a' does not make sense. What can I do? I want that at least the table is not a child of body. Because like this I cannot parse sites properly. Edit: Please read the comments under this question. Tables are allowed inside 'a's in this case in HTML5. So this behavior is even more strange.
[ "When loading HTML content, DOMDocument \"fixes\" your document. You can see by printing the parsed HTML that the <table> has been moved outside the <a>:\necho $dom->saveHTML();\n\nOutput (not formatted):\n<!DOCTYPE html>\n<html><head></head><body>\n <a>\n </a><table><tr><td></td></tr></table></body></html>\n\nYou can try loading your document as XML instead:\n$dom->loadXml('your HTML string');\n\nCalling $dom->saveXml() shows the document structure has not changed.\nYou get the correct parent node when fetching the <table>:\necho $dom->getElementsByTagName(\"table\")->item(0)->parentNode->nodeName;\n// Output: a\n\n\nWild guess about the warning you got (I don't know how it works internally, I can't be sure):\nThe parser sees the opening <a> and then the opening <table>:\n...<body><a><table>\n\nAs it considers having a <table> inside a <a> is \"wrong\", it closes the <a> before the opening <table>:\n...<body><a></a><table>\n\nLater in the document, it finds your original closing </a>, alone, which throws the error of \"Unexpected end tag\"\n...<body><a></a><table>...</table></a>\n\n" ]
[ 0 ]
[]
[]
[ "dom", "php" ]
stackoverflow_0074656718_dom_php.txt
Q: React onclick Argument of type 'EventTarget' is not assignable to parameter of type 'Node' I import MouseEvent from react import { MouseEvent } from 'react'; Use MouseEvent in the following const closeSelectBox = (e: MouseEvent): void => { if (!searchOptionWrapRef.current?.contains(e.target)) { setOpenSelectBox(false) } }; I listen to my closeSelectBox useEffect(() => { document.addEventListener("click", closeSelectBox); return () => { document.removeEventListener("click", closeSelectBox); }; }, []) searchOptionWrapRef is a div const searchOptionWrapRef = useRef<HTMLDivElement>(null); <div ref={searchOptionWrapRef}/> But I get the following error Argument of type 'EventTarget' is not assignable to parameter of type 'Node'. Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more. How do I resolve this type error without using any in place of MouseEvent? A: The event interfaces exported by React are for React event handler props, not addEventListener handlers. For those, don't import MouseEvent from React and you'll get the DOM global interface for it instead, which works with addEventListener. And yes, it's confusing. :-) But the second issue (which actually may be your main issue) is that the DOM global MouseEvent defines target as an EventTarget, not as a Node. In your case, it'll always be a Node (specifically, an Element), but that's how the DOM type is defined. To deal with that, you have at least two choices: Purist You could go really purist (I do) and use a type assertion function to assert that target is a Node: // In a utility library: function assertIsNode(e: EventTarget | null): asserts e is Node { if (!e || !("nodeType" in e)) { throw new Error(`Node expected`); } } // And then in your component: const closeSelectBox = ({target}: MouseEvent): void => { assertIsNode(target); if (!searchOptionWrapRef.current?.contains(target)) { setOpenSelectBox(false); } }; Playground link Concise and Pragmatic You know that target is a Node and isn't null, so you could use a type assertion (target as Node): const closeSelectBox = ({target}: MouseEvent): void => { if (!searchOptionWrapRef.current?.contains(target as Node)) { setOpenSelectBox(false); } }; Playground link I don't like type assertions that aren't checked at runtime (which is what a type assertion function like assertIsNode does), so I'd probably go with the first approach. But in limited situations where you're sure about it, you might consider one. A: You can assert that the instance is of Element or HTMLElement using instanceof. This solution solves both runtime and compile time checking in a minimal way without causing exceptions. const closeSelectBox = (e: MouseEvent): void => { if (e.target instanceof HTMLElement && !searchOptionWrapRef.current?.contains(e.target)) { setOpenSelectBox(false) } }; A: This solve in my use case. I assert to typescript that "target" is of Node type. function handleOutsideClickModal({ target }: MouseEvent) { if (!sidebar.current?.contains(target as Node)) { setOpenModal(!openModal); } }
React onclick Argument of type 'EventTarget' is not assignable to parameter of type 'Node'
I import MouseEvent from react import { MouseEvent } from 'react'; Use MouseEvent in the following const closeSelectBox = (e: MouseEvent): void => { if (!searchOptionWrapRef.current?.contains(e.target)) { setOpenSelectBox(false) } }; I listen to my closeSelectBox useEffect(() => { document.addEventListener("click", closeSelectBox); return () => { document.removeEventListener("click", closeSelectBox); }; }, []) searchOptionWrapRef is a div const searchOptionWrapRef = useRef<HTMLDivElement>(null); <div ref={searchOptionWrapRef}/> But I get the following error Argument of type 'EventTarget' is not assignable to parameter of type 'Node'. Type 'EventTarget' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 43 more. How do I resolve this type error without using any in place of MouseEvent?
[ "The event interfaces exported by React are for React event handler props, not addEventListener handlers. For those, don't import MouseEvent from React and you'll get the DOM global interface for it instead, which works with addEventListener. And yes, it's confusing. :-)\nBut the second issue (which actually may be your main issue) is that the DOM global MouseEvent defines target as an EventTarget, not as a Node. In your case, it'll always be a Node (specifically, an Element), but that's how the DOM type is defined. To deal with that, you have at least two choices:\nPurist\nYou could go really purist (I do) and use a type assertion function to assert that target is a Node:\n// In a utility library:\nfunction assertIsNode(e: EventTarget | null): asserts e is Node {\n if (!e || !(\"nodeType\" in e)) {\n throw new Error(`Node expected`);\n }\n}\n\n// And then in your component:\nconst closeSelectBox = ({target}: MouseEvent): void => {\n assertIsNode(target);\n if (!searchOptionWrapRef.current?.contains(target)) {\n setOpenSelectBox(false);\n }\n};\n\nPlayground link\nConcise and Pragmatic\nYou know that target is a Node and isn't null, so you could use a type assertion (target as Node):\nconst closeSelectBox = ({target}: MouseEvent): void => {\n if (!searchOptionWrapRef.current?.contains(target as Node)) {\n setOpenSelectBox(false);\n }\n};\n\nPlayground link\nI don't like type assertions that aren't checked at runtime (which is what a type assertion function like assertIsNode does), so I'd probably go with the first approach. But in limited situations where you're sure about it, you might consider one.\n", "You can assert that the instance is of Element or HTMLElement using instanceof. This solution solves both runtime and compile time checking in a minimal way without causing exceptions.\nconst closeSelectBox = (e: MouseEvent): void => {\n if (e.target instanceof HTMLElement && !searchOptionWrapRef.current?.contains(e.target)) {\n setOpenSelectBox(false)\n }\n};\n\n", "This solve in my use case. I assert to typescript that \"target\" is of Node type.\nfunction handleOutsideClickModal({ target }: MouseEvent) {\n if (!sidebar.current?.contains(target as Node)) {\n setOpenModal(!openModal);\n }\n}\n\n" ]
[ 25, 1, 0 ]
[]
[]
[ "reactjs", "typescript" ]
stackoverflow_0071193818_reactjs_typescript.txt
Q: C# Trouble changing a method after it has been defined I am very VERY new to all things coding, and I have run into a bit of trouble. I have this method that generates a random number between 1 - 6 (its supposed to simulate a dice roll), and what I want to do is through an input enable the user to change how many sides the dices has (The second parameter of the int nr in this case). I want to be able to change the 7 to any number with a piece of code that is outside the method itself. I can not wrap my head around how I am supposed to accomplish this. static int RullaTärning(Random slumpObjekt) { int nr = slumpObjekt.Next(1, 7); return nr; } Any and all help is appreciated, and if there is some piece of information missing that is needed to solve this, please let me know. Thanks I've tried changing the 7 to an integer variable "sides", but I don't know how to change this integer variable later on in the program. I have tried a load of random stuff without much thought, but I don't know how to accomplish this at all. I really am lost. A: You managed to realize that you need to somehow make the second param to Next method variable. Great! Let's do it: static int RullaTärning(Random slumpObjekt) { int sides = 6; int nr = slumpObjekt.Next(1, sides +1); return nr; } now all you need to do is get the value from the user instead of hardcode it: static int RullaTärning(Random slumpObjekt, int sides) { int nr = slumpObjekt.Next(1, sides+1); return nr; } If you do not want to force the user to choose a side-count (most dice would be 6-sided) you can work with a default: static int RullaTärning(Random slumpObjekt, int sides = 6) { int nr = slumpObjekt.Next(1, sides+1); return nr; } // Can be used as int roll = RullaTärning(rnd); // no second param => 6 will be used // or int damage = RullaTärning(rnd, 16); I would always encourage to check your inputs: static int RullaTärning(Random slumpObjekt, int sides = 6) { // Assuming we had a requirement to allow no less than 6 sides. if( sides < 6 ) throw new ArgumentException("Dice need at least 6 sides.", nameof(sides)); // Mind that I did not check `slumpObjekt` for null, // because a NullReferenceException will be thrown anyway // on the attempt to call `Next` on `null`. int nr = slumpObjekt.Next(1, sides+1); return nr; } // because there is always "that guy" who will try int nonsense = RullaTärning(rnd, -5); ... and a really pedantic fellow just made me mention clean code and "no magic numbers" ... const int MINIMAL_ALLOWED_SIDES = 6; // Now we know why "6" and // we only need to change 1 place in code // if requirement of minimal allowed sides // changes static int RullaTärning(Random slumpObjekt, int sides = MINIMAL_ALLOWED_SIDES) { if( sides < MINIMAL_ALLOWED_SIDES) throw new ArgumentException($"Dice need at least {MINIMAL_ALLOWED_SIDES} sides.", nameof(sides)); int nr = slumpObjekt.Next(1, sides+1); return nr; } A: Pass another parameter to your method: static int RullaTärning(Random slumpObjekt, int sides) { int nr = slumpObjekt.Next(1, sides); return nr; } A: Hope this works for you this is simple method. Please go through basics static int RullaTärning(Random slumpObjekt, int numberOfFaces){ int nr = slumpObjekt.Next(1, numberOfFaces+1); return nr; }
C# Trouble changing a method after it has been defined
I am very VERY new to all things coding, and I have run into a bit of trouble. I have this method that generates a random number between 1 - 6 (its supposed to simulate a dice roll), and what I want to do is through an input enable the user to change how many sides the dices has (The second parameter of the int nr in this case). I want to be able to change the 7 to any number with a piece of code that is outside the method itself. I can not wrap my head around how I am supposed to accomplish this. static int RullaTärning(Random slumpObjekt) { int nr = slumpObjekt.Next(1, 7); return nr; } Any and all help is appreciated, and if there is some piece of information missing that is needed to solve this, please let me know. Thanks I've tried changing the 7 to an integer variable "sides", but I don't know how to change this integer variable later on in the program. I have tried a load of random stuff without much thought, but I don't know how to accomplish this at all. I really am lost.
[ "You managed to realize that you need to somehow make the second param to Next method variable. Great! Let's do it:\nstatic int RullaTärning(Random slumpObjekt)\n{\n int sides = 6;\n int nr = slumpObjekt.Next(1, sides +1); \n return nr;\n}\n\nnow all you need to do is get the value from the user instead of hardcode it:\nstatic int RullaTärning(Random slumpObjekt, int sides)\n{\n int nr = slumpObjekt.Next(1, sides+1); \n return nr;\n}\n\nIf you do not want to force the user to choose a side-count (most dice would be 6-sided) you can work with a default:\nstatic int RullaTärning(Random slumpObjekt, int sides = 6)\n{\n int nr = slumpObjekt.Next(1, sides+1); \n return nr;\n}\n\n// Can be used as\nint roll = RullaTärning(rnd); // no second param => 6 will be used\n// or\nint damage = RullaTärning(rnd, 16);\n\nI would always encourage to check your inputs:\nstatic int RullaTärning(Random slumpObjekt, int sides = 6)\n{\n // Assuming we had a requirement to allow no less than 6 sides.\n if( sides < 6 ) throw new ArgumentException(\"Dice need at least 6 sides.\", nameof(sides));\n // Mind that I did not check `slumpObjekt` for null,\n // because a NullReferenceException will be thrown anyway\n // on the attempt to call `Next` on `null`.\n int nr = slumpObjekt.Next(1, sides+1); \n return nr;\n}\n\n// because there is always \"that guy\" who will try\nint nonsense = RullaTärning(rnd, -5);\n\n... and a really pedantic fellow just made me mention clean code and \"no magic numbers\" ...\nconst int MINIMAL_ALLOWED_SIDES = 6; // Now we know why \"6\" and \n // we only need to change 1 place in code \n // if requirement of minimal allowed sides \n // changes\nstatic int RullaTärning(Random slumpObjekt, int sides = MINIMAL_ALLOWED_SIDES)\n{\n if( sides < MINIMAL_ALLOWED_SIDES) throw new ArgumentException($\"Dice need at least {MINIMAL_ALLOWED_SIDES} sides.\", nameof(sides));\n int nr = slumpObjekt.Next(1, sides+1); \n return nr;\n}\n\n\n", "Pass another parameter to your method:\nstatic int RullaTärning(Random slumpObjekt, int sides)\n{\n int nr = slumpObjekt.Next(1, sides);\n return nr;\n}\n\n", "Hope this works for you this is simple method. Please go through basics\nstatic int RullaTärning(Random slumpObjekt, int numberOfFaces){\nint nr = slumpObjekt.Next(1, numberOfFaces+1); \nreturn nr;\n}\n\n" ]
[ 3, 1, 1 ]
[]
[]
[ "c#", "dice", "methods" ]
stackoverflow_0074656999_c#_dice_methods.txt
Q: Determine the line of code that causes a segmentation fault? How does one determine where the mistake is in the code that causes a segmentation fault? Can my compiler (gcc) show the location of the fault in the program? A: GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this: gcc program.c -g Then use gdb: $ gdb ./a.out (gdb) run <segfault happens here> (gdb) backtrace <offending code is shown here> Here is a nice tutorial to get you started with GDB. Where the segfault occurs is generally only a clue as to where "the mistake which causes" it is in the code. The given location is not necessarily where the problem resides. A: Also, you can give valgrind a try: if you install valgrind and run valgrind --leak-check=full <program> then it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful. A: You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g flag. Whenever you get the message: Segmentation fault (core dumped) a core file is written into your current directory. And you can examine it with the command gdb your_program core_file The file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software. Make sure your system doesn't set the core dump file size to zero. You can set it to unlimited with: ulimit -c unlimited Careful though! that core dumps can become huge. A: There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN). Modern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking. According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example: int main() { volatile int *ptr = (int*)0; *ptr = 0; } $ gcc -g -fsanitize=address main.c $ ./a.out AddressSanitizer:DEADLYSIGNAL ================================================================= ==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0) ==4848==The signal is caused by a WRITE memory access. ==4848==Hint: address points to the zero page. #0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3 #1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a) #2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099) AddressSanitizer can not provide additional info. SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main ==4848==ABORTING The output is slightly more complicated than what gdb would output but there are upsides: There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough. ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process. ¹ That is Clang 3.1+ and GCC 4.8+. A: All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used. If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints. It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing) A: Lucas's answer about core dumps is good. In my .cshrc I have: alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"' to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(. Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file. A: This is a crude way to find the exact line after which there was the segmentation fault. Define line logging function #include \<iostream> void log(int line) { std::cout << line << std::endl; } find and replace all the semicolon after the log function with "; log(_LINE_);" Make sure that the semicolons replaced with functions in the for (;;) loops are removed A: The compiler is much more powerful these days. Before resorting to the use of the debugger, you can also try out these compile options. For me, this identified exactly the line of code where the error occurred and which variable I was accessing out of bounds to cause the segmentation fault error. -O0 -g -Wall -fcheck=all -fbacktrace A: If you have a reproducible exception like segmentation fault, you can use a tool like a debugger to reproduce the error. I used to find source code location for even non-reproducible error. It's based on the Microsoft compiler tool chain. But it's based on a idea. Save the MAP file for each binary (DLL,EXE) before you give it to the customer. If an exception occurs, lookup the address in the MAP file and determine the function whose start address is just below the exception address. As a result you know the function, where the exception occurred. Subtract the function start address from the exception address. The result is the offset in the function. Recompile the source file containing the function with assembly listing enabled. Extract the function's assembly listing. The assembly includes the offset of each instruction in the function. Lookup the source code line, that matches the offset in the function. Evaluate the assembler code for the specific source code line. The offset points exactly the assembler instruction that caused the thrown exception. Evaluate the code of this single source code line. With a bit of experience with the compiler output you can say what caused the exception. Be aware the reason for the exception might be at a totally different location. e.g. the code dereferenced a NULL pointer, but the actual reason, why the pointer is NULL can be somewhere else. The steps 6. and 7. are beneficial since you asked only for the line of code. But I recommend that you should be aware of it. I hope you get a similar environment with the GCC compiler for your platform. If you don't have a usable MAP file, use the tool chain tools to get the addresses of the the function. I am sure the ELF file format supports this.
Determine the line of code that causes a segmentation fault?
How does one determine where the mistake is in the code that causes a segmentation fault? Can my compiler (gcc) show the location of the fault in the program?
[ "GCC can't do that but GDB (a debugger) sure can. Compile you program using the -g switch, like this:\ngcc program.c -g\n\nThen use gdb:\n$ gdb ./a.out\n(gdb) run\n<segfault happens here>\n(gdb) backtrace\n<offending code is shown here>\n\nHere is a nice tutorial to get you started with GDB.\nWhere the segfault occurs is generally only a clue as to where \"the mistake which causes\" it is in the code. The given location is not necessarily where the problem resides.\n", "Also, you can give valgrind a try: if you install valgrind and run\nvalgrind --leak-check=full <program>\n\nthen it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful.\n", "You could also use a core dump and then examine it with gdb. To get useful information you also need to compile with the -g flag.\nWhenever you get the message:\n Segmentation fault (core dumped)\n\na core file is written into your current directory. And you can examine it with the command\n gdb your_program core_file\n\nThe file contains the state of the memory when the program crashed. A core dump can be useful during the deployment of your software. \nMake sure your system doesn't set the core dump file size to zero. You can set it to unlimited with:\nulimit -c unlimited\nCareful though! that core dumps can become huge.\n", "There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).\nModern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking.\nAccording to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:\nint main() {\n volatile int *ptr = (int*)0;\n *ptr = 0;\n}\n\n$ gcc -g -fsanitize=address main.c\n$ ./a.out\nAddressSanitizer:DEADLYSIGNAL\n=================================================================\n==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)\n==4848==The signal is caused by a WRITE memory access.\n==4848==Hint: address points to the zero page.\n #0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3\n #1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)\n #2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)\n\nAddressSanitizer can not provide additional info.\nSUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main\n==4848==ABORTING\n\nThe output is slightly more complicated than what gdb would output but there are upsides:\n\nThere is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.\nASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.\n\n\n¹ That is Clang 3.1+ and GCC 4.8+.\n", "All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.\nIf all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, \"CHECKPOINT REACHED @ %s:%i\\n\", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.\nIt's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)\n", "Lucas's answer about core dumps is good. In my .cshrc I have:\nalias core 'ls -lt core; echo where | gdb -core=core -silent; echo \"\\n\"'\n\nto display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.\nAdded: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.\n", "This is a crude way to find the exact line after which there was the segmentation fault.\n\nDefine line logging function\n\n\n#include \\<iostream> \n\nvoid log(int line) { \nstd::cout << line << std::endl; \n}\n\n\n\nfind and replace all the semicolon after the log function with \"; log(_LINE_);\"\n\nMake sure that the semicolons replaced with functions in the for (;;) loops are removed\n\n\n", "The compiler is much more powerful these days. Before resorting to the use of the debugger, you can also try out these compile options. For me, this identified exactly the line of code where the error occurred and which variable I was accessing out of bounds to cause the segmentation fault error.\n-O0 -g -Wall -fcheck=all -fbacktrace\n\n", "If you have a reproducible exception like segmentation fault, you can use a tool like a debugger to reproduce the error.\nI used to find source code location for even non-reproducible error. It's based on the Microsoft compiler tool chain. But it's based on a idea.\n\nSave the MAP file for each binary (DLL,EXE) before you give it to the customer.\nIf an exception occurs, lookup the address in the MAP file and determine the function whose start address is just below the exception address. As a result you know the function, where the exception occurred.\nSubtract the function start address from the exception address. The result is the offset in the function.\nRecompile the source file containing the function with assembly listing enabled. Extract the function's assembly listing.\nThe assembly includes the offset of each instruction in the function. Lookup the source code line, that matches the offset in the function.\nEvaluate the assembler code for the specific source code line. The offset points exactly the assembler instruction that caused the thrown exception. Evaluate the code of this single source code line. With a bit of experience with the compiler output you can say what caused the exception.\nBe aware the reason for the exception might be at a totally different location. e.g. the code dereferenced a NULL pointer, but the actual reason, why the pointer is NULL can be somewhere else.\n\nThe steps 6. and 7. are beneficial since you asked only for the line of code. But I recommend that you should be aware of it.\nI hope you get a similar environment with the GCC compiler for your platform. If you don't have a usable MAP file, use the tool chain tools to get the addresses of the the function. I am sure the ELF file format supports this.\n" ]
[ 313, 78, 25, 20, 6, 2, 0, 0, 0 ]
[]
[]
[ "c", "c++", "debugging", "segmentation_fault" ]
stackoverflow_0002876357_c_c++_debugging_segmentation_fault.txt
Q: Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error? Is there a workaround for 'ORA-01795: maximum number of expressions in a list is 1000 error' I have a query and it is selecting fields based on the value of one field. I am using the in clause and there are 10000+ values example: select field1, field2, field3 from table1 where name in ( 'value1', 'value2', ... 'value10000+' ); Every time I execute the query I get the ORA-01795: maximum number of expressions in a list is 1000 error. I am trying to execute the query in TOAD, no difference, the same error. How would I modify the query to get it to work? Thanks in advance A: Just use multiple in-clauses to get around this: select field1, field2, field3 from table1 where name in ('value1', 'value2', ..., 'value999') or name in ('value1000', ..., 'value1999') or ...; A: Some workaround solutions are: 1. Split up IN clause Split IN clause to multiple IN clauses where literals are less than 1000 and combine them using OR clauses: Split the original "WHERE" clause from one "IN" condition to several "IN" condition: Select id from x where id in (1, 2, ..., 1000,…,1500); To: Select id from x where id in (1, 2, ..., 999) OR id in (1000,...,1500); 2. Use tuples The limit of 1000 applies to sets of single items: (x) IN ((1), (2), (3), ...). There is no limit if the sets contain two or more items: (x, 0) IN ((1,0), (2,0), (3,0), ...): Select id from x where (x.id, 0) IN ((1, 0), (2, 0), (3, 0),.....(n, 0)); 3. Use temporary table Select id from x where id in (select id from <temporary-table>); A: I ran into this issue recently and figured out a cheeky way of doing it without stringing together additional IN clauses You could make use of Tuples SELECT field1, field2, field3 FROM table1 WHERE (1, name) IN ((1, value1), (1, value2), (1, value3),.....(1, value5000)); Oracle does allow >1000 Tuples but not simple values. More on this here, https://community.oracle.com/message/3515498#3515498 and https://community.oracle.com/thread/958612 This is of course if you don't have the option of using a subquery inside IN to get the values you need from a temp table. A: Please use an inner query inside of the in-clause: select col1, col2, col3... from table1 where id in (select id from table2 where conditions...) A: One more way: CREATE OR REPLACE TYPE TYPE_TABLE_OF_VARCHAR2 AS TABLE OF VARCHAR(100); -- ... SELECT field1, field2, field3 FROM table1 WHERE name IN ( SELECT * FROM table (SELECT CAST(? AS TYPE_TABLE_OF_VARCHAR2) FROM dual) ); I don't consider it's optimal, but it works. The hint /*+ CARDINALITY(...) */ would be very useful because Oracle does not understand cardinality of the array passed and can't estimate optimal execution plan. As another alternative - batch insert into temporary table and using the last in subquery for IN predicate. A: There is another option: with syntax. To use the OPs example, this would look like: with data as ( select 'value1' name from dual union all select 'value2' name from dual union all ... select 'value10000+' name from dual) select field1, field2, field3 from table1 t1 inner join data on t1.name = data.name; I ran into this problem. In my case I had a list of data in Java where each item had an item_id and a customer_id. I have two tables in the DB with subscriptions to items respective customers. I want to get a list of all subscriptions to the items or to the customer for that item, together with the item id. I tried three variants: Multiple selects from Java (using tuples to get around the limit) With-syntax Temporary table Option 1: Multiple Selects from Java Basically, I first select item_id, token from item_subs where (item_id, 0) in ((:item_id_0, 0)...(:item_id_n, 0)) Then select cus_id, token from cus_subs where (cus_id, 0) in ((:cus_id_0, 0)...(:cus_id_n, 0)) Then I build a Map in Java with the cus_id as the key and a list of items as value, and for each found customer subscription I add (to the list returned from the first select) an entry for all relevant items with that item_id. It's much messier code Option 2: With-syntax Get everything at once with an SQL like with data as ( select :item_id_0 item_id, :cus_id_0 cus_id union all ... select :item_id_n item_id, :cus_id_n cus_id ) select I.item_id item_id, I.token token from item_subs I inner join data D on I.item_id = D.item_id union all select D.item_id item_id, C.token token from cus_subs C inner join data D on C.cus_id = D.cus_id Option 3: Temporary table Create a global temporary table with three fields: rownr (primary key), item_id and cus_id. Insert all the data there then run a very similar select to option 2, but linking in the temporary table instead of the with data Performance This is not a fully-scientific performance analysis. I'm running against a development database, with slightly over 1000 rows in my data set that I want to find subscriptions for. I've only tried one data set. I'm not in the same physical location as my DB server. It's not that far away, but I do notice if I try from home over the VPN then it's all much slower, even though it's the same distance (and it's not my home internet that's the problem). I was testing the full call, so my API calls another (also running in the same instance in dev) which also connects to to the DB to get the initial data set. But that is the same in all three cases. YMMV. That said, the temporary table option was much slower. As in double so slow. I was getting 14-15 seconds for option 1, 15-16 for option 2 and 30 for option 3. I'll try them again from the same network as the DB server and check if that changes things when I get the chance. A: I realize this is an old question and referring to TOAD but if you need to code around this using c# you can split up the list through a for loop. You can essentially do the same with Java using subList(); List<Address> allAddresses = GetAllAddresses(); List<Employee> employees = GetAllEmployees(); // count > 1000 List<Address> addresses = new List<Address>(); for (int i = 0; i < employees.Count; i += 1000) { int count = ((employees.Count - i) < 1000) ? (employees.Count - i) - 1 : 1000; var query = (from address in allAddresses where employees.GetRange(i, count).Contains(address.EmployeeId) && address.State == "UT" select address).ToList(); addresses.AddRange(query); } Hope this helps someone. A: there is also another way to resolve this issue. lets say you have two tables Table1 and Table2. and it is required to fetch all entries of Table1 not referred/present in Table2 using Criteria query. So go ahead like this... List list=new ArrayList(); Criteria cr=session.createCriteria(Table1.class); cr.add(Restrictions.sqlRestriction("this_.id not in (select t2.t1_id from Table2 t2 )")); . . . . . It will perform all the subquery function directly in SQL without including 1000 or more parameters in SQL converted by Hibernate framework. It worked for me. Note: You may need to change SQL portion as per your requirement. A: Operato union select * from tableA where tableA.Field1 in (1,2,...999) union select * from tableA where tableA.Field1 in (1000,1001,...1999) union select * from tableA where tableA.Field1 in (2000,2001,...2999) A: **Divide a list to lists of n size** import java.util.AbstractList; import java.util.ArrayList; import java.util.List; public final class PartitionUtil<T> extends AbstractList<List<T>> { private final List<T> list; private final int chunkSize; private PartitionUtil(List<T> list, int chunkSize) { this.list = new ArrayList<>(list); this.chunkSize = chunkSize; } public static <T> PartitionUtil<T> ofSize(List<T> list, int chunkSize) { return new PartitionUtil<>(list, chunkSize); } @Override public List<T> get(int index) { int start = index * chunkSize; int end = Math.min(start + chunkSize, list.size()); if (start > end) { throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">"); } return new ArrayList<>(list.subList(start, end)); } @Override public int size() { return (int) Math.ceil((double) list.size() / (double) chunkSize); } } Function call : List<List<String>> containerNumChunks = PartitionUtil.ofSize(list, 999) more details: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/ A: There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework. select * from tableA where id = 1 or id = 2 or id = 3 ... But for better perfo, I would use Nikolai Nechai's solution with unions, if possible. A: Pass the list and the number of records needs to return in the loop most cases = 999. List<List<Long>> getSubLists = batchList(inputList, 999); List<Long> newList = new ArrayList<>(); for (List<Long> subSet : getSubLists) { newList.addALL(daoCall) // add in the required list in loop } public static <T> List<List<T>> batchList(List<T> inputList, final int maxSize) { List<List<T>> sublists = new ArrayList<>(); final int size = inputList.size(); for (int i = 0; i < size; i += maxSize) { sublists.add(new ArrayList<>(inputList.subList(i, Math.min(size, i + maxSize)))); } return sublists; } A: Use Tuple : Let's suppose input is : List<Long> userIdList = Arrays.asList(100L,200L,300L); StringBuilder tuple = new StringBuilder(); for(Long userId : userIdList) { tuple.append("(1,").append(userId).append("),"); } tuple.deleteCharAt(tuple.length()-1); Output will be : (1,100),(1,200),(1,300) And we can pass this to below query like this (And YES, we can pass more than 1000 elements): SELECT * FROM MyTable WHERE (1, USR_ID) IN ((1,100),(1,200),(1,300)); A: ORA-01795: maximum number of expressions in a list is 1000. Issue: When user selects long list of values (greate or qual to 1000 values/expression) for IN/OR list of where clause, system throws error: “ORA-01795: maximum number of expressions in a list is 1000” Root Cause: Oracle IN / OR list has limit of 1000 (actually its 999) number of expression/value list. Proposed Solution: You need to split the list of expressions into multiple sets (using OR) and each should be less than 1000 list/expressoin combine using IN / Or list. Example: Suppose you have a table ABC with column ZIP of CLOB type and table contains more than 1000 rows. You need to break them in multiple list, like shown below: ( ZIP IN (1,2,3,.........N999) OR ZIP IN (1000,1001,......N999) ..... ..... ) A: If you are using Hibernate Query Language(HQL) in your repository class and using IN clause, Oracle database is not going to be let you run your query. Because you are giving more then 1000 value. Oracle in clause limit is 1000. So you cannot give more then 1000 value to your IN clause. In java, you can use this codes. It's going to be very help full. You can call your services like this, and in this example limit is 750. Don't write more than 1000. Happy coding. import java.util.List; public class ListUtils { public static int getPeriodCount(List<?> list, int limit) { int size = list.size(); int leap = size % limit; int periodCount = leap != 0 ? (size / limit) + 1 : (size / limit); return periodCount; } } public class MainClass { private static final int LIMIT = 750; private List<GivenObject> getList(List<Integer> numbers) { if (CollectionUtils.isEmpty(numbers)) { return Collections.emptyList(); } List<Integer> resultList= new ArrayList<>(); int startIndex = 0; int periodCount = ListUtils.getPeriodCount(numbers, LIMIT); for (int i = 1; i <= periodCount; i++) { List<Integer> collectedNumbers = numbers.stream() .skip(startIndex) .limit(LIMIT) .collect(Collectors.toList()); resultList.addAll(collectedNumbers); startIndex += LIMIT; } return resultList; } }
Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?
Is there a workaround for 'ORA-01795: maximum number of expressions in a list is 1000 error' I have a query and it is selecting fields based on the value of one field. I am using the in clause and there are 10000+ values example: select field1, field2, field3 from table1 where name in ( 'value1', 'value2', ... 'value10000+' ); Every time I execute the query I get the ORA-01795: maximum number of expressions in a list is 1000 error. I am trying to execute the query in TOAD, no difference, the same error. How would I modify the query to get it to work? Thanks in advance
[ "Just use multiple in-clauses to get around this:\nselect field1, field2, field3 from table1 \nwhere name in ('value1', 'value2', ..., 'value999') \n or name in ('value1000', ..., 'value1999') \n or ...;\n\n", "Some workaround solutions are:\n1. Split up IN clause\nSplit IN clause to multiple IN clauses where literals are less than 1000 and combine them using OR clauses: \nSplit the original \"WHERE\" clause from one \"IN\" condition to several \"IN\" condition:\nSelect id from x where id in (1, 2, ..., 1000,…,1500);\n\nTo:\nSelect id from x where id in (1, 2, ..., 999) OR id in (1000,...,1500);\n\n2. Use tuples\nThe limit of 1000 applies to sets of single items: (x) IN ((1), (2), (3), ...).\nThere is no limit if the sets contain two or more items: (x, 0) IN ((1,0), (2,0), (3,0), ...):\nSelect id from x where (x.id, 0) IN ((1, 0), (2, 0), (3, 0),.....(n, 0));\n\n3. Use temporary table\nSelect id from x where id in (select id from <temporary-table>);\n\n", "I ran into this issue recently and figured out a cheeky way of doing it without stringing together additional IN clauses\nYou could make use of Tuples\nSELECT field1, field2, field3\nFROM table1\nWHERE (1, name) IN ((1, value1), (1, value2), (1, value3),.....(1, value5000));\n\nOracle does allow >1000 Tuples but not simple values. More on this here, \nhttps://community.oracle.com/message/3515498#3515498\nand\nhttps://community.oracle.com/thread/958612 \nThis is of course if you don't have the option of using a subquery inside IN to get the values you need from a temp table.\n", "Please use an inner query inside of the in-clause:\nselect col1, col2, col3... from table1\n where id in (select id from table2 where conditions...)\n\n", "One more way:\nCREATE OR REPLACE TYPE TYPE_TABLE_OF_VARCHAR2 AS TABLE OF VARCHAR(100);\n-- ...\nSELECT field1, field2, field3\n FROM table1\n WHERE name IN (\n SELECT * FROM table (SELECT CAST(? AS TYPE_TABLE_OF_VARCHAR2) FROM dual)\n );\n\nI don't consider it's optimal, but it works. The hint /*+ CARDINALITY(...) */ would be very useful because Oracle does not understand cardinality of the array passed and can't estimate optimal execution plan.\nAs another alternative - batch insert into temporary table and using the last in subquery for IN predicate.\n", "There is another option: with syntax. To use the OPs example, this would look like:\nwith data as (\n select 'value1' name from dual\n union all\n select 'value2' name from dual\n union all\n...\n select 'value10000+' name from dual)\nselect field1, field2, field3 \nfrom table1 t1\ninner join data on t1.name = data.name;\n\nI ran into this problem. In my case I had a list of data in Java where each item had an item_id and a customer_id. I have two tables in the DB with subscriptions to items respective customers. I want to get a list of all subscriptions to the items or to the customer for that item, together with the item id.\nI tried three variants:\n\nMultiple selects from Java (using tuples to get around the limit)\nWith-syntax\nTemporary table\n\nOption 1: Multiple Selects from Java\nBasically, I first \nselect item_id, token \nfrom item_subs \nwhere (item_id, 0) in ((:item_id_0, 0)...(:item_id_n, 0))\n\nThen\nselect cus_id, token \nfrom cus_subs \nwhere (cus_id, 0) in ((:cus_id_0, 0)...(:cus_id_n, 0))\n\nThen I build a Map in Java with the cus_id as the key and a list of items as value, and for each found customer subscription I add (to the list returned from the first select) an entry for all relevant items with that item_id. It's much messier code\nOption 2: With-syntax\nGet everything at once with an SQL like\nwith data as (\n select :item_id_0 item_id, :cus_id_0 cus_id\n union all\n ...\n select :item_id_n item_id, :cus_id_n cus_id )\nselect I.item_id item_id, I.token token\nfrom item_subs I\ninner join data D on I.item_id = D.item_id\nunion all\nselect D.item_id item_id, C.token token\nfrom cus_subs C\ninner join data D on C.cus_id = D.cus_id\n\nOption 3: Temporary table\nCreate a global temporary table with three fields: rownr (primary key), item_id and cus_id. Insert all the data there then run a very similar select to option 2, but linking in the temporary table instead of the with data\nPerformance\nThis is not a fully-scientific performance analysis. \n\nI'm running against a development database, with slightly over 1000 rows in my data set that I want to find subscriptions for. \nI've only tried one data set. \nI'm not in the same physical location as my DB server. It's not that far away, but I do notice if I try from home over the VPN then it's all much slower, even though it's the same distance (and it's not my home internet that's the problem). \nI was testing the full call, so my API calls another (also running in the same instance in dev) which also connects to to the DB to get the initial data set. But that is the same in all three cases.\n\nYMMV.\nThat said, the temporary table option was much slower. As in double so slow. I was getting 14-15 seconds for option 1, 15-16 for option 2 and 30 for option 3.\nI'll try them again from the same network as the DB server and check if that changes things when I get the chance.\n", "I realize this is an old question and referring to TOAD but if you need to code around this using c# you can split up the list through a for loop. You can essentially do the same with Java using subList();\n List<Address> allAddresses = GetAllAddresses();\n List<Employee> employees = GetAllEmployees(); // count > 1000\n\n List<Address> addresses = new List<Address>();\n\n for (int i = 0; i < employees.Count; i += 1000)\n {\n int count = ((employees.Count - i) < 1000) ? (employees.Count - i) - 1 : 1000;\n var query = (from address in allAddresses\n where employees.GetRange(i, count).Contains(address.EmployeeId)\n && address.State == \"UT\"\n select address).ToList();\n\n addresses.AddRange(query);\n }\n\nHope this helps someone.\n", "there is also another way to resolve this issue. lets say you have two tables Table1 and Table2. and it is required to fetch all entries of Table1 not referred/present in Table2 using Criteria query. So go ahead like this...\nList list=new ArrayList(); \nCriteria cr=session.createCriteria(Table1.class);\ncr.add(Restrictions.sqlRestriction(\"this_.id not in (select t2.t1_id from Table2 t2 )\"));\n.\n.\n\n. . . It will perform all the subquery function directly in SQL without including 1000 or more parameters in SQL converted by Hibernate framework. It worked for me. Note: You may need to change SQL portion as per your requirement.\n", "Operato union\nselect * from tableA where tableA.Field1 in (1,2,...999)\nunion\nselect * from tableA where tableA.Field1 in (1000,1001,...1999)\nunion\nselect * from tableA where tableA.Field1 in (2000,2001,...2999)\n\n", " **Divide a list to lists of n size**\n\n import java.util.AbstractList;\n import java.util.ArrayList;\n import java.util.List;\n\n public final class PartitionUtil<T> extends AbstractList<List<T>> {\n\n private final List<T> list;\n private final int chunkSize;\n\n private PartitionUtil(List<T> list, int chunkSize) {\n this.list = new ArrayList<>(list);\n this.chunkSize = chunkSize;\n }\n\n public static <T> PartitionUtil<T> ofSize(List<T> list, int chunkSize) {\n return new PartitionUtil<>(list, chunkSize);\n }\n\n @Override\n public List<T> get(int index) {\n int start = index * chunkSize;\n int end = Math.min(start + chunkSize, list.size());\n\n if (start > end) {\n throw new IndexOutOfBoundsException(\"Index \" + index + \" is out of the list range <0,\" + (size() - 1) + \">\");\n }\n\n return new ArrayList<>(list.subList(start, end));\n }\n\n @Override\n public int size() {\n return (int) Math.ceil((double) list.size() / (double) chunkSize);\n }\n }\n\n\n\n\n\nFunction call : \n List<List<String>> containerNumChunks = PartitionUtil.ofSize(list, 999)\n\nmore details: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/\n", "There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.\nselect * from tableA where id = 1 or id = 2 or id = 3 ...\n\nBut for better perfo, I would use Nikolai Nechai's solution with unions, if possible.\n", "Pass the list and the number of records needs to return in the loop most cases = 999.\nList<List<Long>> getSubLists = batchList(inputList, 999);\nList<Long> newList = new ArrayList<>();\nfor (List<Long> subSet : getSubLists) { newList.addALL(daoCall) // add in the required list in loop }\n\n public static <T> List<List<T>> batchList(List<T> inputList, final int maxSize) {\n List<List<T>> sublists = new ArrayList<>();\n final int size = inputList.size();\n for (int i = 0; i < size; i += maxSize) {\n sublists.add(new ArrayList<>(inputList.subList(i, Math.min(size, i + maxSize))));\n }\n return sublists;\n}\n\n\n\n\n\n\n\n\n \n\n", "Use Tuple :\nLet's suppose input is :\nList<Long> userIdList = Arrays.asList(100L,200L,300L);\n\nStringBuilder tuple = new StringBuilder();\nfor(Long userId : userIdList) {\n tuple.append(\"(1,\").append(userId).append(\"),\");\n}\ntuple.deleteCharAt(tuple.length()-1);\n\nOutput will be :\n(1,100),(1,200),(1,300)\nAnd we can pass this to below query like this (And YES, we can pass more than 1000 elements):\nSELECT * FROM MyTable WHERE (1, USR_ID) IN ((1,100),(1,200),(1,300));\n\n", "ORA-01795: maximum number of expressions in a list is 1000.\nIssue:\nWhen user selects long list of values (greate or qual to 1000 values/expression) for IN/OR list of where clause, system throws error: “ORA-01795: maximum number of expressions in a list is 1000”\nRoot Cause:\nOracle IN / OR list has limit of 1000 (actually its 999) number of expression/value list.\nProposed Solution:\nYou need to split the list of expressions into multiple sets (using OR) and each should be less than 1000 list/expressoin combine using IN / Or list.\nExample:\nSuppose you have a table ABC with column ZIP of CLOB type and table contains more than 1000 rows.\nYou need to break them in multiple list, like shown below:\n( ZIP IN (1,2,3,.........N999)\nOR ZIP IN (1000,1001,......N999)\n.....\n.....\n)\n", "If you are using Hibernate Query Language(HQL) in your repository class and using IN clause, Oracle database is not going to be let you run your query. Because you are giving more then 1000 value. Oracle in clause limit is 1000. So you cannot give more then 1000 value to your IN clause.\nIn java, you can use this codes. It's going to be very help full. You can call your services like this, and in this example limit is 750.\nDon't write more than 1000. Happy coding.\n import java.util.List;\n \n public class ListUtils {\n \n public static int getPeriodCount(List<?> list, int limit) {\n int size = list.size();\n int leap = size % limit;\n int periodCount = leap != 0 ? (size / limit) + 1 : (size / limit);\n return periodCount;\n }\n }\n\n public class MainClass {\n\n private static final int LIMIT = 750;\n\n private List<GivenObject> getList(List<Integer> numbers) {\n if (CollectionUtils.isEmpty(numbers)) {\n return Collections.emptyList();\n }\n List<Integer> resultList= new ArrayList<>();\n int startIndex = 0;\n\n int periodCount = ListUtils.getPeriodCount(numbers, LIMIT);\n\n for (int i = 1; i <= periodCount; i++) {\n List<Integer> collectedNumbers = numbers.stream()\n .skip(startIndex)\n .limit(LIMIT)\n .collect(Collectors.toList());\n resultList.addAll(collectedNumbers);\n startIndex += LIMIT;\n }\n return resultList;\n }\n}\n\n" ]
[ 145, 47, 26, 7, 7, 5, 4, 3, 3, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "sql", "toad" ]
stackoverflow_0017842453_sql_toad.txt
Q: File "/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) I read previous answers but couldnt fix this. whenever I run the code, this error pops up at different epochs, sometimes the executu=ion goes till 50s and then suddenly this error appears and the execution stops. at some other times this error appears at epoch 16s and so on. 0it [00:00, ?it/s]/usr/local/lib/python3.8/dist-packages/torch/nn/functional.py:1960: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. warnings.warn("nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.") 185it [00:07, 23.88it/s] Traceback (most recent call last): File "/content/drive/MyDrive/train.py", line 241, in <module> train() File "/content/drive/MyDrive/train.py", line 98, in train text_aligned_match, image_aligned_match, pred_similarity_match = similarity_module(fixed_text, matched_image) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl return forward_call(*input, **kwargs) File "/content/drive/MyDrive/model.py", line 106, in forward text_encoding, image_encoding = self.encoding(text, image) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl return forward_call(*input, **kwargs) File "/content/drive/MyDrive/model.py", line 70, in forward text_encoding = self.shared_text_encoding(text) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl return forward_call(*input, **kwargs) File "/content/drive/MyDrive/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) The line creating issue is x_out = torch.cat(x_out, 1) Code is: import math import random from random import random, seed import torch import torch.nn as nn from torch.distributions import Normal, Independent from torch.nn.functional import softplus #random.seed(825) seed(825) class FastCNN(nn.Module): # a CNN-based altertative approach of bert for text encoding def __init__(self, channel=32, kernel_size=(1, 2, 4, 8)): super(FastCNN, self).__init__() self.fast_cnn = nn.ModuleList() for kernel in kernel_size: self.fast_cnn.append( nn.Sequential( nn.Conv1d(200, channel, kernel_size=kernel), nn.BatchNorm1d(channel), nn.ReLU(), nn.AdaptiveMaxPool1d(1) ) ) def forward(self, x): x = x.permute(0, 2, 1) x_out = [] for module in self.fast_cnn: x_out.append(module(x).squeeze()) x_out = torch.cat(x_out, 1) return x_out class EncodingPart(nn.Module): def __init__( self, cnn_channel=32, cnn_kernel_size=(1, 2, 4, 8), shared_image_dim=128, shared_text_dim=128 ): super(EncodingPart, self).__init__() self.shared_text_encoding = FastCNN( channel=cnn_channel, kernel_size=cnn_kernel_size ) self.shared_text_linear = nn.Sequential( nn.Linear(128, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Dropout(), nn.Linear(64, shared_text_dim), nn.BatchNorm1d(shared_text_dim), nn.ReLU() ) self.shared_image = nn.Sequential( nn.Linear(512, 256), nn.BatchNorm1d(256), nn.ReLU(), nn.Dropout(), nn.Linear(256, shared_image_dim), nn.BatchNorm1d(shared_image_dim), nn.ReLU() ) def forward(self, text, image): text_encoding = self.shared_text_encoding(text) text_shared = self.shared_text_linear(text_encoding) image_shared = self.shared_image(image) return text_shared, image_shared class SimilarityModule(nn.Module): def __init__(self, shared_dim=128, sim_dim=64): super(SimilarityModule, self).__init__() self.encoding = EncodingPart() self.text_aligner = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, sim_dim), nn.BatchNorm1d(sim_dim), nn.ReLU() ) self.image_aligner = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, sim_dim), nn.BatchNorm1d(sim_dim), nn.ReLU() ) self.sim_classifier_dim = sim_dim * 2 self.sim_classifier = nn.Sequential( nn.BatchNorm1d(self.sim_classifier_dim), nn.Linear(self.sim_classifier_dim, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Linear(64, 2) ) def forward(self, text, image): text_encoding, image_encoding = self.encoding(text, image) text_aligned = self.text_aligner(text_encoding) image_aligned = self.image_aligner(image_encoding) sim_feature = torch.cat([text_aligned, image_aligned], 1) pred_similarity = self.sim_classifier(sim_feature) return text_aligned, image_aligned, pred_similarity class Encoder(nn.Module): def __init__(self, z_dim=2): super(Encoder, self).__init__() self.z_dim = z_dim # Vanilla MLP self.net = nn.Sequential( nn.Linear(64, 64), nn.ReLU(True), nn.Linear(64, z_dim * 2), ) def forward(self, x): # x = x.view(x.size(0), -1) # Flatten the input params = self.net(x) mu, sigma = params[:, :self.z_dim], params[:, self.z_dim:] sigma = softplus(sigma) + 1e-7 return Independent(Normal(loc=mu, scale=sigma), 1) class AmbiguityLearning(nn.Module): def __init__(self): super(AmbiguityLearning, self).__init__() self.encoding = EncodingPart() self.encoder_text = Encoder() self.encoder_image = Encoder() def forward(self, text_encoding, image_encoding): # text_encoding, image_encoding = self.encoding(text, image) p_z1_given_text = self.encoder_text(text_encoding) p_z2_given_image = self.encoder_image(image_encoding) z1 = p_z1_given_text.rsample() z2 = p_z2_given_image.rsample() kl_1_2 = p_z1_given_text.log_prob(z1) - p_z2_given_image.log_prob(z1) kl_2_1 = p_z2_given_image.log_prob(z2) - p_z1_given_text.log_prob(z2) skl = (kl_1_2 + kl_2_1)/ 2. skl = nn.functional.sigmoid(skl) return skl class UnimodalDetection(nn.Module): def __init__(self, shared_dim=128, prime_dim = 16): super(UnimodalDetection, self).__init__() self.text_uni = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, prime_dim), nn.BatchNorm1d(prime_dim), nn.ReLU() ) self.image_uni = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, prime_dim), nn.BatchNorm1d(prime_dim), nn.ReLU() ) def forward(self, text_encoding, image_encoding): text_prime = self.text_uni(text_encoding) image_prime = self.image_uni(image_encoding) return text_prime, image_prime class CrossModule4Batch(nn.Module): def __init__(self, text_in_dim=64, image_in_dim=64, corre_out_dim=64): super(CrossModule4Batch, self).__init__() self.softmax = nn.Softmax(-1) self.corre_dim = 64 self.pooling = nn.AdaptiveMaxPool1d(1) self.c_specific_2 = nn.Sequential( nn.Linear(self.corre_dim, corre_out_dim), nn.BatchNorm1d(corre_out_dim), nn.ReLU() ) def forward(self, text, image): text_in = text.unsqueeze(2) image_in = image.unsqueeze(1) corre_dim = text.shape[1] similarity = torch.matmul(text_in, image_in) / math.sqrt(corre_dim) correlation = self.softmax(similarity) correlation_p = self.pooling(correlation).squeeze() correlation_out = self.c_specific_2(correlation_p) return correlation_out class DetectionModule(nn.Module): def __init__(self, feature_dim=64+16+16, h_dim=64): super(DetectionModule, self).__init__() self.encoding = EncodingPart() self.ambiguity_module = AmbiguityLearning() self.uni_repre = UnimodalDetection() self.cross_module = CrossModule4Batch() self.classifier_corre = nn.Sequential( nn.Linear(feature_dim, h_dim), nn.BatchNorm1d(h_dim), nn.ReLU(), # nn.Dropout(), nn.Linear(h_dim, h_dim), nn.BatchNorm1d(h_dim), nn.ReLU(), # nn.Dropout(), nn.Linear(h_dim, 2) ) def forward(self, text_raw, image_raw, text, image): # text_encoding, image_encoding = self.encoding_module(text, image) skl = self.ambiguity_module(text, image) text_prime, image_prime = self.encoding(text_raw, image_raw) text_prime, image_prime = self.uni_repre(text_prime, image_prime) correlation = self.cross_module(text, image) weight_uni = (1-skl).unsqueeze(1) weight_corre = skl.unsqueeze(1) text_final = weight_uni * text_prime img_final = weight_uni * image_prime corre_final = weight_corre * correlation final_corre = torch.cat([text_final, img_final, corre_final], 1) pre_label = self.classifier_corre(final_corre) return pre_label I am new to this domain, please suggest a fix. A: x_out has a single dimension after the squeeze operation (I assume, hard to say from your code). Try printing x_out.shape to check. In this case, the solution would be torch.cat(x_out,dim = 0). You may save yourself some code comprehension headaches by not performing the squeeze operation until the end. For instance, if each output i in x_out has some dimension [1,d_i], it's straightforward to see that you want to concatenate along dimension 1. Then you can squeeze x_out at the very end.
File "/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
I read previous answers but couldnt fix this. whenever I run the code, this error pops up at different epochs, sometimes the executu=ion goes till 50s and then suddenly this error appears and the execution stops. at some other times this error appears at epoch 16s and so on. 0it [00:00, ?it/s]/usr/local/lib/python3.8/dist-packages/torch/nn/functional.py:1960: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. warnings.warn("nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.") 185it [00:07, 23.88it/s] Traceback (most recent call last): File "/content/drive/MyDrive/train.py", line 241, in <module> train() File "/content/drive/MyDrive/train.py", line 98, in train text_aligned_match, image_aligned_match, pred_similarity_match = similarity_module(fixed_text, matched_image) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl return forward_call(*input, **kwargs) File "/content/drive/MyDrive/model.py", line 106, in forward text_encoding, image_encoding = self.encoding(text, image) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl return forward_call(*input, **kwargs) File "/content/drive/MyDrive/model.py", line 70, in forward text_encoding = self.shared_text_encoding(text) File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1130, in _call_impl return forward_call(*input, **kwargs) File "/content/drive/MyDrive/model.py", line 33, in forward x_out = torch.cat(x_out, 1) IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1) The line creating issue is x_out = torch.cat(x_out, 1) Code is: import math import random from random import random, seed import torch import torch.nn as nn from torch.distributions import Normal, Independent from torch.nn.functional import softplus #random.seed(825) seed(825) class FastCNN(nn.Module): # a CNN-based altertative approach of bert for text encoding def __init__(self, channel=32, kernel_size=(1, 2, 4, 8)): super(FastCNN, self).__init__() self.fast_cnn = nn.ModuleList() for kernel in kernel_size: self.fast_cnn.append( nn.Sequential( nn.Conv1d(200, channel, kernel_size=kernel), nn.BatchNorm1d(channel), nn.ReLU(), nn.AdaptiveMaxPool1d(1) ) ) def forward(self, x): x = x.permute(0, 2, 1) x_out = [] for module in self.fast_cnn: x_out.append(module(x).squeeze()) x_out = torch.cat(x_out, 1) return x_out class EncodingPart(nn.Module): def __init__( self, cnn_channel=32, cnn_kernel_size=(1, 2, 4, 8), shared_image_dim=128, shared_text_dim=128 ): super(EncodingPart, self).__init__() self.shared_text_encoding = FastCNN( channel=cnn_channel, kernel_size=cnn_kernel_size ) self.shared_text_linear = nn.Sequential( nn.Linear(128, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Dropout(), nn.Linear(64, shared_text_dim), nn.BatchNorm1d(shared_text_dim), nn.ReLU() ) self.shared_image = nn.Sequential( nn.Linear(512, 256), nn.BatchNorm1d(256), nn.ReLU(), nn.Dropout(), nn.Linear(256, shared_image_dim), nn.BatchNorm1d(shared_image_dim), nn.ReLU() ) def forward(self, text, image): text_encoding = self.shared_text_encoding(text) text_shared = self.shared_text_linear(text_encoding) image_shared = self.shared_image(image) return text_shared, image_shared class SimilarityModule(nn.Module): def __init__(self, shared_dim=128, sim_dim=64): super(SimilarityModule, self).__init__() self.encoding = EncodingPart() self.text_aligner = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, sim_dim), nn.BatchNorm1d(sim_dim), nn.ReLU() ) self.image_aligner = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, sim_dim), nn.BatchNorm1d(sim_dim), nn.ReLU() ) self.sim_classifier_dim = sim_dim * 2 self.sim_classifier = nn.Sequential( nn.BatchNorm1d(self.sim_classifier_dim), nn.Linear(self.sim_classifier_dim, 64), nn.BatchNorm1d(64), nn.ReLU(), nn.Linear(64, 2) ) def forward(self, text, image): text_encoding, image_encoding = self.encoding(text, image) text_aligned = self.text_aligner(text_encoding) image_aligned = self.image_aligner(image_encoding) sim_feature = torch.cat([text_aligned, image_aligned], 1) pred_similarity = self.sim_classifier(sim_feature) return text_aligned, image_aligned, pred_similarity class Encoder(nn.Module): def __init__(self, z_dim=2): super(Encoder, self).__init__() self.z_dim = z_dim # Vanilla MLP self.net = nn.Sequential( nn.Linear(64, 64), nn.ReLU(True), nn.Linear(64, z_dim * 2), ) def forward(self, x): # x = x.view(x.size(0), -1) # Flatten the input params = self.net(x) mu, sigma = params[:, :self.z_dim], params[:, self.z_dim:] sigma = softplus(sigma) + 1e-7 return Independent(Normal(loc=mu, scale=sigma), 1) class AmbiguityLearning(nn.Module): def __init__(self): super(AmbiguityLearning, self).__init__() self.encoding = EncodingPart() self.encoder_text = Encoder() self.encoder_image = Encoder() def forward(self, text_encoding, image_encoding): # text_encoding, image_encoding = self.encoding(text, image) p_z1_given_text = self.encoder_text(text_encoding) p_z2_given_image = self.encoder_image(image_encoding) z1 = p_z1_given_text.rsample() z2 = p_z2_given_image.rsample() kl_1_2 = p_z1_given_text.log_prob(z1) - p_z2_given_image.log_prob(z1) kl_2_1 = p_z2_given_image.log_prob(z2) - p_z1_given_text.log_prob(z2) skl = (kl_1_2 + kl_2_1)/ 2. skl = nn.functional.sigmoid(skl) return skl class UnimodalDetection(nn.Module): def __init__(self, shared_dim=128, prime_dim = 16): super(UnimodalDetection, self).__init__() self.text_uni = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, prime_dim), nn.BatchNorm1d(prime_dim), nn.ReLU() ) self.image_uni = nn.Sequential( nn.Linear(shared_dim, shared_dim), nn.BatchNorm1d(shared_dim), nn.ReLU(), nn.Linear(shared_dim, prime_dim), nn.BatchNorm1d(prime_dim), nn.ReLU() ) def forward(self, text_encoding, image_encoding): text_prime = self.text_uni(text_encoding) image_prime = self.image_uni(image_encoding) return text_prime, image_prime class CrossModule4Batch(nn.Module): def __init__(self, text_in_dim=64, image_in_dim=64, corre_out_dim=64): super(CrossModule4Batch, self).__init__() self.softmax = nn.Softmax(-1) self.corre_dim = 64 self.pooling = nn.AdaptiveMaxPool1d(1) self.c_specific_2 = nn.Sequential( nn.Linear(self.corre_dim, corre_out_dim), nn.BatchNorm1d(corre_out_dim), nn.ReLU() ) def forward(self, text, image): text_in = text.unsqueeze(2) image_in = image.unsqueeze(1) corre_dim = text.shape[1] similarity = torch.matmul(text_in, image_in) / math.sqrt(corre_dim) correlation = self.softmax(similarity) correlation_p = self.pooling(correlation).squeeze() correlation_out = self.c_specific_2(correlation_p) return correlation_out class DetectionModule(nn.Module): def __init__(self, feature_dim=64+16+16, h_dim=64): super(DetectionModule, self).__init__() self.encoding = EncodingPart() self.ambiguity_module = AmbiguityLearning() self.uni_repre = UnimodalDetection() self.cross_module = CrossModule4Batch() self.classifier_corre = nn.Sequential( nn.Linear(feature_dim, h_dim), nn.BatchNorm1d(h_dim), nn.ReLU(), # nn.Dropout(), nn.Linear(h_dim, h_dim), nn.BatchNorm1d(h_dim), nn.ReLU(), # nn.Dropout(), nn.Linear(h_dim, 2) ) def forward(self, text_raw, image_raw, text, image): # text_encoding, image_encoding = self.encoding_module(text, image) skl = self.ambiguity_module(text, image) text_prime, image_prime = self.encoding(text_raw, image_raw) text_prime, image_prime = self.uni_repre(text_prime, image_prime) correlation = self.cross_module(text, image) weight_uni = (1-skl).unsqueeze(1) weight_corre = skl.unsqueeze(1) text_final = weight_uni * text_prime img_final = weight_uni * image_prime corre_final = weight_corre * correlation final_corre = torch.cat([text_final, img_final, corre_final], 1) pre_label = self.classifier_corre(final_corre) return pre_label I am new to this domain, please suggest a fix.
[ "x_out has a single dimension after the squeeze operation (I assume, hard to say from your code). Try printing x_out.shape to check. In this case, the solution would be torch.cat(x_out,dim = 0).\nYou may save yourself some code comprehension headaches by not performing the squeeze operation until the end. For instance, if each output i in x_out has some dimension [1,d_i], it's straightforward to see that you want to concatenate along dimension 1. Then you can squeeze x_out at the very end.\n" ]
[ 0 ]
[]
[]
[ "machine_learning", "python", "pytorch" ]
stackoverflow_0074656868_machine_learning_python_pytorch.txt
Q: android studio gradle sync issues help plz I tried to import the project written around 2016, but the error occurred as below How do you solve these problems? enter image description here // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() maven { url 'https://maven.google.com' } } dependencies { classpath 'com.android.tools.build:gradle:7.31' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenCentral() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } This is my build.gradle (https://github.com/udacity/ud839_Miwok/issues/143) I tried the solution provided by the above site, but the problem was not solved Did I find the wrong solution? A: Jcenter() is at the end of its life add maven {url"https://jitpack.io"} below the jcenter() line. However some additional tips. Bump up the Gradle plugin to max 4.2.2 and the Gradle version to 6.9.2. 2.There might be outdated libraries which you'll have to update in build.gradle
android studio gradle sync issues help plz
I tried to import the project written around 2016, but the error occurred as below How do you solve these problems? enter image description here // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() maven { url 'https://maven.google.com' } } dependencies { classpath 'com.android.tools.build:gradle:7.31' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenCentral() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } This is my build.gradle (https://github.com/udacity/ud839_Miwok/issues/143) I tried the solution provided by the above site, but the problem was not solved Did I find the wrong solution?
[ "Jcenter() is at the end of its life\nadd maven {url\"https://jitpack.io\"} below the jcenter() line.\nHowever some additional tips.\n\nBump up the Gradle plugin to max 4.2.2 and the Gradle version to 6.9.2.\n\n2.There might be outdated libraries which you'll have to update in build.gradle\n" ]
[ 0 ]
[]
[]
[ "android", "build.gradle", "kotlin" ]
stackoverflow_0074657037_android_build.gradle_kotlin.txt
Q: Logitech G910 how to make Lua script only run on M3 G keys I have a logitech G910 keyboard which has 9 G-keys and 3 "M-key" sets for a total of 27 I have a script that i have linked to G1 key but i have other macros on M1 set and M2 set, I only want the scripts to activate if on M3 set. Is there anyway to add something to specify that. This is one of the scripts I have if (event == "G_PRESSED" and arg == 1) then MoveMouseTo( 63076, 53509) Sleep(150) PressMouseButton(3) ReleaseMouseButton(3) Sleep(150) MoveMouseTo( 60583, 56728) Sleep(150) PressMouseButton(1) ReleaseMouseButton(1) end I tried to add in there something like if (event == "M3_ACTIVE" and "G_PRESSED" and arg == 1) then or if (event == "M3_PRESSED" and "G_PRESSED" and arg == 1) then but Im only very new to scripting and just googled what I wanted so no idea :D A: You can call GetMKeyState("kb") to get the current M key number. if event == "G_PRESSED" and arg == 1 and GetMKeyState("kb") == 3 then
Logitech G910 how to make Lua script only run on M3 G keys
I have a logitech G910 keyboard which has 9 G-keys and 3 "M-key" sets for a total of 27 I have a script that i have linked to G1 key but i have other macros on M1 set and M2 set, I only want the scripts to activate if on M3 set. Is there anyway to add something to specify that. This is one of the scripts I have if (event == "G_PRESSED" and arg == 1) then MoveMouseTo( 63076, 53509) Sleep(150) PressMouseButton(3) ReleaseMouseButton(3) Sleep(150) MoveMouseTo( 60583, 56728) Sleep(150) PressMouseButton(1) ReleaseMouseButton(1) end I tried to add in there something like if (event == "M3_ACTIVE" and "G_PRESSED" and arg == 1) then or if (event == "M3_PRESSED" and "G_PRESSED" and arg == 1) then but Im only very new to scripting and just googled what I wanted so no idea :D
[ "You can call GetMKeyState(\"kb\") to get the current M key number.\nif event == \"G_PRESSED\" and arg == 1 and GetMKeyState(\"kb\") == 3 then\n\n" ]
[ 0 ]
[]
[]
[ "logitech_gaming_software", "lua" ]
stackoverflow_0074655903_logitech_gaming_software_lua.txt
Q: PHP: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence I am getting the following warning in my PHP script The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence The code works though, the PHP version on the server is: PHP 7.4.33, is there a problem with the code? array_push($data, "" . str_getcsv($row)[0] . "," . str_getcsv($row)[1] . "," . str_getcsv($row)[2] . "," . str_getcsv($row)[3] + 1); A: Try the this to explicitly set precedence, see if warning is clear. array_push($data, "" . str_getcsv($row)[0] . "," . str_getcsv($row)[1] . "," . str_getcsv($row)[2] . "," . (str_getcsv($row)[3] + 1));
PHP: The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence
I am getting the following warning in my PHP script The behavior of unparenthesized expressions containing both '.' and '+'/'-' will change in PHP 8: '+'/'-' will take a higher precedence The code works though, the PHP version on the server is: PHP 7.4.33, is there a problem with the code? array_push($data, "" . str_getcsv($row)[0] . "," . str_getcsv($row)[1] . "," . str_getcsv($row)[2] . "," . str_getcsv($row)[3] + 1);
[ "Try the this to explicitly set precedence, see if warning is clear.\narray_push($data, \"\" . str_getcsv($row)[0] . \",\" . str_getcsv($row)[1] . \",\" . str_getcsv($row)[2] . \",\" . (str_getcsv($row)[3] + 1));\n\n" ]
[ 1 ]
[]
[]
[ "php" ]
stackoverflow_0074657049_php.txt
Q: Is this a problem with Array push() in Svelte or is it something I'm doing wrong? I've been wracking my brain over this issue for several hours now, and although I've found a workaround to the problem, I can't get over the fact that it's happening at all. I don't understand it. There seems to be some sort of an issue in using Array.push() within a promise handler. I've created the below test code to demonstrate it, and it's reproducable in Svelte REPL. Am I just doing something wrong? <script> const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }); let itemsA = []; let itemsB = []; const addItem = (item) => { itemsA[itemsA.length] = item; itemsB.push(item); } const loadItems = (last) => { addItem("Begin"); myPromise .then((value) => { addItem(value); }); addItem("End"); return true; }; loadItems(); </script> <div>Items A: {itemsA}</div> <div>Items B: {itemsB}</div> I would think that itemsB.push(item) should do the same thing as itemsA[itemsA.length] = item, and it does, except when called from inside the promise handler. I get the following results instead: Items A: Begin,End,foo Items B: Begin,End Edit: I've eliminated promises as the source of the weirdness. The following code illustrates it more simply. <script> let itemsA = []; let itemsB = []; const addItem = (item) => { itemsA[itemsA.length] = item; itemsB.push(item); } const clickHandler = () => { addItem('click'); } addItem('load'); </script> <div>Items A: {itemsA}</div> <div>Items B: {itemsB}</div> <button on:click={clickHandler}>Click Me</button> A: Actually that has nothing to do with the promise. When you add a button and log the arrays, you see that 'foo' is in 'itemsB' as well, it's just not rendered. From the Svelte Docs Because Svelte's reactivity is based on assignments, using array methods like .push() and .splice() won't automatically trigger updates. A subsequent assignment is required to trigger the update. The according tutorial You can use .push() if it's followed by a reassignment of the array to itself itemsB.push(item); itemsB = itemsB or alternatively use the spread operator syntax itemsB = [...itemsB, item] Here's a REPL to try this out A: You can try this: https://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1 use a library called svelox. It allows you to use the Array native api(push/splice...etc.) without reassignment statements.
Is this a problem with Array push() in Svelte or is it something I'm doing wrong?
I've been wracking my brain over this issue for several hours now, and although I've found a workaround to the problem, I can't get over the fact that it's happening at all. I don't understand it. There seems to be some sort of an issue in using Array.push() within a promise handler. I've created the below test code to demonstrate it, and it's reproducable in Svelte REPL. Am I just doing something wrong? <script> const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }); let itemsA = []; let itemsB = []; const addItem = (item) => { itemsA[itemsA.length] = item; itemsB.push(item); } const loadItems = (last) => { addItem("Begin"); myPromise .then((value) => { addItem(value); }); addItem("End"); return true; }; loadItems(); </script> <div>Items A: {itemsA}</div> <div>Items B: {itemsB}</div> I would think that itemsB.push(item) should do the same thing as itemsA[itemsA.length] = item, and it does, except when called from inside the promise handler. I get the following results instead: Items A: Begin,End,foo Items B: Begin,End Edit: I've eliminated promises as the source of the weirdness. The following code illustrates it more simply. <script> let itemsA = []; let itemsB = []; const addItem = (item) => { itemsA[itemsA.length] = item; itemsB.push(item); } const clickHandler = () => { addItem('click'); } addItem('load'); </script> <div>Items A: {itemsA}</div> <div>Items B: {itemsB}</div> <button on:click={clickHandler}>Click Me</button>
[ "Actually that has nothing to do with the promise. When you add a button and log the arrays, you see that 'foo' is in 'itemsB' as well, it's just not rendered.\nFrom the Svelte Docs\n\nBecause Svelte's reactivity is based on assignments, using array methods like .push() and .splice() won't automatically trigger updates. A subsequent assignment is required to trigger the update.\nThe according tutorial\n\nYou can use .push() if it's followed by a reassignment of the array to itself\nitemsB.push(item);\nitemsB = itemsB\n\nor alternatively use the spread operator syntax\nitemsB = [...itemsB, item]\n\nHere's a REPL to try this out\n", "You can try this:\nhttps://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1\nuse a library called svelox.\nIt allows you to use the Array native api(push/splice...etc.) without reassignment statements.\n" ]
[ 4, 0 ]
[]
[]
[ "arrays", "promise", "push", "svelte" ]
stackoverflow_0069919047_arrays_promise_push_svelte.txt
Q: type object 'Teachprofile' has no attribute '_meta' Models.py class Teachprofile: owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1) name=models.CharField(max_length=51) DOB=models.DateField() Address=models.TextField() Place=models.CharField(max_length=51) City=models.CharField(max_length=51) State=models.CharField(max_length=51) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1) Forms.py class Teachprofeditform(forms.ModelForm): class Meta: model = Teachprofile exclude = ['owner'] When I running the server,I get error as File "D:\Newproject\elearn\views.py", line 7, in <module> from .forms import UserRegistrationForm,CourseeditForm,ExameditForm,MarkeditForm,Teachprofeditform,Stuprofeditform File "D:\Newproject\elearn\forms.py", line 32, in <module> class Teachprofeditform(forms.ModelForm): File "D:\Newproject\env\lib\site-packages\django\forms\models.py", line 306, in __new__ fields = fields_for_model( File "D:\Newproject\env\lib\site-packages\django\forms\models.py", line 181, in fields_for_model opts = model._meta AttributeError: type object 'Teachprofile' has no attribute '_meta' I tried so many ways to debug,but didn't get the expected results.Also unable to migrate.I have to run the server. A: You need to inherit your class Teachprofile from Django's default model class from django.db import models class TeachProfile(models.Model): NB: Keep your field name's in lower-case letters. eg : dob, address, place, city etc
type object 'Teachprofile' has no attribute '_meta'
Models.py class Teachprofile: owner=models.ForeignKey(User,on_delete=models.CASCADE,default=1) name=models.CharField(max_length=51) DOB=models.DateField() Address=models.TextField() Place=models.CharField(max_length=51) City=models.CharField(max_length=51) State=models.CharField(max_length=51) course=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1) Forms.py class Teachprofeditform(forms.ModelForm): class Meta: model = Teachprofile exclude = ['owner'] When I running the server,I get error as File "D:\Newproject\elearn\views.py", line 7, in <module> from .forms import UserRegistrationForm,CourseeditForm,ExameditForm,MarkeditForm,Teachprofeditform,Stuprofeditform File "D:\Newproject\elearn\forms.py", line 32, in <module> class Teachprofeditform(forms.ModelForm): File "D:\Newproject\env\lib\site-packages\django\forms\models.py", line 306, in __new__ fields = fields_for_model( File "D:\Newproject\env\lib\site-packages\django\forms\models.py", line 181, in fields_for_model opts = model._meta AttributeError: type object 'Teachprofile' has no attribute '_meta' I tried so many ways to debug,but didn't get the expected results.Also unable to migrate.I have to run the server.
[ "You need to inherit your class Teachprofile from Django's default model class\nfrom django.db import models\n\n\nclass TeachProfile(models.Model):\n\n\nNB: Keep your field name's in lower-case letters.\neg : dob, address, place, city etc\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "django_models", "django_templates", "django_views" ]
stackoverflow_0074656776_django_django_forms_django_models_django_templates_django_views.txt
Q: Kotlin iterator to list? I have an iterator of strings from fieldNames of JsonNode: val mm = ... //JsonNode val xs = mm.fieldNames() I want to loop over the fields while keeping count, something like: when mm.size() { 1 -> myFunction1(xs[0]) 2 -> myFunction2(xs[0], xs[1]) 3 -> myFunction3(xs[0], xs[1], xs[2]) else -> print("invalid") } Obviously the above code does not work as xs the Iterator cannot be indexed like so. I tried to see if I can convert the iterator to list by mm.toList() but that does not exist. How can I achieve this? A: Probably the easiest way is to convert iterator to Sequence first and then to List: listOf(1,2,3).iterator().asSequence().toList() result: [1, 2, 3] A: I would skip the conversion to sequence, because it is only a few lines of code. fun <T> Iterator<T>.toList(): List<T> = ArrayList<T>().apply { while (hasNext()) this += next() } Update: Please keep in mind though, that appending to an ArrayList is not that performant, so for longer lists, you are better off with the following, or with the accepted answer: fun <T> Iterator<T>.toList(): List<T> = LinkedList<T>().apply { while (hasNext()) this += next() }.toMutableList() A: You can turn an Iterator into an Iterable using Iterable { iterator } on which you can then call toList(): Iterable { listOf(1,2,3).iterator() }.toList() // [1, 2, 3]
Kotlin iterator to list?
I have an iterator of strings from fieldNames of JsonNode: val mm = ... //JsonNode val xs = mm.fieldNames() I want to loop over the fields while keeping count, something like: when mm.size() { 1 -> myFunction1(xs[0]) 2 -> myFunction2(xs[0], xs[1]) 3 -> myFunction3(xs[0], xs[1], xs[2]) else -> print("invalid") } Obviously the above code does not work as xs the Iterator cannot be indexed like so. I tried to see if I can convert the iterator to list by mm.toList() but that does not exist. How can I achieve this?
[ "Probably the easiest way is to convert iterator to Sequence first and then to List:\nlistOf(1,2,3).iterator().asSequence().toList()\n\nresult:\n[1, 2, 3]\n\n", "I would skip the conversion to sequence, because it is only a few lines of code.\nfun <T> Iterator<T>.toList(): List<T> =\n ArrayList<T>().apply {\n while (hasNext())\n this += next()\n }\n\n\nUpdate:\nPlease keep in mind though, that appending to an ArrayList is not that performant, so for longer lists, you are better off with the following, or with the accepted answer:\n fun <T> Iterator<T>.toList(): List<T> =\n LinkedList<T>().apply {\n while (hasNext())\n this += next()\n }.toMutableList()\n\n", "You can turn an Iterator into an Iterable using Iterable { iterator } on which you can then call toList():\nIterable { listOf(1,2,3).iterator() }.toList() // [1, 2, 3]\n\n" ]
[ 52, 4, 1 ]
[]
[]
[ "kotlin" ]
stackoverflow_0046107706_kotlin.txt
Q: Sprockets throws NoMethodError while pushing to Heroku I am upgrading my app to ruby 2.6.5 and it seems sprockets 4.0.2 is the cause of the issue. Most answers I've found involve downgrading to sprockets 3.7.2 (which I'm using locally), but when the assets get compiled during the Heroku push, I get the following error: remote: NoMethodError: undefined method `start_with?' for #<Regexp:0x00005582ab94a790> remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/uri_utils.rb:78:in `valid_asset_uri?' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/resolve.rb:27:in `resolve' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/base.rb:79:in `find_asset' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/base.rb:88:in `find_all_linked_assets' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/manifest.rb:125:in `block (2 levels) in find' I've modified config/initializers/assets.rb to: # Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/ Rails.application.config.assets.precompile << ["*.svg", "*.eot", "*.woff", "*.ttf"] But the error is still occurring. Any idea how to fix this? A: I also faces the same error. I added below version specified gem due to downgrade sprockets and it deploys successfully. Gemfile gem 'sprockets', '~> 3.0'
Sprockets throws NoMethodError while pushing to Heroku
I am upgrading my app to ruby 2.6.5 and it seems sprockets 4.0.2 is the cause of the issue. Most answers I've found involve downgrading to sprockets 3.7.2 (which I'm using locally), but when the assets get compiled during the Heroku push, I get the following error: remote: NoMethodError: undefined method `start_with?' for #<Regexp:0x00005582ab94a790> remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/uri_utils.rb:78:in `valid_asset_uri?' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/resolve.rb:27:in `resolve' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/base.rb:79:in `find_asset' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/base.rb:88:in `find_all_linked_assets' remote: /tmp/build_f56a8b75/vendor/bundle/ruby/2.6.0/gems/sprockets-4.0.2/lib/sprockets/manifest.rb:125:in `block (2 levels) in find' I've modified config/initializers/assets.rb to: # Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/ Rails.application.config.assets.precompile << ["*.svg", "*.eot", "*.woff", "*.ttf"] But the error is still occurring. Any idea how to fix this?
[ "I also faces the same error.\nI added below version specified gem due to downgrade sprockets and it deploys successfully.\nGemfile\ngem 'sprockets', '~> 3.0'\n\n" ]
[ 0 ]
[]
[]
[ "heroku", "ruby_on_rails", "sprockets" ]
stackoverflow_0065116331_heroku_ruby_on_rails_sprockets.txt
Q: Expo Go app download stuck for IOS simulator I have upgraded expo sdk to recent version 47.0.0. And expo asked me to upgrade Expo Go version in IOS simulator, so I removed app in IOS simulator. Then run expo start --ios It stuck in downloading Expo Go app into IOS simulator. To fix this, I tried these. tried on different IOS simulators (iPhone 12, iPhone 12 Pro) reset IOS simulator (Erase All Content and Settings...) restart Computer. installing fresh new app (it stucks too) Lastly, I tried this expo client:install:ios It stuck too, but a few mins later, it shows this message. This download is taking longer than expected. You can also try downloading the clients from the website at https://expo.dev/tools Expo Info here: Thanks. A: This was netowork issue, Please check VPN or Firewall or Proxy
Expo Go app download stuck for IOS simulator
I have upgraded expo sdk to recent version 47.0.0. And expo asked me to upgrade Expo Go version in IOS simulator, so I removed app in IOS simulator. Then run expo start --ios It stuck in downloading Expo Go app into IOS simulator. To fix this, I tried these. tried on different IOS simulators (iPhone 12, iPhone 12 Pro) reset IOS simulator (Erase All Content and Settings...) restart Computer. installing fresh new app (it stucks too) Lastly, I tried this expo client:install:ios It stuck too, but a few mins later, it shows this message. This download is taking longer than expected. You can also try downloading the clients from the website at https://expo.dev/tools Expo Info here: Thanks.
[ "This was netowork issue, Please check VPN or Firewall or Proxy\n" ]
[ 0 ]
[]
[]
[ "download", "expo", "expo_go", "ios" ]
stackoverflow_0074653749_download_expo_expo_go_ios.txt
Q: "Socket id" is null while a connection is established in Flutter I use the following code to establish a connection with socket.io: late IO.Socket _socket; @override void initState() { super.initState(); _socket = IO.io('http://192.168.1.3:3001', IO.OptionBuilder().setTransports(['websocket']).build()); print(_socket.id); } When I run the app, _socket.id is null. A: You forgot to connect the socket like below _socket.connect(); But the Way you're writing your code is not good. You can follow below pattern. IO.Socket socket; @override void initState() { initSocket(); super.initState(); } initSocket() { socket = IO.io('http://192.168.1.3:3001', IO.OptionBuilder().setTransports(['websocket']) .disableAutoConnect() .build()); socket.connect(); socket.onConnect((_) { print('Connection established'); }); socket.onDisconnect((_) => print('Connection Disconnection')); socket.onConnectError((err) => print(err)); socket.onError((err) => print(err)); }
"Socket id" is null while a connection is established in Flutter
I use the following code to establish a connection with socket.io: late IO.Socket _socket; @override void initState() { super.initState(); _socket = IO.io('http://192.168.1.3:3001', IO.OptionBuilder().setTransports(['websocket']).build()); print(_socket.id); } When I run the app, _socket.id is null.
[ "You forgot to connect the socket like below\n_socket.connect();\n\nBut the Way you're writing your code is not good.\nYou can follow below pattern.\nIO.Socket socket;\n@override\nvoid initState() {\n initSocket();\n super.initState();\n}\ninitSocket() {\n socket = IO.io('http://192.168.1.3:3001', IO.OptionBuilder().setTransports(['websocket'])\n.disableAutoConnect() .build());\n socket.connect();\n socket.onConnect((_) {\n print('Connection established');\n });\n socket.onDisconnect((_) => print('Connection Disconnection'));\n socket.onConnectError((err) => print(err));\n socket.onError((err) => print(err));\n }\n\n" ]
[ 1 ]
[]
[]
[ "flutter", "socket.io" ]
stackoverflow_0074657110_flutter_socket.io.txt
Q: code running fine on computer and on pydroid 3 it doesnt so i have made a script that when my phone connects to my wifi network it automatically turn on my computer and i downloaded pydroid on another phone to run it non stop and it outputs : ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface] [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos] [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline] [-W timeout] [hop1 ...] destination and the code is this that works perfectly on a computer: import subprocess from wakeonlan import send_magic_packet IP_DEVICE = 'phonesip' devices = { 'my_pc': {'mac': 'mymacadress', 'ip_address': 'myipadress'} } def wake_device(device_name): if device_name in devices: mac, ip = devices[device_name].values() send_magic_packet(mac, ip_address=ip) print('Magic Packet Sent') else: print('Device Not Found') proc = subprocess.Popen(["ping", '-t', IP_DEVICE], stdout=subprocess.PIPE) while True: line = proc.stdout.readline() if not line: break else: None try: connected_ip = line.decode('utf-8').split()[2].replace(':', '') if connected_ip == IP_DEVICE: print('Device connected!') wake_device('my_pc') # Do whatever you want when the device connects here... break else: print('Pinging device...') except: pass A: Try omitting the -t from ping when running the script on your phone. ping works differently on your phone. On windows you have to add -t for it to ping nonstop, on other operating systems that is the default behaviour.
code running fine on computer and on pydroid 3 it doesnt
so i have made a script that when my phone connects to my wifi network it automatically turn on my computer and i downloaded pydroid on another phone to run it non stop and it outputs : ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface] [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos] [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline] [-W timeout] [hop1 ...] destination and the code is this that works perfectly on a computer: import subprocess from wakeonlan import send_magic_packet IP_DEVICE = 'phonesip' devices = { 'my_pc': {'mac': 'mymacadress', 'ip_address': 'myipadress'} } def wake_device(device_name): if device_name in devices: mac, ip = devices[device_name].values() send_magic_packet(mac, ip_address=ip) print('Magic Packet Sent') else: print('Device Not Found') proc = subprocess.Popen(["ping", '-t', IP_DEVICE], stdout=subprocess.PIPE) while True: line = proc.stdout.readline() if not line: break else: None try: connected_ip = line.decode('utf-8').split()[2].replace(':', '') if connected_ip == IP_DEVICE: print('Device connected!') wake_device('my_pc') # Do whatever you want when the device connects here... break else: print('Pinging device...') except: pass
[ "Try omitting the -t from ping when running the script on your phone.\nping works differently on your phone. On windows you have to add -t for it to ping nonstop, on other operating systems that is the default behaviour.\n" ]
[ 0 ]
[]
[]
[ "pydroid", "python" ]
stackoverflow_0074633484_pydroid_python.txt
Q: Prepare json file for GPT I would like to create a dataset to use it for fine-tuning GPT3. As I read from the following site https://beta.openai.com/docs/guides/fine-tuning, the dataset should look like this {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"prompt": "<prompt text>", "completion": "<ideal generated text>"} ... For this reason I am creating the dataset with the following way import json # Data to be written dictionary = { "prompt": "<text1>", "completion": "<text to be generated1>"}, { "prompt": "<text2>", "completion": "<text to be generated2>"} with open("sample2.json", "w") as outfile: json.dump(dictionary, outfile) However, when I am trying to load it, it looks like this which is not as we want import json # Opening JSON file with open('sample2.json', 'r') as openfile: # Reading from json file json_object = json.load(openfile) print(json_object) print(type(json_object)) >> [{'prompt': '<text1>', 'completion': '<text to be generated1>'}, {'prompt': '<text2>', 'completion': '<text to be generated2>'}] <class 'list'> Could you please let me know how can I face this problem? A: it's more like, writing \n a new line character after each json. so each line is JSON. somehow the link jsonlines throw server not found error on me. you can have these options: write \n after each line: import json with open("sample2_op1.json", "w") as outfile: for e_json in dictionary: json.dump(e_json, outfile) outfile.write('\n') #read file, as it has \n, read line by line and load as json with open("sample2_op1.json","r") as file: for line in file: print(json.loads(line),type(json.loads(line))) which have way to read file too, its jsonlines install the module !pip install jsonlines import jsonlines #write to file with jsonlines.open('sample2_op2.jsonl', 'w') as outfile: outfile.write_all(dictionary) #read the file with jsonlines.open('sample2_op2.jsonl') as reader: for obj in reader: print(obj)
Prepare json file for GPT
I would like to create a dataset to use it for fine-tuning GPT3. As I read from the following site https://beta.openai.com/docs/guides/fine-tuning, the dataset should look like this {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"prompt": "<prompt text>", "completion": "<ideal generated text>"} {"prompt": "<prompt text>", "completion": "<ideal generated text>"} ... For this reason I am creating the dataset with the following way import json # Data to be written dictionary = { "prompt": "<text1>", "completion": "<text to be generated1>"}, { "prompt": "<text2>", "completion": "<text to be generated2>"} with open("sample2.json", "w") as outfile: json.dump(dictionary, outfile) However, when I am trying to load it, it looks like this which is not as we want import json # Opening JSON file with open('sample2.json', 'r') as openfile: # Reading from json file json_object = json.load(openfile) print(json_object) print(type(json_object)) >> [{'prompt': '<text1>', 'completion': '<text to be generated1>'}, {'prompt': '<text2>', 'completion': '<text to be generated2>'}] <class 'list'> Could you please let me know how can I face this problem?
[ "it's more like, writing \\n a new line character after each json. so each line is JSON. somehow the link jsonlines throw server not found error on me.\nyou can have these options:\n\nwrite \\n after each line:\n\nimport json\nwith open(\"sample2_op1.json\", \"w\") as outfile:\n for e_json in dictionary:\n json.dump(e_json, outfile)\n outfile.write('\\n')\n#read file, as it has \\n, read line by line and load as json\nwith open(\"sample2_op1.json\",\"r\") as file:\n for line in file:\n print(json.loads(line),type(json.loads(line)))\n\n\nwhich have way to read file too, its jsonlines\ninstall the module !pip install jsonlines\n\nimport jsonlines\n#write to file\nwith jsonlines.open('sample2_op2.jsonl', 'w') as outfile:\n outfile.write_all(dictionary)\n#read the file\nwith jsonlines.open('sample2_op2.jsonl') as reader:\n for obj in reader:\n print(obj)\n\n" ]
[ 1 ]
[]
[]
[ "gpt_3", "nlp", "python" ]
stackoverflow_0074656790_gpt_3_nlp_python.txt
Q: Get component ref from Vue @click event Hopefully a simple one to answer, but I cannot get an HTML reference to the component that triggers an @click event in vue after much searching. So I have a custom component in a list <ion-list lines="none" v-for="item in uiPosts" :key="item.createdAt"> <ion-item v-if="!item.skipped" class="ion-no-padding"> <SummaryCard class="summary" :post=item @click="handleCardClick" ... blah blah blah and a simple handler const handleCardClick = async (e : Event) => { ... stuff console.log(e.target); // something like the card title but not the actual card } And e.target just gives me granular sub elements for the card like the heading or subheading. Same if I attach @click event to the ion-item in the list. I just want a ref to the thing I actually attach the click event to so I can make sure it is fully scrolled into view when clicked. A: Ok. So from the vue 3 docs (with the composition API switch toggled!!!). Callback like this: const cardRefs = ref<HTMLDivElement[]>([]) const handleCardClick = async (idx: number) => { const el = cardRefs.value[idx]; el.scrollIntoView({ behavior: "smooth", block: "end"}); } Template like this: <ion-list lines="none"> <div v-for="(item, idx) in uiPosts" :key="item.createdAt" ref="cardRefs" @click.capture="handleCardClick(idx)"> <ion-item v-if="!item.skipped" class="ion-no-padding" > <SummaryCard class="summary" :post=item ... Which solves the challenge in the original question EDIT: There is a better way . . because from the docs "It should be noted that the ref array does not guarantee the same order as the source array." . . and this definitely gets weird when you have something like an infinite list. Instead of passing the callback from the infinite list, derive it from the event. This is more robust const handleCardClick = async (e: Event) => { const idx = cardRefs.value.findIndex((element)=>{return element.contains(e.target as HTMLElement)}) cardRefs.value[idx].scrollIntoView({ behavior: "smooth", block: "start"}); }
Get component ref from Vue @click event
Hopefully a simple one to answer, but I cannot get an HTML reference to the component that triggers an @click event in vue after much searching. So I have a custom component in a list <ion-list lines="none" v-for="item in uiPosts" :key="item.createdAt"> <ion-item v-if="!item.skipped" class="ion-no-padding"> <SummaryCard class="summary" :post=item @click="handleCardClick" ... blah blah blah and a simple handler const handleCardClick = async (e : Event) => { ... stuff console.log(e.target); // something like the card title but not the actual card } And e.target just gives me granular sub elements for the card like the heading or subheading. Same if I attach @click event to the ion-item in the list. I just want a ref to the thing I actually attach the click event to so I can make sure it is fully scrolled into view when clicked.
[ "Ok. So from the vue 3 docs (with the composition API switch toggled!!!).\nCallback like this:\nconst cardRefs = ref<HTMLDivElement[]>([])\n\nconst handleCardClick = async (idx: number) => {\n const el = cardRefs.value[idx];\n el.scrollIntoView({ behavior: \"smooth\", block: \"end\"});\n}\n\nTemplate like this:\n <ion-list lines=\"none\">\n <div v-for=\"(item, idx) in uiPosts\" :key=\"item.createdAt\" ref=\"cardRefs\" @click.capture=\"handleCardClick(idx)\">\n <ion-item v-if=\"!item.skipped\" class=\"ion-no-padding\" >\n <SummaryCard class=\"summary\" \n :post=item \n ...\n\nWhich solves the challenge in the original question\nEDIT:\nThere is a better way . . because from the docs \"It should be noted that the ref array does not guarantee the same order as the source array.\" . . and this definitely gets weird when you have something like an infinite list.\nInstead of passing the callback from the infinite list, derive it from the event. This is more robust\nconst handleCardClick = async (e: Event) => { \n const idx = cardRefs.value.findIndex((element)=>{return element.contains(e.target as HTMLElement)}) \n cardRefs.value[idx].scrollIntoView({ behavior: \"smooth\", block: \"start\"});\n}\n\n" ]
[ 0 ]
[]
[]
[ "html", "typescript", "vue.js", "vue_composition_api", "vuejs3" ]
stackoverflow_0074656232_html_typescript_vue.js_vue_composition_api_vuejs3.txt
Q: Copy recent/new files based on timestamp via PowerShell Can you guys help me how can I compare the files in "Folder A" and "Folder B" via PowerShell and if the files are not present in "Folder B" based on the content of "Folder A", it will copy these missing files to "Folder C"? This is what I tried using the code from this link Powershell: Move files to folder based on Date Created but it doesn't have the comparison and it will copy all the files from "Folder A" to "Folder C". Thank you in advance.: Get-ChildItem C:\Users\TestUser\Desktop\TEST\Folder A\*.xlsx -Recurse | foreach { $x = $_.LastWriteTime.ToShortDateString() $new_folder_name = Get-Date $x -Format yyyy.MM.dd $des_path = "C:\Users\TestUser\Desktop\TEST\Folder C\" if (test-path $des_path){ copy-item $_.fullname $des_path } else { new-item -ItemType directory -Path $des_path copy-item $_.fullname $des_path } } A: Your question title and real question is not same, assuming that you only want to copy the missing files to third folder, here is the script below: #Folder Path $folderA = "C:\temp\folderA" $folderB = "C:\temp\folderB" $destination = "C:\temp\folderC\" #Getting File names only from source and folder to be compared $sourceFolder = Get-childItem -path $folderA | Select-Object -ExpandProperty Name $foldertobeCompared = Get-childItem -path $folderB | Select-Object -ExpandProperty Name # comparing files and copying to third folder foreach ($file in $sourceFolder) { if ($foldertobeCompared -contains $file) { Write-Host "$($file) exists in folderB" } else { Copy-Item -Path "$folderA\$file" -Destination $destination Write-Host "$($file) copied in folderC" } }
Copy recent/new files based on timestamp via PowerShell
Can you guys help me how can I compare the files in "Folder A" and "Folder B" via PowerShell and if the files are not present in "Folder B" based on the content of "Folder A", it will copy these missing files to "Folder C"? This is what I tried using the code from this link Powershell: Move files to folder based on Date Created but it doesn't have the comparison and it will copy all the files from "Folder A" to "Folder C". Thank you in advance.: Get-ChildItem C:\Users\TestUser\Desktop\TEST\Folder A\*.xlsx -Recurse | foreach { $x = $_.LastWriteTime.ToShortDateString() $new_folder_name = Get-Date $x -Format yyyy.MM.dd $des_path = "C:\Users\TestUser\Desktop\TEST\Folder C\" if (test-path $des_path){ copy-item $_.fullname $des_path } else { new-item -ItemType directory -Path $des_path copy-item $_.fullname $des_path } }
[ "Your question title and real question is not same, assuming that you only want to copy the missing files to third folder, here is the script below:\n#Folder Path\n$folderA = \"C:\\temp\\folderA\" \n$folderB = \"C:\\temp\\folderB\" \n$destination = \"C:\\temp\\folderC\\\"\n\n#Getting File names only from source and folder to be compared\n$sourceFolder = Get-childItem -path $folderA | Select-Object -ExpandProperty Name\n$foldertobeCompared = Get-childItem -path $folderB | Select-Object -ExpandProperty Name\n\n# comparing files and copying to third folder\nforeach ($file in $sourceFolder) {\n if ($foldertobeCompared -contains $file) {\n Write-Host \"$($file) exists in folderB\"\n } else {\n Copy-Item -Path \"$folderA\\$file\" -Destination $destination\n Write-Host \"$($file) copied in folderC\" \n }\n\n}\n\n" ]
[ 1 ]
[]
[]
[ "powershell" ]
stackoverflow_0074655695_powershell.txt
Q: how to submit form data with multiple buttons I want to send data to database table. but there are two submit buttons. 1.Accept 2.Reject. When you click the Accept button, the database will receive the input "value = accepted," and when you click the Reject button, the database will receive the input "value = rejected." The problem is that if you click on any button, "input value = accepted" is sent to the table. This is my form. @foreach($attendance as $request) <form class="d-sm-inline-block" method="POST" action="/update" enctype="multipart/form-data"> @csrf <tr> <th scope="row"> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['id']}}</label> <input type="hidden" value="{{$request['id']}}" name="id" class="form-control"> </div> </th> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['name']}}</label> <input type="hidden" value="{{$request['name']}}" name="name" class="form-control"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['class']}}</label> <input type="hidden" value="{{$request['class']}}" name="class" class="form-control"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['roll_number']}}</label> <input type="hidden" value="{{$request['roll_number']}}" name="rollnumber" class="form-control"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['subject_name']}}</label> <input type="hidden" value="{{$request['subject_name']}}" name="subject" class="form-control" > </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['attendance']}}</label> <input type="hidden" value="{{$request['attendance']}}" name="attendance" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['status']}}</label> <input type="hidden" value="{{$request['status']}}" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </td> <td> <div class="mb-3"> <input type="hidden" value="Accepted" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <input type="hidden" value="Rejected" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <button type="submit" class="btn btn-success" action="action" value="accept">accept</button> <button type="submit" class="btn btn-warning" action="action" value="reject">Reject</button> </tr> </form> @endforeach A: remove: <div class="mb-3"> <input type="hidden" value="Accepted" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <input type="hidden" value="Rejected" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> and change this: <button type="submit" class="btn btn-success" action="action" value="accept">accept</button> <button type="submit" class="btn btn-warning" action="action" value="reject">Reject</button> to: <button type="submit" name="status" class="btn btn-success" action="action" value="accept">accept</button> <button type="submit" name="status" class="btn btn-warning" action="action" value="reject">Reject</button> Your submit buttons have no name attribute so their values won't be there in the request.
how to submit form data with multiple buttons
I want to send data to database table. but there are two submit buttons. 1.Accept 2.Reject. When you click the Accept button, the database will receive the input "value = accepted," and when you click the Reject button, the database will receive the input "value = rejected." The problem is that if you click on any button, "input value = accepted" is sent to the table. This is my form. @foreach($attendance as $request) <form class="d-sm-inline-block" method="POST" action="/update" enctype="multipart/form-data"> @csrf <tr> <th scope="row"> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['id']}}</label> <input type="hidden" value="{{$request['id']}}" name="id" class="form-control"> </div> </th> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['name']}}</label> <input type="hidden" value="{{$request['name']}}" name="name" class="form-control"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['class']}}</label> <input type="hidden" value="{{$request['class']}}" name="class" class="form-control"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['roll_number']}}</label> <input type="hidden" value="{{$request['roll_number']}}" name="rollnumber" class="form-control"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['subject_name']}}</label> <input type="hidden" value="{{$request['subject_name']}}" name="subject" class="form-control" > </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['attendance']}}</label> <input type="hidden" value="{{$request['attendance']}}" name="attendance" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </td> <td> <div class="mb-3"> <label for="exampleInputPassword1" class="form-label">{{$request['status']}}</label> <input type="hidden" value="{{$request['status']}}" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> </td> <td> <div class="mb-3"> <input type="hidden" value="Accepted" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <input type="hidden" value="Rejected" name="status" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> </div> <button type="submit" class="btn btn-success" action="action" value="accept">accept</button> <button type="submit" class="btn btn-warning" action="action" value="reject">Reject</button> </tr> </form> @endforeach
[ "remove:\n <div class=\"mb-3\">\n <input type=\"hidden\" value=\"Accepted\" name=\"status\" class=\"form-control\" id=\"exampleInputEmail1\" aria-describedby=\"emailHelp\">\n <input type=\"hidden\" value=\"Rejected\" name=\"status\" class=\"form-control\" id=\"exampleInputEmail1\" aria-describedby=\"emailHelp\">\n </div>\n\nand change this:\n<button type=\"submit\" class=\"btn btn-success\" action=\"action\" value=\"accept\">accept</button>\n<button type=\"submit\" class=\"btn btn-warning\" action=\"action\" value=\"reject\">Reject</button>\n\nto:\n <button type=\"submit\" name=\"status\" class=\"btn btn-success\" action=\"action\" value=\"accept\">accept</button>\n <button type=\"submit\" name=\"status\" class=\"btn btn-warning\" action=\"action\" value=\"reject\">Reject</button>\n\nYour submit buttons have no name attribute so their values won't be there in the request.\n" ]
[ 0 ]
[]
[]
[ "laravel_9" ]
stackoverflow_0074656481_laravel_9.txt
Q: Data path "" should NOT have additional properties(rebaseRootRelativeCssUrls) I am new at angular and I just want to update some packages and happen this issue. I have been finding this issue and nothing found a useful answer. Here is Error => Schema validation failed with the following errors: Data path "" should NOT have additional properties(rebaseRootRelativeCssUrls). npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] start: `ng serve --ssl` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\me\AppData\Roaming\npm-cache\_logs\2020-12-21T07_08_11_784Z-debug.log Here is Full Log = > > 0 info it worked if it ends with ok > 1 verbose cli [ > 1 verbose cli 'C:\\Program Files\\nodejs\\node.exe', > 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', > 1 verbose cli 'start' > 1 verbose cli ] > 2 info using [email protected] > 3 info using [email protected] > 4 verbose run-script [ 'prestart', 'start', 'poststart' ] > 5 info lifecycle [email protected]~prestart: [email protected] > 6 info lifecycle [email protected]~start: [email protected] > 7 verbose lifecycle [email protected]~start: unsafe-perm in lifecycle true > 8 verbose lifecycle [email protected]~start: PATH of Environment > 9 verbose lifecycle [email protected]~start: CWD: C:\me\Project1\web > 10 silly lifecycle [email protected]~start: Args: [ '/d /s /c', 'ng serve --ssl' ] > 11 silly lifecycle [email protected]~start: Returned: code: 1 signal: null > 12 info lifecycle [email protected]~start: Failed to exec start script > 13 verbose stack Error: [email protected] start: `ng serve --ssl` > 13 verbose stack Exit status 1 > 13 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16) > 13 verbose stack at EventEmitter.emit (events.js:315:20) > 13 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14) > 13 verbose stack at ChildProcess.emit (events.js:315:20) > 13 verbose stack at maybeClose (internal/child_process.js:1021:16) > 13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5) > 14 verbose pkgid [email protected] > 15 verbose cwd C:\me\Project1\web > 16 verbose Windows_NT 10.0.19041 > 17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start" > 18 verbose node v12.18.4 > 19 verbose npm v6.14.6 > 20 error code ELIFECYCLE > 21 error errno 1 > 22 error [email protected] start: `ng serve --ssl` > 22 error Exit status 1 > 23 error Failed at the [email protected] start script. > 23 error This is probably not a problem with npm. There is likely additional logging output above. > 24 verbose exit [ 1, true ] Please May I know Any Idea or any reason why this error happen? A: I think that package-lock.json and node modules are the causes of the issue. try : delete node-modules and package-lock.json npm clean cache --force npm install A: I solve this problem by removing rebaseRootRelativeCssUrls line from angular.json.
Data path "" should NOT have additional properties(rebaseRootRelativeCssUrls)
I am new at angular and I just want to update some packages and happen this issue. I have been finding this issue and nothing found a useful answer. Here is Error => Schema validation failed with the following errors: Data path "" should NOT have additional properties(rebaseRootRelativeCssUrls). npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] start: `ng serve --ssl` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\me\AppData\Roaming\npm-cache\_logs\2020-12-21T07_08_11_784Z-debug.log Here is Full Log = > > 0 info it worked if it ends with ok > 1 verbose cli [ > 1 verbose cli 'C:\\Program Files\\nodejs\\node.exe', > 1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js', > 1 verbose cli 'start' > 1 verbose cli ] > 2 info using [email protected] > 3 info using [email protected] > 4 verbose run-script [ 'prestart', 'start', 'poststart' ] > 5 info lifecycle [email protected]~prestart: [email protected] > 6 info lifecycle [email protected]~start: [email protected] > 7 verbose lifecycle [email protected]~start: unsafe-perm in lifecycle true > 8 verbose lifecycle [email protected]~start: PATH of Environment > 9 verbose lifecycle [email protected]~start: CWD: C:\me\Project1\web > 10 silly lifecycle [email protected]~start: Args: [ '/d /s /c', 'ng serve --ssl' ] > 11 silly lifecycle [email protected]~start: Returned: code: 1 signal: null > 12 info lifecycle [email protected]~start: Failed to exec start script > 13 verbose stack Error: [email protected] start: `ng serve --ssl` > 13 verbose stack Exit status 1 > 13 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16) > 13 verbose stack at EventEmitter.emit (events.js:315:20) > 13 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14) > 13 verbose stack at ChildProcess.emit (events.js:315:20) > 13 verbose stack at maybeClose (internal/child_process.js:1021:16) > 13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5) > 14 verbose pkgid [email protected] > 15 verbose cwd C:\me\Project1\web > 16 verbose Windows_NT 10.0.19041 > 17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start" > 18 verbose node v12.18.4 > 19 verbose npm v6.14.6 > 20 error code ELIFECYCLE > 21 error errno 1 > 22 error [email protected] start: `ng serve --ssl` > 22 error Exit status 1 > 23 error Failed at the [email protected] start script. > 23 error This is probably not a problem with npm. There is likely additional logging output above. > 24 verbose exit [ 1, true ] Please May I know Any Idea or any reason why this error happen?
[ "I think that package-lock.json and node modules are the causes of the issue.\ntry :\n\ndelete node-modules and package-lock.json\nnpm clean cache --force\nnpm install\n\n", "I solve this problem by removing rebaseRootRelativeCssUrls line from angular.json.\n" ]
[ 2, 1 ]
[]
[]
[ "angular10", "angular_cli", "npm" ]
stackoverflow_0065388829_angular10_angular_cli_npm.txt
Q: Data in Pandas becomes NaN when I add it to another data frame I am trying to pull Worldwide data from a data set and add the column to another dataframe using pandas, but the data becomes NaN everytime I run the code. The same code works for when I try to pull US data. Code: fb_us_data = us_data[us_data.app_id == fb_key] fb_ww_data = ww_data[ww_data.app_id == fb_key] fb_intl_data = fb_us_data[["app_id","date"]] fb_intl_data['total_users_ww'] = fb_us_data['total_users'] fb_intl_data["total_users_us"] = fb_us_data['total_users'] print(fb_intl_data)` Output: app_id date total_users_ww total_users_us 158515 55c530a702ac64f9c0002dff 2015-09-28 NaN 114609170 158516 55c530a702ac64f9c0002dff 2015-10-05 NaN 115642838 158517 55c530a702ac64f9c0002dff 2015-10-12 NaN 116414827 158518 55c530a702ac64f9c0002dff 2015-10-19 NaN 117005866 158519 55c530a702ac64f9c0002dff 2015-10-26 NaN 118743332 ... ... ... ... ... 158885 55c530a702ac64f9c0002dff 2022-10-31 NaN 228981651 158886 55c530a702ac64f9c0002dff 2022-11-07 NaN 229721851 158887 55c530a702ac64f9c0002dff 2022-11-14 NaN 228069299 158888 55c530a702ac64f9c0002dff 2022-11-21 NaN 228729072 158889 55c530a702ac64f9c0002dff 2022-11-28 NaN 225447696 [375 rows x 4 columns] A: the problem here come from indexes try reseting index before adding like this: fb_us_data = us_data[us_data.app_id == fb_key].copy() fb_ww_data = ww_data[ww_data.app_id == fb_key].copy() fb_us_data.reset_index(drop=True, inplace=True) fb_ww_data.reset_index(drop=True, inplace=True)
Data in Pandas becomes NaN when I add it to another data frame
I am trying to pull Worldwide data from a data set and add the column to another dataframe using pandas, but the data becomes NaN everytime I run the code. The same code works for when I try to pull US data. Code: fb_us_data = us_data[us_data.app_id == fb_key] fb_ww_data = ww_data[ww_data.app_id == fb_key] fb_intl_data = fb_us_data[["app_id","date"]] fb_intl_data['total_users_ww'] = fb_us_data['total_users'] fb_intl_data["total_users_us"] = fb_us_data['total_users'] print(fb_intl_data)` Output: app_id date total_users_ww total_users_us 158515 55c530a702ac64f9c0002dff 2015-09-28 NaN 114609170 158516 55c530a702ac64f9c0002dff 2015-10-05 NaN 115642838 158517 55c530a702ac64f9c0002dff 2015-10-12 NaN 116414827 158518 55c530a702ac64f9c0002dff 2015-10-19 NaN 117005866 158519 55c530a702ac64f9c0002dff 2015-10-26 NaN 118743332 ... ... ... ... ... 158885 55c530a702ac64f9c0002dff 2022-10-31 NaN 228981651 158886 55c530a702ac64f9c0002dff 2022-11-07 NaN 229721851 158887 55c530a702ac64f9c0002dff 2022-11-14 NaN 228069299 158888 55c530a702ac64f9c0002dff 2022-11-21 NaN 228729072 158889 55c530a702ac64f9c0002dff 2022-11-28 NaN 225447696 [375 rows x 4 columns]
[ "the problem here come from indexes try reseting index before adding like this:\nfb_us_data = us_data[us_data.app_id == fb_key].copy()\nfb_ww_data = ww_data[ww_data.app_id == fb_key].copy()\nfb_us_data.reset_index(drop=True, inplace=True)\nfb_ww_data.reset_index(drop=True, inplace=True)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "typeerror" ]
stackoverflow_0074656491_dataframe_pandas_python_typeerror.txt
Q: Flutter or Dart: How to I get device information such as CPU count, total memory and storage, etc Using Flutter, I would like to get device information details such as CPU count, bitness, Total Memory, Total device storage, etc. Similar to apps one can get on the App stores. I looked at device_info package, but that does not cover it. I also looked at system_info (which is pretty good, seems abandoned), but only works on Android since it's using Linux shell commands to get the info. I would also like it to work for iOS. Any ideas? A: Add this package to your pubspec.yaml: system_info: ^0.0.15, read more about it here : system_info. The docs says: Provides easy access to useful information about the system (architecture, bitness, kernel, operating system, CPU, user). A: The information is now available under the package: system_info2 since system_info is discontinued, with this you can easily get: KernelArchitecture Kernel bitness Kernel name Kernel version Operating system name Operating system version User directory User id User name User space bitness
Flutter or Dart: How to I get device information such as CPU count, total memory and storage, etc
Using Flutter, I would like to get device information details such as CPU count, bitness, Total Memory, Total device storage, etc. Similar to apps one can get on the App stores. I looked at device_info package, but that does not cover it. I also looked at system_info (which is pretty good, seems abandoned), but only works on Android since it's using Linux shell commands to get the info. I would also like it to work for iOS. Any ideas?
[ "Add this package to your pubspec.yaml: system_info: ^0.0.15,\nread more about it here : system_info.\nThe docs says: Provides easy access to useful information about the system (architecture, bitness, kernel, operating system, CPU, user).\n", "The information is now available under the package: system_info2 since system_info is discontinued, with this you can easily get:\n\nKernelArchitecture\nKernel bitness\nKernel name\nKernel version\nOperating system name\nOperating system version\nUser directory\nUser id\nUser name\nUser space bitness\n\n" ]
[ 0, 0 ]
[]
[]
[ "dart", "flutter", "system_information" ]
stackoverflow_0055859730_dart_flutter_system_information.txt
Q: Reset loop with condition I'm coding project with codewars and have a trouble. This function has to check if parentheses in string are valid. My problem is when i assign i = 0 in function valid pair it's doesnt work . I tried assign it below if statement and then my loop is infinite. My idea is valid pairs and then start over and over while parens.lenght will be <= 2 then i know that there left a pair and i can nothing to do with it. Could you help me? // "()" => true // ")(()))" => false // "(" => false // "(())((()())())" => true const validPair = (parens) => { console.log(parens); for (let i = 0; i < parens.length; i++) { if (parens[i] == '(' && parens[i + 1] == ')') { parens.splice(i, 2); i = 0; console.log(parens.length); } if (parens.length <= 2) { console.log(parens); } } console.log(parens); }; function validParentheses(parens) { let validLength = 0; parens = parens.split(''); parens.forEach((el) => { if (el == '(') { validLength++; } else { validLength--; } }); if (validLength != 0) { return false; } else { validPair(parens); } } console.log(validParentheses('(()))(()')); I will be updating this code but i stuck in this moment and dont know what to do. A: Approach: The idea is to use stack. so when you get ( you need to push it to stack and when you get ) you need to pop it. And at the end just need to check stack is still empty or not. if stack is empty that means parentheses are valid. Edge case: When there's no element in the stack and you have ) that means there's no ( bracket to match with it. so it returns false. const validParentheses = (str) => { const stack = []; for (let parentheses of str) { if (parentheses == '(') stack.push(parentheses); else { if (!stack.length) return false; stack.pop(); } } return !stack.length; } console.log(validParentheses("()")); console.log(validParentheses(")(()))")); console.log(validParentheses("(")); console.log(validParentheses("(())((()())())")); A: You've overcomplicated things Simply counting is enough // "()" => true // ")(()))" => false // "(" => false // "(())((()())())" => true function validParentheses(parens) { let lefts = 0 for (const par of parens) { if (par === '(') { lefts += 1 } else { lefts -= 1 } if (lefts < 0) return false } if (lefts !== 0) return false return true } console.log(validParentheses('()')); console.log(validParentheses('(()))(()')); console.log(validParentheses('(')); console.log(validParentheses('(())((()())())'));
Reset loop with condition
I'm coding project with codewars and have a trouble. This function has to check if parentheses in string are valid. My problem is when i assign i = 0 in function valid pair it's doesnt work . I tried assign it below if statement and then my loop is infinite. My idea is valid pairs and then start over and over while parens.lenght will be <= 2 then i know that there left a pair and i can nothing to do with it. Could you help me? // "()" => true // ")(()))" => false // "(" => false // "(())((()())())" => true const validPair = (parens) => { console.log(parens); for (let i = 0; i < parens.length; i++) { if (parens[i] == '(' && parens[i + 1] == ')') { parens.splice(i, 2); i = 0; console.log(parens.length); } if (parens.length <= 2) { console.log(parens); } } console.log(parens); }; function validParentheses(parens) { let validLength = 0; parens = parens.split(''); parens.forEach((el) => { if (el == '(') { validLength++; } else { validLength--; } }); if (validLength != 0) { return false; } else { validPair(parens); } } console.log(validParentheses('(()))(()')); I will be updating this code but i stuck in this moment and dont know what to do.
[ "Approach:\nThe idea is to use stack. so when you get ( you need to push it to stack and when you get ) you need to pop it. And at the end just need to check stack is still empty or not. if stack is empty that means parentheses are valid.\nEdge case:\nWhen there's no element in the stack and you have ) that means there's no ( bracket to match with it. so it returns false.\n\n\nconst validParentheses = (str) => {\n const stack = [];\n\n for (let parentheses of str) {\n if (parentheses == '(') stack.push(parentheses);\n else {\n if (!stack.length) return false;\n stack.pop();\n }\n }\n return !stack.length;\n}\n\nconsole.log(validParentheses(\"()\")); \nconsole.log(validParentheses(\")(()))\")); \nconsole.log(validParentheses(\"(\")); \nconsole.log(validParentheses(\"(())((()())())\"));\n\n\n\n", "You've overcomplicated things\nSimply counting is enough\n\n\n// \"()\" => true\n// \")(()))\" => false\n// \"(\" => false\n// \"(())((()())())\" => true\nfunction validParentheses(parens) {\n let lefts = 0\n for (const par of parens) {\n if (par === '(') {\n lefts += 1\n } else {\n lefts -= 1\n }\n if (lefts < 0) return false\n }\n if (lefts !== 0) return false\n return true\n}\n\nconsole.log(validParentheses('()'));\nconsole.log(validParentheses('(()))(()'));\nconsole.log(validParentheses('('));\nconsole.log(validParentheses('(())((()())())'));\n\n\n\n" ]
[ 1, 1 ]
[]
[]
[ "for_loop", "javascript", "loops" ]
stackoverflow_0074656885_for_loop_javascript_loops.txt
Q: How to select specific items in IN sql I have a table "products" with a column called "store_id". This table has a lot af products from many stores. I need to select 4 random products from 4 specific stores (id: 1, 34, 45, 100). How can I do that? I've tried to like this: SELECT * FROM products WHERE store_id IN (1, 34, 45, 100) But that query returns duplicated records (by store_id). I need the following result: store_id title 1 title a 34 title b 45 title c 100 title d A: Use the DISTINCT construct to get unique records for the desired column: SELECT distinct on (store_id) store_id, title FROM products WHERE store_id IN (1, 34, 45, 100); Demo in sqldaddy.io A: To get a true random pick of the products use a row_number function with random order. This query shows all data with a random index of the product for each store select products.*, row_number() over (partition by store_id order by random()) rn from products where store_id in (1,34) store_id|product_id|title|rn| --------+----------+-----+--+ 1| 1|a | 1| 1| 3|c | 2| 1| 2|b | 3| 34| 6|f | 1| 34| 7|g | 2| 34| 8|h | 3| 34| 5|e | 4| 34| 4|d | 5| To get only one product per store simple filter with rn=1 with prod as ( select products.*, row_number() over (partition by store_id order by random()) rn from products where store_id in (1,34) ) select store_id, title from prod where rn = 1 ; store_id|title| --------+-----+ 1|a | 34|e | Note this query will produce a different result on each run. If you need a stability you must call setseed before each execution. E.g. SELECT setseed(1)
How to select specific items in IN sql
I have a table "products" with a column called "store_id". This table has a lot af products from many stores. I need to select 4 random products from 4 specific stores (id: 1, 34, 45, 100). How can I do that? I've tried to like this: SELECT * FROM products WHERE store_id IN (1, 34, 45, 100) But that query returns duplicated records (by store_id). I need the following result: store_id title 1 title a 34 title b 45 title c 100 title d
[ "Use the DISTINCT construct to get unique records for the desired column:\nSELECT distinct on (store_id) store_id, title FROM products WHERE store_id IN (1, 34, 45, 100);\n\nDemo in sqldaddy.io\n", "To get a true random pick of the products use a row_number function with random order.\nThis query shows all data with a random index of the product for each store\nselect products.*,\nrow_number() over (partition by store_id order by random()) rn\nfrom products\nwhere store_id in (1,34)\n\nstore_id|product_id|title|rn|\n--------+----------+-----+--+\n 1| 1|a | 1|\n 1| 3|c | 2|\n 1| 2|b | 3|\n 34| 6|f | 1|\n 34| 7|g | 2|\n 34| 8|h | 3|\n 34| 5|e | 4|\n 34| 4|d | 5|\n\nTo get only one product per store simple filter with rn=1\nwith prod as (\nselect products.*,\nrow_number() over (partition by store_id order by random()) rn\nfrom products\nwhere store_id in (1,34)\n)\nselect store_id, title from prod\nwhere rn = 1\n;\n\nstore_id|title|\n--------+-----+\n 1|a |\n 34|e |\n\nNote this query will produce a different result on each run. If you need a stability you must call setseed before each execution. E.g.\nSELECT setseed(1)\n\n" ]
[ 1, 1 ]
[]
[]
[ "postgresql" ]
stackoverflow_0074655565_postgresql.txt
Q: Sql Server: Select String array of JSON Given the following test data: declare @mg nvarchar(max); set @mg = '{"fiskepind":["ko","hest","gris"]}'; select @mg, JSON_VALUE(@mg,'$.fiskepind') How do i get returned a column with: ko,hest,gris Example returns: NULL, and i dont want to [index] to only get one returned. A: Starting from SQL Server 2017, a possible solution is a combination of OPENJSON() and STRING_AGG(). SELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY CONVERT(int, [key])) AS Result FROM OPENJSON(@mg, '$.fiskepind') Note, that JSON_VALUE() returns a scalar value, so the NULL value is the expected result when you try to extract a JSON array ('$.fiskepind') from the input JSON text. A: If you just want a combine list, you can use OPENJSON to get a table and then use FOR XML PATH or STRING_AGG to combine into a single string. declare @mg nvarchar(max); set @mg = '{"fiskepind":["ko","hest","gris"]}'; select @mg, JSON_VALUE(@mg,'$.fiskepind') , STUFF(( SELECT ',' + value FROM OPENJSON(@mg, '$.fiskepind') FOR XML PATH('') ),1,1,'') as combined_list
Sql Server: Select String array of JSON
Given the following test data: declare @mg nvarchar(max); set @mg = '{"fiskepind":["ko","hest","gris"]}'; select @mg, JSON_VALUE(@mg,'$.fiskepind') How do i get returned a column with: ko,hest,gris Example returns: NULL, and i dont want to [index] to only get one returned.
[ "Starting from SQL Server 2017, a possible solution is a combination of OPENJSON() and STRING_AGG().\nSELECT STRING_AGG([value], ',') WITHIN GROUP (ORDER BY CONVERT(int, [key])) AS Result\nFROM OPENJSON(@mg, '$.fiskepind')\n\nNote, that JSON_VALUE() returns a scalar value, so the NULL value is the expected result when you try to extract a JSON array ('$.fiskepind') from the input JSON text.\n", "If you just want a combine list, you can use OPENJSON to get a table and then use FOR XML PATH or STRING_AGG to combine into a single string.\ndeclare @mg nvarchar(max);\nset @mg = '{\"fiskepind\":[\"ko\",\"hest\",\"gris\"]}';\n\nselect @mg, JSON_VALUE(@mg,'$.fiskepind')\n , STUFF((\n SELECT\n ',' + value\n FROM OPENJSON(@mg, '$.fiskepind')\n FOR XML PATH('')\n ),1,1,'') as combined_list\n\n" ]
[ 1, 0 ]
[]
[]
[ "json", "sql_server" ]
stackoverflow_0074654163_json_sql_server.txt
Q: problems with emoji in discord.js dans sql i work on discord bot , and when a people add the bot to their server , with : bot.on("guildCreate", guild => { let logoUrl = "https://cdn.discordapp.com/icons/"+ guild.id + "/" + guild.icon console.log(guild.name) connection.query("INSERT INTO `servers` (`discord_server_id`, `server_name`, `server_logo`) VALUES ('" + guild.id + "', '" + guild.name + "', '" + logoUrl + "')"); }) But when server have an emoji in the guild.name , the bot crash with this error : A: This is a mysql related problem, so you may need to alter your table using utf8mb4 format: ALTER DATABASE <database> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
problems with emoji in discord.js dans sql
i work on discord bot , and when a people add the bot to their server , with : bot.on("guildCreate", guild => { let logoUrl = "https://cdn.discordapp.com/icons/"+ guild.id + "/" + guild.icon console.log(guild.name) connection.query("INSERT INTO `servers` (`discord_server_id`, `server_name`, `server_logo`) VALUES ('" + guild.id + "', '" + guild.name + "', '" + logoUrl + "')"); }) But when server have an emoji in the guild.name , the bot crash with this error :
[ "This is a mysql related problem, so you may need to alter your table using utf8mb4 format:\nALTER DATABASE <database> CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;\n\n" ]
[ 0 ]
[]
[]
[ "discord", "mysql", "node.js", "sql" ]
stackoverflow_0074645826_discord_mysql_node.js_sql.txt
Q: Rails - how to add parameter to the "params.require(:model).permit" construction? I have following code in the controller: def create @company = Company.new(company_params) .... end private def company_params params.require(:company).permit(...list of columns...).merge(latlng: geocode) end I would need to save to the database the column called slug. The value of this column would be slug = params[:company][:name].parameterize The column slug is not mentioned in the permit list. How to add & save this information to the database? Thanks A: def blog_post_params params.require(:Post).permit(:title,:author,:published,:body) end
Rails - how to add parameter to the "params.require(:model).permit" construction?
I have following code in the controller: def create @company = Company.new(company_params) .... end private def company_params params.require(:company).permit(...list of columns...).merge(latlng: geocode) end I would need to save to the database the column called slug. The value of this column would be slug = params[:company][:name].parameterize The column slug is not mentioned in the permit list. How to add & save this information to the database? Thanks
[ "def blog_post_params\nparams.require(:Post).permit(:title,:author,:published,:body)\nend\n" ]
[ 0 ]
[]
[]
[ "model", "ruby", "ruby_on_rails", "slug" ]
stackoverflow_0024125113_model_ruby_ruby_on_rails_slug.txt
Q: scala.reflect.internal.MissingRequirementError: object java.lang.Object in compiler mirror not found I'am trying to build spark streaming application using sbt package,I can't discover what's the reason of this error. this is some thing of the error scala.reflect.internal.MissingRequirementError: object java.lang.Object in compiler mirror not found. at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16) at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17) at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48) at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40) at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40) and here is the code import org.apache.spark.SparkContext import org.apache.spark._ import org.apache.spark.streaming._ import org.apache.spark.streaming.twitter._ import twitter4j.Status object TrendingHashTags { def main(args: Array[String]): Unit = { val Array(consumerKey, consumerSecret, accessToken, accessTokenSecret, lang, batchInterval, minThreshold, showCount ) = args.take(8) val filters = args.takeRight(args.length - 8) System.setProperty("twitter4j.oauth.consumerKey", consumerKey) System.setProperty("twitter4j.oauth.consumerSecret", consumerSecret) System.setProperty("twitter4j.oauth.accessToken", accessToken) System.setProperty("twitter4j.oauth.accessTokenSecret", accessTokenSecret) val conf = new SparkConf().setAppName("TrendingHashTags") val ssc = new StreamingContext(conf, Seconds(batchInterval.toInt)) val tweets = TwitterUtils.createStream(ssc, None, filters) val tweetsFilteredByLang = tweets.filter{tweet => tweet.getLang() == lang} val statuses = tweetsFilteredByLang.map{ tweet => tweet.getText()} val words = statuses.flatMap{status => status.split("""\s+""")} val hashTags = words.filter{word => word.startsWith("#")} val hashTagPairs = hashTags.map{hashtag => (hashtag, 1)} val tagsWithCounts = hashTagPairs.updateStateByKey( (counts: Seq[Int], prevCount: Option[Int]) => prevCount.map{c => c + counts.sum}.orElse{Some(counts.sum)} ) val topHashTags = tagsWithCounts.filter{ case(t, c) => c > minThreshold.toInt } val sortedTopHashTags = topHashTags.transform{ rdd => rdd.sortBy({case(w, c) => c}, false) } sortedTopHashTags.print(showCount.toInt) ssc.start() ssc.awaitTermination() } } A: I solved this issue ,I found that I used java 9 that isn't compatible with scala version so I migrated from java 9 into java 8. A: I had faced this issue when I had to downgrade my projects Scala version to use a dependency that was compiled in a lower Scala version and could not resolved it even after I made sure JDK and all other dependencies are compatible with the downgraded Scala library version. As @ForeverLearner mentioned above, deleting Scala library versions higher than the one I am now using to compile project from maven repo (/Users/<>/.m2/repository/org/scala-lang/scala-library/...) helped me get rid of this error A: The error means that scala was compiled using a version of java, different from the current version. I am using maven instead of sbt, but the same behavior is observed. Find the java version: > /usr/libexec/java_home -V Matching Java Virtual Machines (2): 15.0.1, x86_64: "OpenJDK 15.0.1" /Users/noname/Library/Java/JavaVirtualMachines/openjdk-15.0.1/Contents/Home 1.8.0_271, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home If you installed scala, while you were on version >1.8 and then downgraded the java version (edited the $JAVA_HOME to point to 1.8), you will get this error. Checked the scala version being used by the project : $ ls -l /Users/noname/.m2/repository/org/scala-lang/scala-library/2.11.11/scala-library-2.11.11.jar -rwxrwxrwx 1 noname staff 0 Nov 17 03:41 /Users/noname/.m2/repository/org/scala-lang/scala-library/2.11.11/scala-library-2.11.11.jar To rectify the issue, remove the scala jar file: $ rm /Users/noname/.m2/repository/org/scala-lang/scala-library/2.11.11/scala-library-2.11.11.jar Now, execute mvn clean install again and the project would compile.
scala.reflect.internal.MissingRequirementError: object java.lang.Object in compiler mirror not found
I'am trying to build spark streaming application using sbt package,I can't discover what's the reason of this error. this is some thing of the error scala.reflect.internal.MissingRequirementError: object java.lang.Object in compiler mirror not found. at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16) at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17) at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48) at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40) at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40) and here is the code import org.apache.spark.SparkContext import org.apache.spark._ import org.apache.spark.streaming._ import org.apache.spark.streaming.twitter._ import twitter4j.Status object TrendingHashTags { def main(args: Array[String]): Unit = { val Array(consumerKey, consumerSecret, accessToken, accessTokenSecret, lang, batchInterval, minThreshold, showCount ) = args.take(8) val filters = args.takeRight(args.length - 8) System.setProperty("twitter4j.oauth.consumerKey", consumerKey) System.setProperty("twitter4j.oauth.consumerSecret", consumerSecret) System.setProperty("twitter4j.oauth.accessToken", accessToken) System.setProperty("twitter4j.oauth.accessTokenSecret", accessTokenSecret) val conf = new SparkConf().setAppName("TrendingHashTags") val ssc = new StreamingContext(conf, Seconds(batchInterval.toInt)) val tweets = TwitterUtils.createStream(ssc, None, filters) val tweetsFilteredByLang = tweets.filter{tweet => tweet.getLang() == lang} val statuses = tweetsFilteredByLang.map{ tweet => tweet.getText()} val words = statuses.flatMap{status => status.split("""\s+""")} val hashTags = words.filter{word => word.startsWith("#")} val hashTagPairs = hashTags.map{hashtag => (hashtag, 1)} val tagsWithCounts = hashTagPairs.updateStateByKey( (counts: Seq[Int], prevCount: Option[Int]) => prevCount.map{c => c + counts.sum}.orElse{Some(counts.sum)} ) val topHashTags = tagsWithCounts.filter{ case(t, c) => c > minThreshold.toInt } val sortedTopHashTags = topHashTags.transform{ rdd => rdd.sortBy({case(w, c) => c}, false) } sortedTopHashTags.print(showCount.toInt) ssc.start() ssc.awaitTermination() } }
[ "I solved this issue ,I found that I used java 9 that isn't compatible with scala version so I migrated from java 9 into java 8. \n", "I had faced this issue when I had to downgrade my projects Scala version to use a dependency that was compiled in a lower Scala version and could not resolved it even after I made sure JDK and all other dependencies are compatible with the downgraded Scala library version.\nAs @ForeverLearner mentioned above, deleting Scala library versions higher than the one I am now using to compile project from maven repo (/Users/<>/.m2/repository/org/scala-lang/scala-library/...) helped me get rid of this error\n", "The error means that scala was compiled using a version of java, different from the current version.\nI am using maven instead of sbt, but the same behavior is observed.\nFind the java version:\n> /usr/libexec/java_home -V\nMatching Java Virtual Machines (2):\n 15.0.1, x86_64: \"OpenJDK 15.0.1\" /Users/noname/Library/Java/JavaVirtualMachines/openjdk-15.0.1/Contents/Home\n 1.8.0_271, x86_64: \"Java SE 8\" /Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home\n\nIf you installed scala, while you were on version >1.8 and then downgraded the java version (edited the $JAVA_HOME to point to 1.8), you will get this error.\nChecked the scala version being used by the project :\n$ ls -l /Users/noname/.m2/repository/org/scala-lang/scala-library/2.11.11/scala-library-2.11.11.jar\n-rwxrwxrwx 1 noname staff 0 Nov 17 03:41 /Users/noname/.m2/repository/org/scala-lang/scala-library/2.11.11/scala-library-2.11.11.jar\n\nTo rectify the issue, remove the scala jar file:\n$ rm /Users/noname/.m2/repository/org/scala-lang/scala-library/2.11.11/scala-library-2.11.11.jar\n\nNow, execute mvn clean install again and the project would compile.\n" ]
[ 72, 2, 1 ]
[ "The above fix resolved my issue as well (setting Java 8) , If you are using Intellij you can go to Project Settings and under Project change the Project SDK to 1.8 .\n" ]
[ -1 ]
[ "apache_spark", "bigdata", "scala" ]
stackoverflow_0039791996_apache_spark_bigdata_scala.txt
Q: radioMatrixInput from shinySurvey doesn't work with incomplete responses I'm working with this package (shinySurveys) and I can use it pretty easily. I'm facing one issue regarding the radioMatrixInput object. I can't seem to get the responses out of the object unless all options are completed, and that's my challenge, the user can leave some options unanswered. So, if question has 4 options, he can answer 2 and leave 2 without selecting an option for them. I'm providing an example of the behaviour I'm describing. I've tried observe and observeEvent but both didn't work. if (interactive()) { df <- data.frame( question = c(rep("I love sushi.", 3), rep("I love chocolate.",3), rep("I love vegetables.",3)), option = c(rep(c("Disagree", "Neutral", "Agree"), 3)), input_type = c(rep("matrix", 9)), # For matrix questions, the IDs should be the same for each question # but different for each matrix input unit input_id = c(rep("matId", 9)), dependence = NA, dependence_value = NA, required = FALSE ) library(shiny) library(shinySurveys) ui <- fluidPage( surveyOutput(df), verbatimTextOutput('debug01') ) server <- function(input, output, session) { renderSurvey() observe({ print(input$matId) }) output$debug01 <- renderPrint({input$matId}) observeEvent(input$submit, { print(input$matId) showModal(modalDialog( title = "Congrats, you completed your first shinysurvey!", "You can customize what actions happen when a user finishes a survey using input$submit." )) }) } shinyApp(ui, server) } This works fine as long as I provide an answer to all the option. When I select only one option, the object doesn't get any answers back to my print function in the server. Any of you would happen to know how to access that data from the server part of shiny? A: After sometime thinking about this I have solved my own challenge. What I've done is I've created an extended input type using the object radioMatrixInput from the package shinyRadioMatrix. The matrix radio input already exist in shinysurveys but as I explained in my issue above it requires the user to always respond all questions before one can extract the answers with the function getSurveyData and in my case users should only respond 2 of the 4 options per question. On the contrary, this new radioMatrixInput allows me to get the answers only 2 answers from the users leaving the other 2 blanks. For this to work I had to re-arrange the options for each question into one line so they can be assigned to my new extended input type, let's call it 'matx'. The definition of this new type is as follow: extendInputType(input_type = "matx", { shinyRadioMatrix::radioMatrixInput( inputId = surveyID(), rowIDs = unlist(strsplit(surveyLabel(), ",")), selected = NULL, rowLLabels = c("","","",""), choices = unlist(strsplit(surveyOptions(), ",")), rowIDsName = paste("Question",substr(surveyID(), 11,12)) ) }) For this extension to work one has to use the helper functions: surveyID(), surveyLabel() and surveyOptions(). The last two bring back the question and the options from the dataframe that holds the questions. As for my dataframe, each question contains four questions separated by comma, same with the options. In my case options are always two (most and least). see image below enter image description here So considering that the helper functions will return a vector of strings separated by commas I have used strsplit and unlist to separate the questions and convert them into a vector that radioMatrixInput can use and read. After doing that this is how my questions look in shiny: enter image description here There you have it, hope this helps anyone facing a similar challenge than mine. All the best!
radioMatrixInput from shinySurvey doesn't work with incomplete responses
I'm working with this package (shinySurveys) and I can use it pretty easily. I'm facing one issue regarding the radioMatrixInput object. I can't seem to get the responses out of the object unless all options are completed, and that's my challenge, the user can leave some options unanswered. So, if question has 4 options, he can answer 2 and leave 2 without selecting an option for them. I'm providing an example of the behaviour I'm describing. I've tried observe and observeEvent but both didn't work. if (interactive()) { df <- data.frame( question = c(rep("I love sushi.", 3), rep("I love chocolate.",3), rep("I love vegetables.",3)), option = c(rep(c("Disagree", "Neutral", "Agree"), 3)), input_type = c(rep("matrix", 9)), # For matrix questions, the IDs should be the same for each question # but different for each matrix input unit input_id = c(rep("matId", 9)), dependence = NA, dependence_value = NA, required = FALSE ) library(shiny) library(shinySurveys) ui <- fluidPage( surveyOutput(df), verbatimTextOutput('debug01') ) server <- function(input, output, session) { renderSurvey() observe({ print(input$matId) }) output$debug01 <- renderPrint({input$matId}) observeEvent(input$submit, { print(input$matId) showModal(modalDialog( title = "Congrats, you completed your first shinysurvey!", "You can customize what actions happen when a user finishes a survey using input$submit." )) }) } shinyApp(ui, server) } This works fine as long as I provide an answer to all the option. When I select only one option, the object doesn't get any answers back to my print function in the server. Any of you would happen to know how to access that data from the server part of shiny?
[ "After sometime thinking about this I have solved my own challenge. What I've done is I've created an extended input type using the object radioMatrixInput from the package shinyRadioMatrix. The matrix radio input already exist in shinysurveys but as I explained in my issue above it requires the user to always respond all questions before one can extract the answers with the function getSurveyData and in my case users should only respond 2 of the 4 options per question. On the contrary, this new radioMatrixInput allows me to get the answers only 2 answers from the users leaving the other 2 blanks.\nFor this to work I had to re-arrange the options for each question into one line so they can be assigned to my new extended input type, let's call it 'matx'. The definition of this new type is as follow:\nextendInputType(input_type = \"matx\", {\n shinyRadioMatrix::radioMatrixInput(\n inputId = surveyID(),\n rowIDs = unlist(strsplit(surveyLabel(), \",\")),\n selected = NULL,\n rowLLabels = c(\"\",\"\",\"\",\"\"),\n choices = unlist(strsplit(surveyOptions(), \",\")),\n rowIDsName = paste(\"Question\",substr(surveyID(), 11,12))\n )\n})\n\nFor this extension to work one has to use the helper functions: surveyID(), surveyLabel() and surveyOptions(). The last two bring back the question and the options from the dataframe that holds the questions.\nAs for my dataframe, each question contains four questions separated by comma, same with the options. In my case options are always two (most and least). see image below\nenter image description here\nSo considering that the helper functions will return a vector of strings separated by commas I have used strsplit and unlist to separate the questions and convert them into a vector that radioMatrixInput can use and read.\nAfter doing that this is how my questions look in shiny:\nenter image description here\nThere you have it, hope this helps anyone facing a similar challenge than mine.\nAll the best!\n" ]
[ 0 ]
[]
[]
[ "r", "shiny", "shiny_reactivity" ]
stackoverflow_0074637795_r_shiny_shiny_reactivity.txt
Q: Sort array of objects by 2 conditions I need to sort array of objects by 2 conditions sort by value if names are the same show them next to each other in value order Example example: https://codesandbox.io/s/relaxed-dhawan-sfryng?file=/src/index.js A: To sort an array of objects by multiple conditions, you can use the Array.prototype.sort() method and provide a custom sorting function. The custom sorting function should take two objects as arguments and return a value indicating how they should be ordered in the sorted array. Here is an example of how you might implement a custom sorting function that sorts the array by value, and then by name if the values are the same: function sortByValueAndName(a, b) { // If the values are different, sort by value if (a.value !== b.value) { return a.value - b.value; } // If the values are the same, sort by name if (a.name !== b.name) { return a.name < b.name ? -1 : 1; } // If both the values and the names are the same, the objects are equal return 0; } // Example array of objects const objects = [ { name: "John", value: 10 }, { name: "Jane", value: 10 }, { name: "Alice", value: 5 }, ]; // Sort the array using the custom sorting function objects.sort(sortByValueAndName); // The sorted array will be: // [ // { name: "Alice", value: 5 }, // { name: "John", value: 10 }, // { name: "Jane", value: 10 }, // ] Note that the sort() method modifies the array in place, so you don't need to assign the result of the sort() method to a new variable. The sorted array will be available in the same variable that you called sort() on. A: I provide a solution for it,it's a bit complexed,you can read the comment I have added const array = [ { name: "John", value: 5 }, { name: "David", value: 6 }, { name: "John", value: 2 }, { name: "Michael", value: 4 } ]; const customSort = (data) => { // create a new array to make elements have same name together let newArray = data.reduce((a,v) => { let obj = a.find(e => e.name === v.name) if(obj){ obj.datas.push(v) }else{ a.push({'name':v.name,'datas':[v]}) } return a },[]) // sort data in the new array by value newArray.forEach(e => { e.datas.sort((a,b) => a.value - b.value) }) // create a value object with boolean value to avoid add duplicate element let values = data.reduce((a,v) => { a[v.value] = false return a },{}) let keys = Object.keys(values) let result = [] for(k of keys){ // if the value has iterated,then skip it if(values[k]){ continue } // find data by value let arr = newArray.filter(e1 => e1.datas.some(e2 => e2.value == k)).flatMap(e => e.datas) result.push(...arr) // mark the value already added arr.forEach(e => { values[e.value] = true }) } return result } console.log(customSort(array)) A: Hope it helps: const arr = [ { name: "John", value: 5 }, { name: "David", value: 6 }, { name: "John", value: 2 }, { name: "Michael", value: 4 } ]; const groupByItems = []; // Get index of the item based on name in groupByItems array const getIndex = (name) => { let index = -1; groupByItems.forEach((groupByItem, _index) => { if(groupByItem.name === name) { index = _index; } }); return index; } // Group items by their name const groupByName = () => { arr.forEach((item) => { const name = item.name; const value = item.value; let index = getIndex(name); //Means that the [name] has not added before, so we should add it if(index === -1) { groupByItems.push({ name: name, // Hold all values of the [name] values: [], // Hold minValue to sort groupByItems by that minValue: Infinity }); index = groupByItems.length - 1; } // Add current value to the list of values groupByItems[index].values.push(value); // Update minValue if(groupByItems[index].minValue > value) { groupByItems[index].minValue = value; } }); } groupByName(); //Sort by minValue and then return final objects const result = groupByItems.sort((a, b) => a.minValue - b.minValue).flatMap((item) => ( item.values.sort((firstValue, secondValue) => firstValue - secondValue).map((value) => { return { name: item.name, value: value } }) )); console.log(result);
Sort array of objects by 2 conditions
I need to sort array of objects by 2 conditions sort by value if names are the same show them next to each other in value order Example example: https://codesandbox.io/s/relaxed-dhawan-sfryng?file=/src/index.js
[ "To sort an array of objects by multiple conditions, you can use the Array.prototype.sort() method and provide a custom sorting function. The custom sorting function should take two objects as arguments and return a value indicating how they should be ordered in the sorted array.\nHere is an example of how you might implement a custom sorting function that sorts the array by value, and then by name if the values are the same:\nfunction sortByValueAndName(a, b) {\n // If the values are different, sort by value\n if (a.value !== b.value) {\n return a.value - b.value;\n }\n\n // If the values are the same, sort by name\n if (a.name !== b.name) {\n return a.name < b.name ? -1 : 1;\n }\n\n // If both the values and the names are the same, the objects are equal\n return 0;\n}\n\n// Example array of objects\nconst objects = [\n { name: \"John\", value: 10 },\n { name: \"Jane\", value: 10 },\n { name: \"Alice\", value: 5 },\n];\n\n// Sort the array using the custom sorting function\nobjects.sort(sortByValueAndName);\n\n// The sorted array will be:\n// [\n// { name: \"Alice\", value: 5 },\n// { name: \"John\", value: 10 },\n// { name: \"Jane\", value: 10 },\n// ]\n\nNote that the sort() method modifies the array in place, so you don't need to assign the result of the sort() method to a new variable. The sorted array will be available in the same variable that you called sort() on.\n", "I provide a solution for it,it's a bit complexed,you can read the comment I have added\n\n\nconst array = [\n {\n name: \"John\",\n value: 5\n },\n {\n name: \"David\",\n value: 6\n },\n {\n name: \"John\",\n value: 2\n },\n {\n name: \"Michael\",\n value: 4\n }\n];\n\nconst customSort = (data) => {\n \n // create a new array to make elements have same name together\n let newArray = data.reduce((a,v) => {\n let obj = a.find(e => e.name === v.name)\n if(obj){\n obj.datas.push(v) \n }else{\n a.push({'name':v.name,'datas':[v]})\n }\n return a\n },[])\n \n // sort data in the new array by value\n newArray.forEach(e => {\n e.datas.sort((a,b) => a.value - b.value) \n })\n\n // create a value object with boolean value to avoid add duplicate element\n let values = data.reduce((a,v) => {\n a[v.value] = false\n return a\n },{})\n let keys = Object.keys(values)\n\n let result = []\n for(k of keys){\n \n // if the value has iterated,then skip it\n if(values[k]){\n continue\n }\n // find data by value\n let arr = newArray.filter(e1 => e1.datas.some(e2 => e2.value == k)).flatMap(e => e.datas)\n result.push(...arr)\n \n // mark the value already added\n arr.forEach(e => {\n values[e.value] = true \n })\n }\n return result\n}\n\n\nconsole.log(customSort(array))\n\n\n\n", "Hope it helps:\n\n\nconst arr = [\n {\n name: \"John\",\n value: 5\n },\n {\n name: \"David\",\n value: 6\n },\n {\n name: \"John\",\n value: 2\n },\n {\n name: \"Michael\",\n value: 4\n }\n];\n\nconst groupByItems = [];\n\n// Get index of the item based on name in groupByItems array\nconst getIndex = (name) => {\n let index = -1;\n groupByItems.forEach((groupByItem, _index) => {\n if(groupByItem.name === name) {\n index = _index;\n }\n });\n return index;\n}\n\n// Group items by their name\nconst groupByName = () => {\n arr.forEach((item) => {\n const name = item.name;\n const value = item.value;\n let index = getIndex(name);\n //Means that the [name] has not added before, so we should add it\n if(index === -1) {\n groupByItems.push({\n name: name,\n // Hold all values of the [name]\n values: [],\n // Hold minValue to sort groupByItems by that\n minValue: Infinity\n });\n index = groupByItems.length - 1;\n }\n // Add current value to the list of values\n groupByItems[index].values.push(value);\n // Update minValue\n if(groupByItems[index].minValue > value) {\n groupByItems[index].minValue = value;\n }\n });\n}\n\ngroupByName();\n\n//Sort by minValue and then return final objects\nconst result = groupByItems.sort((a, b) => a.minValue - b.minValue).flatMap((item) => (\n item.values.sort((firstValue, secondValue) => firstValue - secondValue).map((value) => {\n return {\n name: item.name,\n value: value\n }\n })\n));\n\nconsole.log(result);\n\n\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "javascript", "typescript" ]
stackoverflow_0074655807_javascript_typescript.txt
Q: Using the stack to remove vowels off a string but im getting the original string with vowels still on it im working on some code using mips that asks the user to wnter in a string, and remove the vowels from that string with the help of the Stack, this is what i have so far, sorry for the slight sloppiness as im fairly new to MIPS .text .globl main main: li $v0, 4 la $a0, prompt # prompt user for string syscall li $v0, 8 # store string in str buffer la $a0, str li $a1, 120 syscall li $t4, 0 li $t1, 0 addiu $sp, $sp, -4 # push a NUL byte onto the stack to signal its bottom sw $zero, ($sp) # remember, always access the stact using words, not bytes! loop: lbu $t0, str($t1) nop nop beqz $t0, end nop nop addiu $t1, $t1, 1 #traverse through string until you reach the end of the string j loop end: addiu $t1, -2 # backing up the index twice to start at the last character of string loop2: lbu $t0, str($t1) nop nop beq $t1, $t4, end2 nop li $t5, 'a' beq $t5, $t0, vowel # picking up all of the consonants and putting them in the stack nop li $t5, 'e' beq $t5, $t0, vowel nop li $t5, 'i' beq $t5, $t0, vowel nop li $t5, 'o' beq $t5, $t0, vowel nop li $t5, 'u' beq $t5, $t0, vowel nop vowel: addiu $t1, $t1, -1 # decrement index of string addiu $sp, $sp, -4 # push sw $t0, ($sp) nop j loop2 nop nop end2: li $t1, 0 # index of first byte of str buffer popl: lw $t0, ($sp) # pop a char off the stack addiu $sp, $sp, 4 # adjust $sp in load delay slot beqz $t0, done # NUL byte means empty stack nop # branch delay slot sw $t0, str($t1) # store at string[$t1] nop addiu $t1, $t1, 1 # increment the index (in load delay slot) j popl # loop nop # branch delay slot # print the reversed string done: li $v0, 4 # print string service code la $a0, str # address of string syscall li $v0, 10 # exit program syscall li $v0, 10 syscall .data prompt: .asciiz "enter a word" number: str: .space 128 i feel like a lot of my issues are coming on how i store the individual characters in the stack as well as trying to pop them out back into the character buffer before the printing syscall. any guidance will be appreciated, thanks A: I think the problem is here: popl: lw $t0, ($sp) # pop a char off the stack addiu $sp, $sp, 4 # adjust $sp in load delay slot beqz $t0, done # NUL byte means empty stack nop # branch delay slot sw $t0, str($t1) # store at string[$t1] nop addiu $t1, $t1, 1 # increment the index (in load delay slot) j popl # loop nop # branch delay slot See the line sw $t0, str($t1)? That should be sb $t0,str($t1). You're storing the desired letters as 32-bit words on the stack because you have to, as the stack needs to be word-aligned at all times. However, each character in the string takes up only one byte, so you need to use sb to store them into the string. As an example, I'll show what happens if your code were run with the input string "BOOBOO". This represents what happens on the first pass through: popl: lw $t0, ($sp) # $t0 = 0x00000042 (0x42 in ASCII = 'B') addiu $sp, $sp, 4 # adjust $sp in load delay slot beqz $t0, done # NUL byte means empty stack nop # branch delay slot sw $t0, str($t1) # store at string[$t1] nop # load delay slot After the store, we have the following: str: .word 0x00000042 #could be 0x42000000 depending on your CPU's endianness .space 124 After storing we execute the following and loop again: addiu $t1, $t1, 1 # increment the index (in load delay slot) j popl # loop nop # branch delay slot If you had used sb $t0, str($t1), the addiu $t1,$t1,1 wouldn't be a problem. But since you're using sw, you get an error. This is because lw and sw in MIPS can only be used on addresses that are word-aligned, i.e. their hex value ends in 0, 4, 8, or C. Failure to do so will result in an alignment fault. The statement sw $t0, str($t1) became unaligned when you executed addiu $t1, $t1, 1. Side note: It's not a good practice to use labels as constant offsets like you have here. Reason being is that they can cause similar alignment faults if you store a string above them like so: foo: .asciiz "Hello" #total of 6 bytes, so the array below is unaligned bar: .space 128 #doing "sw $t1,bar($t0) would cause an alignment fault if $t0 = 0.
Using the stack to remove vowels off a string but im getting the original string with vowels still on it
im working on some code using mips that asks the user to wnter in a string, and remove the vowels from that string with the help of the Stack, this is what i have so far, sorry for the slight sloppiness as im fairly new to MIPS .text .globl main main: li $v0, 4 la $a0, prompt # prompt user for string syscall li $v0, 8 # store string in str buffer la $a0, str li $a1, 120 syscall li $t4, 0 li $t1, 0 addiu $sp, $sp, -4 # push a NUL byte onto the stack to signal its bottom sw $zero, ($sp) # remember, always access the stact using words, not bytes! loop: lbu $t0, str($t1) nop nop beqz $t0, end nop nop addiu $t1, $t1, 1 #traverse through string until you reach the end of the string j loop end: addiu $t1, -2 # backing up the index twice to start at the last character of string loop2: lbu $t0, str($t1) nop nop beq $t1, $t4, end2 nop li $t5, 'a' beq $t5, $t0, vowel # picking up all of the consonants and putting them in the stack nop li $t5, 'e' beq $t5, $t0, vowel nop li $t5, 'i' beq $t5, $t0, vowel nop li $t5, 'o' beq $t5, $t0, vowel nop li $t5, 'u' beq $t5, $t0, vowel nop vowel: addiu $t1, $t1, -1 # decrement index of string addiu $sp, $sp, -4 # push sw $t0, ($sp) nop j loop2 nop nop end2: li $t1, 0 # index of first byte of str buffer popl: lw $t0, ($sp) # pop a char off the stack addiu $sp, $sp, 4 # adjust $sp in load delay slot beqz $t0, done # NUL byte means empty stack nop # branch delay slot sw $t0, str($t1) # store at string[$t1] nop addiu $t1, $t1, 1 # increment the index (in load delay slot) j popl # loop nop # branch delay slot # print the reversed string done: li $v0, 4 # print string service code la $a0, str # address of string syscall li $v0, 10 # exit program syscall li $v0, 10 syscall .data prompt: .asciiz "enter a word" number: str: .space 128 i feel like a lot of my issues are coming on how i store the individual characters in the stack as well as trying to pop them out back into the character buffer before the printing syscall. any guidance will be appreciated, thanks
[ "I think the problem is here:\npopl: \n lw $t0, ($sp) # pop a char off the stack\n addiu $sp, $sp, 4 # adjust $sp in load delay slot\n beqz $t0, done # NUL byte means empty stack\n nop # branch delay slot\n sw $t0, str($t1) # store at string[$t1]\n nop\n addiu $t1, $t1, 1 # increment the index (in load delay slot)\n j popl # loop\n nop # branch delay slot\n\nSee the line sw $t0, str($t1)? That should be sb $t0,str($t1). You're storing the desired letters as 32-bit words on the stack because you have to, as the stack needs to be word-aligned at all times. However, each character in the string takes up only one byte, so you need to use sb to store them into the string.\nAs an example, I'll show what happens if your code were run with the input string \"BOOBOO\".\nThis represents what happens on the first pass through:\npopl: \n lw $t0, ($sp) # $t0 = 0x00000042 (0x42 in ASCII = 'B')\n addiu $sp, $sp, 4 # adjust $sp in load delay slot\n beqz $t0, done # NUL byte means empty stack\n nop # branch delay slot\n sw $t0, str($t1) # store at string[$t1]\n nop # load delay slot \n\nAfter the store, we have the following:\nstr:\n.word 0x00000042 #could be 0x42000000 depending on your CPU's endianness\n.space 124\n\nAfter storing we execute the following and loop again:\n addiu $t1, $t1, 1 # increment the index (in load delay slot)\n j popl # loop\n nop # branch delay slot\n\nIf you had used sb $t0, str($t1), the addiu $t1,$t1,1 wouldn't be a problem. But since you're using sw, you get an error. This is because lw and sw in MIPS can only be used on addresses that are word-aligned, i.e. their hex value ends in 0, 4, 8, or C. Failure to do so will result in an alignment fault. The statement sw $t0, str($t1) became unaligned when you executed addiu $t1, $t1, 1.\n\nSide note: It's not a good practice to use labels as constant offsets like you have here. Reason being is that they can cause similar alignment faults if you store a string above them like so:\nfoo: .asciiz \"Hello\" #total of 6 bytes, so the array below is unaligned\nbar: .space 128 #doing \"sw $t1,bar($t0) would cause an alignment fault if $t0 = 0.\n\n" ]
[ 0 ]
[]
[]
[ "assembly", "mips" ]
stackoverflow_0074383869_assembly_mips.txt
Q: How to call another ECS Fargate container from nginx container? Lets say I have 2 containers. One with nginx and and another with a simple app. Each container has his own ECR repo image and his own Task Definition. My nginx container is running in a public subnet with a public IP. How do I pass the request from nginx to my container like this: proxy_pass app_container:9000; How can I make my second container only visible to nginx container? Should I put him in a private subnet? Do I need to map a port for the app container in the task definition? Should I use Cloud Map? Should I call him with localhost:9000? Will the container be called the same as it is in the task definition? I tried using service discovery but I still dont know how to call my container. I created the container, its running, but my nginx container cant reach him doesnt matter how I try, the documentation doesnt explain it well. How exactly should i call my container? A: How can I make my second container only visible to nginx container? Should I put him in a private subnet? Private subnet is fine here yes. Do I need to map a port for the app container in the task definition? No, they are running on two separate services, since you are using two separate task definitions. So port mapping isn't an option here. Should I use Cloud Map? No, just use ECS Service Discovery. Should I call him with localhost:9000? No, that would only work if both containers were in the same task definition. And to be honest, that is probably the correct solution for this sort of thing. Running Nginx on a completely separate server is unnecessary and makes this all much more complicated. Will the container be called the same as it is in the task definition? No, you either have the option of using Service Discovery, and then using the name you gave the service in the Service Discovery namespace, or moving both of the containers into the same task definition and using localhost for inter-service communication. I tried using service discovery but I still dont know how to call my container. I created the container, its running, but my nginx container cant reach him doesnt matter how I try, the documentation doesnt explain it well. How exactly should i call my container? Without any details about what you did exactly, it's impossible to point out what you did wrong. When you created a private DNS namespace for Service Discovery, what DNS name did you use? The service address would be the service name + the private DNS name.
How to call another ECS Fargate container from nginx container?
Lets say I have 2 containers. One with nginx and and another with a simple app. Each container has his own ECR repo image and his own Task Definition. My nginx container is running in a public subnet with a public IP. How do I pass the request from nginx to my container like this: proxy_pass app_container:9000; How can I make my second container only visible to nginx container? Should I put him in a private subnet? Do I need to map a port for the app container in the task definition? Should I use Cloud Map? Should I call him with localhost:9000? Will the container be called the same as it is in the task definition? I tried using service discovery but I still dont know how to call my container. I created the container, its running, but my nginx container cant reach him doesnt matter how I try, the documentation doesnt explain it well. How exactly should i call my container?
[ "\nHow can I make my second container only visible to nginx container? Should I put him in a private subnet?\n\nPrivate subnet is fine here yes.\n\nDo I need to map a port for the app container in the task definition?\n\nNo, they are running on two separate services, since you are using two separate task definitions. So port mapping isn't an option here.\n\nShould I use Cloud Map?\n\nNo, just use ECS Service Discovery.\n\nShould I call him with localhost:9000?\n\nNo, that would only work if both containers were in the same task definition. And to be honest, that is probably the correct solution for this sort of thing. Running Nginx on a completely separate server is unnecessary and makes this all much more complicated.\n\nWill the container be called the same as it is in the task definition?\n\nNo, you either have the option of using Service Discovery, and then using the name you gave the service in the Service Discovery namespace, or moving both of the containers into the same task definition and using localhost for inter-service communication.\n\nI tried using service discovery but I still dont know how to call my container. I created the container, its running, but my nginx container cant reach him doesnt matter how I try, the documentation doesnt explain it well. How exactly should i call my container?\n\nWithout any details about what you did exactly, it's impossible to point out what you did wrong. When you created a private DNS namespace for Service Discovery, what DNS name did you use? The service address would be the service name + the private DNS name.\n" ]
[ 1 ]
[]
[]
[ "amazon_ecs", "amazon_web_services", "aws_fargate" ]
stackoverflow_0074648910_amazon_ecs_amazon_web_services_aws_fargate.txt
Q: Can I bulk gecode addresses from local OSM tile server to get lat/long? I need to geocode a few million addresses within a single country. I know that paid geocode APIs charge for bulk geocoding and/or place limits for queries. I downloaded a map tile server to run within a docker but would like to know how to get address lat/long. I used https://github.com/Overv/openstreetmap-tile-server to set up the openStreet map tile server. Is there a better way of doing this? I am using python- A: You did set up a local tile server, not a geocoder. To perform local bulk geocoding you need a local geocoding server. For an OSM-based geocoder take a look at Nominatim.
Can I bulk gecode addresses from local OSM tile server to get lat/long?
I need to geocode a few million addresses within a single country. I know that paid geocode APIs charge for bulk geocoding and/or place limits for queries. I downloaded a map tile server to run within a docker but would like to know how to get address lat/long. I used https://github.com/Overv/openstreetmap-tile-server to set up the openStreet map tile server. Is there a better way of doing this? I am using python-
[ "You did set up a local tile server, not a geocoder. To perform local bulk geocoding you need a local geocoding server. For an OSM-based geocoder take a look at Nominatim.\n" ]
[ 0 ]
[]
[]
[ "docker", "geocode", "local", "openstreetmap", "python" ]
stackoverflow_0074657183_docker_geocode_local_openstreetmap_python.txt
Q: Why are shell builtins not found when using Kubectl exec I am making a bash script to copy files from a Kubernetes pod running Debian. When I include the following line: kubectl --namespace "$namesp" exec "$pod" -c "$container" -- cd /var it errors out: OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "cd": executable file not found in $PATH: unknown command terminated with exit code 126 I also tried kubectl --namespace "$namesp" exec "$pod" -c "$container" -- builtin kubectl --namespace "$namesp" exec "$pod" -c "$container" -it -- cd /var which gave the same result. I was able to resolve the issue by changing the command to: kubectl --namespace "$namesp" exec "$pod" -c "$container" -- /bin/bash -c "builtin" Would love to understand why the first command(s) don't work and the latter one does. I would have thought that builtin commands are the one group of commands that would always be found, in contrast to commands that rely on the PATH environment variable. A: kubectl exec is used to execute an executable in a running container. The command has to be built into the container. Neither builtin nor cd are valid executables in your container. Only /bin/bash is. To execute a builtin shell command, you have to execute the shell and call it as the command argument like in your third example.
Why are shell builtins not found when using Kubectl exec
I am making a bash script to copy files from a Kubernetes pod running Debian. When I include the following line: kubectl --namespace "$namesp" exec "$pod" -c "$container" -- cd /var it errors out: OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "cd": executable file not found in $PATH: unknown command terminated with exit code 126 I also tried kubectl --namespace "$namesp" exec "$pod" -c "$container" -- builtin kubectl --namespace "$namesp" exec "$pod" -c "$container" -it -- cd /var which gave the same result. I was able to resolve the issue by changing the command to: kubectl --namespace "$namesp" exec "$pod" -c "$container" -- /bin/bash -c "builtin" Would love to understand why the first command(s) don't work and the latter one does. I would have thought that builtin commands are the one group of commands that would always be found, in contrast to commands that rely on the PATH environment variable.
[ "kubectl exec is used to execute an executable in a running container. The command has to be built into the container.\nNeither builtin nor cd are valid executables in your container. Only /bin/bash is.\nTo execute a builtin shell command, you have to execute the shell and call it as the command argument like in your third example.\n" ]
[ 2 ]
[]
[]
[ "bash", "kubectl", "kubernetes" ]
stackoverflow_0074656942_bash_kubectl_kubernetes.txt
Q: Destructuring props passed to functional component in kotlin In JavaScript, the destructuring of an object is something common. const foo = { a: 1 b: 2 c: 3 }; const {a, b, c } = foo; console.log(a) 1 Is something like this possigle with KotlinJS React? interface FooProps : Props { var a: Int var b: Int var c: Int } val Foo = FC<FooProps> { props -> val(a, b, c) = props ... } This is not working. It gives me Destructuring declaration initializer of type FooProps must have a 'component1()' function A: Kotlin supports destructuring declarations, however they work in a different way than JavaScript. In particular, you can destructure an object like this: val (property1, property2, property3, ..., propertyN) = object assuming that object contains certain methods: operator fun component1() operator fun component2() ... operator fun componentN() Example: class Person(val name: String, val dateOfBirth: LocalDate) { operator fun component1(): String = name operator fun component2(): LocalDate = dateOfBirth } val johnDoe = Person("John", LocalDate.of(1980, JANUARY, 1)) val (name, dob) = johnDoe println("$name -> $dob") // prints John -> 1980-01-01 Use can make use of extension functions to implement this behaviour on classes you don't own. Example: operator fun String.component1(): Int = this.length operator fun String.component2(): Char = this.first() val someString = "Hello, world" val (length, firstChar) = someString println("$length -> $firstChar") // prints 12 -> H
Destructuring props passed to functional component in kotlin
In JavaScript, the destructuring of an object is something common. const foo = { a: 1 b: 2 c: 3 }; const {a, b, c } = foo; console.log(a) 1 Is something like this possigle with KotlinJS React? interface FooProps : Props { var a: Int var b: Int var c: Int } val Foo = FC<FooProps> { props -> val(a, b, c) = props ... } This is not working. It gives me Destructuring declaration initializer of type FooProps must have a 'component1()' function
[ "Kotlin supports destructuring declarations, however they work in a different way than JavaScript.\nIn particular, you can destructure an object like this:\nval (property1, property2, property3, ..., propertyN) = object\n\nassuming that object contains certain methods:\n\noperator fun component1()\noperator fun component2()\n...\noperator fun componentN()\n\nExample:\nclass Person(val name: String, val dateOfBirth: LocalDate) {\n operator fun component1(): String = name\n operator fun component2(): LocalDate = dateOfBirth\n}\n\nval johnDoe = Person(\"John\", LocalDate.of(1980, JANUARY, 1))\n\nval (name, dob) = johnDoe\nprintln(\"$name -> $dob\") // prints John -> 1980-01-01\n\nUse can make use of extension functions to implement this behaviour on classes you don't own. Example:\noperator fun String.component1(): Int = this.length\noperator fun String.component2(): Char = this.first()\n\nval someString = \"Hello, world\"\n\nval (length, firstChar) = someString\nprintln(\"$length -> $firstChar\") // prints 12 -> H\n\n" ]
[ 1 ]
[]
[]
[ "kotlin", "kotlin_js" ]
stackoverflow_0074654027_kotlin_kotlin_js.txt
Q: Most efficient way to do a bulk UPDATE with pairs of input Suppose I want to do a bulk update, setting a=b for a collection of a values. This can easily be done with a sequence of UPDATE queries: UPDATE foo SET value='foo' WHERE id=1 UPDATE foo SET value='bar' WHERE id=2 UPDATE foo SET value='baz' WHERE id=3 But now I suppose I want to do this in bulk. I have a two dimensional array containing the ids and new values: [ [ 1, 'foo' ] [ 2, 'bar' ] [ 3, 'baz' ] ] Is there an efficient way to do these three UPDATEs in a single SQL query? Some solutions I have considered: A temporary table CREATE TABLE temp ...; INSERT INTO temp (id,value) VALUES (....); UPDATE foo USING temp ... But this really just moves the problem. Although it may be easier (or at least less ugly) to do a bulk INSERT, there are still a minimum of three queries. Denormalize the input by passing the data pairs as SQL arrays. This makes the query incredibly ugly, though UPDATE foo USING ( SELECT split_part(x,',',1)::INT AS id, split_part(x,',',2)::VARCHAR AS value FROM ( SELECT UNNEST(ARRAY['1,foo','2,bar','3,baz']) AS x ) AS x; ) SET value=x.value WHERE id=x.id This makes it possible to use a single query, but makes that query ugly, and inefficient (especially for mixed and/or complex data types). Is there a better solution? Or should I resort to multiple UPDATE queries? A: Normally you want to batch-update from a table with sufficient index to make the merge easy: CREATE TEMP TABLE updates_table ( id integer not null primary key , val varchar ); INSERT into updates_table(id, val) VALUES ( 1, 'foo' ) ,( 2, 'bar' ) ,( 3, 'baz' ) ; UPDATE target_table t SET value = u.val FROM updates_table u WHERE t.id = u.id ; So you should probably populate your update_table by something like: INSERT into updates_table(id, val) SELECT split_part(x,',',1)::INT AS id, split_part(x,',',2)::VARCHAR AS value FROM ( SELECT UNNEST(ARRAY['1,foo','2,bar','3,baz']) ) AS x ; Remember: an index (or the primary key) on the id field in the updates_table is important. (but for small sets like this one, a hashjoin will probably by chosen by the optimiser) In addition: for updates, it is important to avoid updates with the same value, these cause extra rowversions to be created + plus the resulting VACUUM activity after the update was committed: UPDATE target_table t SET value = u.val FROM updates_table u WHERE t.id = u.id AND (t.value IS NULL OR t.value <> u.value) ; A: You can use CASE conditional expression: UPDATE foo SET "value" = CASE id WHEN 1 THEN 'foo' WHEN 2 THEN 'bar' WHEN 3 THEN 'baz' END
Most efficient way to do a bulk UPDATE with pairs of input
Suppose I want to do a bulk update, setting a=b for a collection of a values. This can easily be done with a sequence of UPDATE queries: UPDATE foo SET value='foo' WHERE id=1 UPDATE foo SET value='bar' WHERE id=2 UPDATE foo SET value='baz' WHERE id=3 But now I suppose I want to do this in bulk. I have a two dimensional array containing the ids and new values: [ [ 1, 'foo' ] [ 2, 'bar' ] [ 3, 'baz' ] ] Is there an efficient way to do these three UPDATEs in a single SQL query? Some solutions I have considered: A temporary table CREATE TABLE temp ...; INSERT INTO temp (id,value) VALUES (....); UPDATE foo USING temp ... But this really just moves the problem. Although it may be easier (or at least less ugly) to do a bulk INSERT, there are still a minimum of three queries. Denormalize the input by passing the data pairs as SQL arrays. This makes the query incredibly ugly, though UPDATE foo USING ( SELECT split_part(x,',',1)::INT AS id, split_part(x,',',2)::VARCHAR AS value FROM ( SELECT UNNEST(ARRAY['1,foo','2,bar','3,baz']) AS x ) AS x; ) SET value=x.value WHERE id=x.id This makes it possible to use a single query, but makes that query ugly, and inefficient (especially for mixed and/or complex data types). Is there a better solution? Or should I resort to multiple UPDATE queries?
[ "Normally you want to batch-update from a table with sufficient index to make the merge easy:\nCREATE TEMP TABLE updates_table\n ( id integer not null primary key\n , val varchar\n );\nINSERT into updates_table(id, val) VALUES\n ( 1, 'foo' ) ,( 2, 'bar' ) ,( 3, 'baz' )\n ;\n\nUPDATE target_table t\nSET value = u.val\nFROM updates_table u\nWHERE t.id = u.id\n ;\n\nSo you should probably populate your update_table by something like:\n\nINSERT into updates_table(id, val)\nSELECT\n split_part(x,',',1)::INT AS id,\n split_part(x,',',2)::VARCHAR AS value\n FROM (\n SELECT UNNEST(ARRAY['1,foo','2,bar','3,baz']) \n ) AS x\n ;\n\n\nRemember: an index (or the primary key) on the id field in the updates_table is important. (but for small sets like this one, a hashjoin will probably by chosen by the optimiser)\n\nIn addition: for updates, it is important to avoid updates with the same value, these cause extra rowversions to be created + plus the resulting VACUUM activity after the update was committed:\nUPDATE target_table t\n SET value = u.val\n FROM updates_table u\n WHERE t.id = u.id\n AND (t.value IS NULL OR t.value <> u.value)\n ;\n\n", "You can use CASE conditional expression:\nUPDATE foo\nSET \"value\" = CASE id\n WHEN 1 THEN 'foo'\n WHEN 2 THEN 'bar'\n WHEN 3 THEN 'baz'\nEND\n\n" ]
[ 10, 0 ]
[]
[]
[ "bulkupdate", "postgresql", "sql_update" ]
stackoverflow_0028723251_bulkupdate_postgresql_sql_update.txt
Q: Where to reset the value of operator in calculator? This is a live demo of my calculator: https://kepplin.github.io/odin-calculator/ After the equals button is pressed and the calculation is displayed, if a number button is pressed, then instead of starting a new calculation, the calculator evaluates with the operator of the previous calculation. I have 3 global variables: num1, num2, operator. As well as a previous display and current display. Example of the problem (step-by-step): 12 console.log(num1) // 12 console.log(num2) // console.log(operator) // 12 + console.log(num1) // console.log(num2) // 12 console.log(operator) // + 12 + 4 console.log(num1) // 4 console.log(num2) // 12 console.log(operator) // + After the '=' button is pressed, the calculator displays: 16 console.log(num1) // console.log(num2) // 16 console.log(operator) // + The calculator immediately evaluates if there are values for num1, num2, and operator. The problem comes here, if the user wants to start a different calculation (e.g, 5 - 4): 5 console.log(num1) // 5 console.log(num2) // 16 console.log(operator) // + 5 - console.log(num1) // console.log(num2) // 21 console.log(operator) // - The calculator did 5 + 16. I want the values of num1, num2 and operator to be reset back to ' ' if a number button is pressed after the calculator has evaluated (only for a number button not an operator button). An example of the behaviour I want is this: https://mike-monta.github.io/calculator-pro/ https://github.com/Mike-Monta/calculator-pro Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculator</title> <link rel="stylesheet" href="style.css"> <link rel="icon" type="image/x-icon" href="img/favicon.ico"> </head> <body> <div class="calcBody"> <div class="calcDisplay"> <div class="screenDisplay"> <div class="prevDisplay"></div> <div class="currentDisplay">0</div> </div> </div> <div class="buttonsBody"> <div class="numberButtons"> <!--Row 1--> <button class="clearButton inputButton" data-all="AC"><span class="buttonsText">AC</span></button> <button class="deleteButton inputButton" data-all="C"><span class="buttonsText">C</span></button> <button class="percentButton inputButton" data-all="%" data-operator="%"><span class="buttonsText">%</span></button> <button class="divideButton inputButton" data-all="÷" data-operator="÷"><span class="buttonsText">÷</span></button> <!--Row 2--> <button class="sevenButton inputButton" data-all="7" data-num="7"><span class="buttonsText">7</span></button> <button class="eightButton inputButton" data-all="8" data-num="8"><span class="buttonsText">8</span></button> <button class="nineButton inputButton" data-all="9" data-num="9"><span class="buttonsText">9</span></button> <button class="multiplyButton inputButton" data-all="×" data-operator="×"><span class="buttonsText">×</span></button> <!--Row 3--> <button class="fourButton inputButton" data-all="4" data-num="4"><span class="buttonsText">4</span></button> <button class="fiveButton inputButton" data-all="5" data-num="5"><span class="buttonsText">5</span></button> <button class="sixButton inputButton" data-all="6" data-num="6"><span class="buttonsText">6</span></button> <button class="minusButton inputButton" data-all="-" data-operator="-"><span class="buttonsText">-</span></button> <!--Row 4--> <button class="oneButton inputButton" data-all="1" data-num="1"><span class="buttonsText">1</span></button> <button class="twoButton inputButton" data-all="2" data-num="2"><span class="buttonsText">2</span></button> <button class="threeButton inputButton" data-all="3" data-num="3"><span class="buttonsText">3</span></button> <button class="plusButton inputButton" data-all="+" data-operator="+"><span class="buttonsText">+</span></button> <!--Row 5 --> <button class="doubleZeroButton inputButton" data-all="00" data-num="00"><span class="buttonsText">00</span></button> <button class="zeroButton inputButton" data-all="0" data-num="0"><span class="buttonsText">0</span></button> <button class="decimalButton inputButton" data-all="."><span class="buttonsText">.</span></button> <button class="equalsButton inputButton" data-all="="><span class="buttonsText">=</span></button> </div> </div> </div> <script src="script.js"></script> </body> </html> const prevDisplay = document.querySelector('.prevDisplay'); const currentDisplay = document.querySelector('.currentDisplay'); const inputButton = document.querySelectorAll('.inputButton'); const divideButton = document.querySelector('.divideButton'); const equalsButton = document.querySelector('.equalsButton'); const operatorButton = document.querySelectorAll('[data-operator]'); const numberButton = document.querySelectorAll('[data-num]'); const clearButton = document.querySelector('.clearButton'); const deleteButton = document.querySelector('.deleteButton'); const decimalButton = document.querySelector('.decimalButton') //Global variables let num1 = ""; let operator = ""; let num2 = ""; let removeDot; //Current display numberButton.forEach((btn) => { btn.addEventListener('click', (e) => { handleNumber(e.target.textContent); }) } ) function handleNumber(number){ if (num1.length <= 21){ num1 += number; currentDisplay.textContent = num1; } } //Previous display operatorButton.forEach((btn) => { btn.addEventListener('click', (e) => { handleOperator(e.target.textContent); }) }) function handleOperator(op){ if (num1 == '' && num2 == ''){ num1 = '0'; } else if (operator == '' && num2 !== ''){ num2 = '' } else if (num2 === "") { num2 = num1; operatorCheck(op); } else if (num1 === "") { operatorCheck(op); } else { operate(); operator = op; currentDisplay.textContent = "0"; prevDisplay.textContent = num2 + " " + operator; } } function operatorCheck(text) { operator = text; prevDisplay.textContent = num2 + " " + operator; currentDisplay.textContent = "0"; num1 = ""; } //Clear button function clearCalc(){ prevDisplay.textContent = ''; currentDisplay.textContent = ''; num1 = ''; num2 = ''; operator = ''; } clearButton.addEventListener('click', clearCalc) //Delete button function deleteCalc(){ num1 = num1.slice(0, currentDisplay.textContent.length - 1) currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1) } deleteButton.addEventListener('click', deleteCalc) //Equals button function equalsCalc(){ if (num1 != '' && num2 != ''){ operate() } } equalsButton.addEventListener('click', equalsCalc) //Decimal button function decimalCalc(){ if (num1.includes('.') == false){ currentDisplay.textContent = currentDisplay.textContent + '.' num1 = num1 + '.' } } decimalButton.addEventListener('click', decimalCalc) //Doing the calculation function calcPercent(num1, num2){ return (num2 / 100) * num1 } function calcDivide(num1, num2){ return num2 / num1 } function calcMultiply(num1, num2){ return num1 * num2 } function calcSubtract(num1, num2){ return num2 - num1 } function calcAdd(num1, num2){ return num1 + num2 } function operate() { num1 = Number(num1) num2 = Number(num2) switch (operator) { case '+': num2 = calcAdd(num1, num2) break case '-': num2 = calcSubtract(num1, num2) break case '×': num2 = calcMultiply(num1, num2) break case '%': num2 = calcPercent(num1, num2) break case '÷': num2 = num2.toString(); if (num1 == 0){ num2 = "Error, you can't divide by 0" } else{ num2 = calcDivide(num1, num2); } break } num2 = roundNum(num2) prevDisplay.textContent = ""; currentDisplay.textContent = num2; num1 = ''; } //Round Number function roundNum(num){ return Math.round(num * 1000000) / 1000000; } //Event listeners for key presses window.addEventListener('keydown', removeDot = function(e){ switch (e.key){ case "7": handleNumber(7) break case "8": handleNumber(8) break case "9": handleNumber(9) break case "4": handleNumber(4) break case "5": handleNumber(5) break case "6": handleNumber(6) break case "1": handleNumber(1) break case "2": handleNumber(2) break case "3": handleNumber(3) break case "0": handleNumber(0) break case ")": handleNumber(00) break case "Delete": clearCalc(); break case "+": handleOperator('+') break case "-": handleOperator('-') break case "*": handleOperator('×') break case "/": handleOperator('÷') break case "%": handleOperator('%') break case ".": decimalCalc(); break case "Backspace": deleteCalc(); break case "Enter": e.preventDefault(); equalsCalc(); break } }, true) A: I think I would generally have a different approach BUT... A simple solution would be to capture the = as an operator, and check for it's presence in the handleNumber method. If it is the current operator, just clear num2. ... function handleNumber(number) { if (num1.length <= 21) { num1 += number; currentDisplay.textContent = num1; } if (operator === '=') { // <-- Added num2 = '' } } ... function equalsCalc() { if (num1 != '' && num2 != '') { operate() operator = '=' // <-- Added } } ... const prevDisplay = document.querySelector('.prevDisplay'); const currentDisplay = document.querySelector('.currentDisplay'); const inputButton = document.querySelectorAll('.inputButton'); const divideButton = document.querySelector('.divideButton'); const equalsButton = document.querySelector('.equalsButton'); const operatorButton = document.querySelectorAll('[data-operator]'); const numberButton = document.querySelectorAll('[data-num]'); const clearButton = document.querySelector('.clearButton'); const deleteButton = document.querySelector('.deleteButton'); const decimalButton = document.querySelector('.decimalButton') //Global variables let num1 = ""; let operator = ""; let num2 = ""; let removeDot; //Current display numberButton.forEach((btn) => { btn.addEventListener('click', (e) => { handleNumber(e.target.textContent); }) }) function handleNumber(number) { console.log('handleNumber', num1, operator, num2, '->', number) if (num1.length <= 21) { num1 += number; currentDisplay.textContent = num1; } if (operator === '=') { num2 = '' } console.log('handleNumber END', num1, operator, num2) } //Previous display operatorButton.forEach((btn) => { btn.addEventListener('click', (e) => { handleOperator(e.target.textContent); }) }) function handleOperator(op) { console.log('handleOperator', num1, operator, num2, '->', op) if (num1 == '' && num2 == '') { num1 = ''; } else if (operator == '' && num2 !== '') { num2 = '' } else if (num2 === "") { num2 = num1; operatorCheck(op); } else if (num1 === "") { operatorCheck(op); } else { operate(); operator = op; currentDisplay.textContent = "0"; prevDisplay.textContent = num2 + " " + operator; } console.log('handleOperator END', num1, operator, num2) } function operatorCheck(text) { operator = text; prevDisplay.textContent = num2 + " " + operator; currentDisplay.textContent = "0"; num1 = ""; } //Clear button function clearCalc() { prevDisplay.textContent = ''; currentDisplay.textContent = ''; num1 = ''; num2 = ''; operator = ''; } clearButton.addEventListener('click', clearCalc) //Delete button function deleteCalc() { num1 = num1.slice(0, currentDisplay.textContent.length - 1) currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1) } deleteButton.addEventListener('click', deleteCalc) //Equals button function equalsCalc() { if (num1 != '' && num2 != '') { operate() console.log('equalsCalc END', num1, operator, num2) operator = '=' } } equalsButton.addEventListener('click', equalsCalc) //Decimal button function decimalCalc() { if (num1.includes('.') == false) { currentDisplay.textContent = currentDisplay.textContent + '.' num1 = num1 + '.' } } decimalButton.addEventListener('click', decimalCalc) //Doing the calculation function calcPercent(num1, num2) { return (num2 / 100) * num1 } function calcDivide(num1, num2) { return num2 / num1 } function calcMultiply(num1, num2) { return num1 * num2 } function calcSubtract(num1, num2) { return num2 - num1 } function calcAdd(num1, num2) { return num1 + num2 } function operate() { num1 = Number(num1) num2 = Number(num2) switch (operator) { case '+': num2 = calcAdd(num1, num2) break case '-': num2 = calcSubtract(num1, num2) break case '×': num2 = calcMultiply(num1, num2) break case '%': num2 = calcPercent(num1, num2) break case '÷': num2 = num2.toString(); if (num1 == 0) { num2 = "Error, you can't divide by 0" } else { num2 = calcDivide(num1, num2); } break } num2 = roundNum(num2) prevDisplay.textContent = ""; currentDisplay.textContent = num2; num1 = ''; } //Round Number function roundNum(num) { return Math.round(num * 1000000) / 1000000; } //Event listeners for key presses window.addEventListener('keydown', removeDot = function(e) { switch (e.key) { case "7": handleNumber(7) break case "8": handleNumber(8) break case "9": handleNumber(9) break case "4": handleNumber(4) break case "5": handleNumber(5) break case "6": handleNumber(6) break case "1": handleNumber(1) break case "2": handleNumber(2) break case "3": handleNumber(3) break case "0": handleNumber(0) break case ")": handleNumber(00) break case "Delete": clearCalc(); break case "+": handleOperator('+') break case "-": handleOperator('-') break case "*": handleOperator('×') break case "/": handleOperator('÷') break case "%": handleOperator('%') break case ".": decimalCalc(); break case "Backspace": deleteCalc(); break case "Enter": e.preventDefault(); equalsCalc(); break } }, true) html, body { display: flex; justify-content: center; align-items: center; height: 100%; padding: 0; margin: 0; } .calcBody { display: flex; background-color: rgb(160, 160, 160); width: 500px; height: 700px; border: 2px solid black; border-radius: 35px; padding-bottom: 25px; transform: scale(0.95, 1); } .calcDisplay { display: flex; height: 200px; width: 500px; position: absolute; justify-content: center; border-radius: 30px; } .screenDisplay { display: flex; align-self: center; background-color: rgb(248, 248, 248); width: 450px; height: 150px; justify-content: flex-end; border-radius: 45px; border: 2px solid black; } .prevDisplay { display: flex; justify-content: flex-end; align-items: flex-start; width: 85%; height: 50px; position: absolute; margin-top: 50px; margin-right: 25px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 20px; margin-bottom: 20px; } .currentDisplay { display: flex; align-self: flex-end; justify-self: end; height: 50px; width: 100%; justify-content: flex-end; margin-right: 25px; font-family: Verdana, Geneva, Tahoma, sans-serif; font-size: 30px; margin-bottom: 20px; } .buttonsBody { display: flex; width: 100%; height: 500px; align-self: flex-end; justify-content: center; } .numberButtons { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; grid-template-rows: 1fr 1fr 1fr 1fr 1fr; width: 450px; height: 500px; gap: 5px; } .inputButton { padding: 0px; margin: 0px; border: 2px solid black; border-radius: 20px; transition: 200ms; background-color: rgb(231, 231, 231); } .buttonsText { padding: 0; margin: 0; font-size: 20px; font-family: Verdana, Geneva, Tahoma, sans-serif; transition: 150ms; display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; } .inputButton:hover { background-color: darkgray; cursor: pointer; } .buttonsText:hover { font-size: 30px; } .clearButton, .deleteButton { background-color: rgb(223, 145, 145); } .equalsButton { background-color: rgb(187, 238, 110); } <div class="calcBody"> <div class="calcDisplay"> <div class="screenDisplay"> <div class="prevDisplay"></div> <div class="currentDisplay"></div> </div> </div> <div class="buttonsBody"> <div class="numberButtons"> <!--Row 1--> <button class="clearButton inputButton" data-all="AC"><span class="buttonsText">AC</span></button> <button class="deleteButton inputButton" data-all="C"><span class="buttonsText">C</span></button> <button class="percentButton inputButton" data-all="%" data-operator="%"><span class="buttonsText">%</span></button> <button class="divideButton inputButton" data-all="÷" data-operator="÷"><span class="buttonsText">÷</span></button> <!--Row 2--> <button class="sevenButton inputButton" data-all="7" data-num="7"><span class="buttonsText">7</span></button> <button class="eightButton inputButton" data-all="8" data-num="8"><span class="buttonsText">8</span></button> <button class="nineButton inputButton" data-all="9" data-num="9"><span class="buttonsText">9</span></button> <button class="multiplyButton inputButton" data-all="×" data-operator="×"><span class="buttonsText">×</span></button> <!--Row 3--> <button class="fourButton inputButton" data-all="4" data-num="4"><span class="buttonsText">4</span></button> <button class="fiveButton inputButton" data-all="5" data-num="5"><span class="buttonsText">5</span></button> <button class="sixButton inputButton" data-all="6" data-num="6"><span class="buttonsText">6</span></button> <button class="minusButton inputButton" data-all="-" data-operator="-"><span class="buttonsText">-</span></button> <!--Row 4--> <button class="oneButton inputButton" data-all="1" data-num="1"><span class="buttonsText">1</span></button> <button class="twoButton inputButton" data-all="2" data-num="2"><span class="buttonsText">2</span></button> <button class="threeButton inputButton" data-all="3" data-num="3"><span class="buttonsText">3</span></button> <button class="plusButton inputButton" data-all="+" data-operator="+"><span class="buttonsText">+</span></button> <!--Row 5 --> <button class="doubleZeroButton inputButton" data-all="00" data-num="00"><span class="buttonsText">00</span></button> <button class="zeroButton inputButton" data-all="0" data-num="0"><span class="buttonsText">0</span></button> <button class="decimalButton inputButton" data-all="."><span class="buttonsText">.</span></button> <button class="equalsButton inputButton" data-all="="><span class="buttonsText">=</span></button> </div> </div> </div> A: You can clear num2 after new number has been clicked. typeof num2 !== 'string' checks if it was operated before. function handleNumber(number) { if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line if (num1.length <= 21) { num1 += number; currentDisplay.textContent = num1; } }
Where to reset the value of operator in calculator?
This is a live demo of my calculator: https://kepplin.github.io/odin-calculator/ After the equals button is pressed and the calculation is displayed, if a number button is pressed, then instead of starting a new calculation, the calculator evaluates with the operator of the previous calculation. I have 3 global variables: num1, num2, operator. As well as a previous display and current display. Example of the problem (step-by-step): 12 console.log(num1) // 12 console.log(num2) // console.log(operator) // 12 + console.log(num1) // console.log(num2) // 12 console.log(operator) // + 12 + 4 console.log(num1) // 4 console.log(num2) // 12 console.log(operator) // + After the '=' button is pressed, the calculator displays: 16 console.log(num1) // console.log(num2) // 16 console.log(operator) // + The calculator immediately evaluates if there are values for num1, num2, and operator. The problem comes here, if the user wants to start a different calculation (e.g, 5 - 4): 5 console.log(num1) // 5 console.log(num2) // 16 console.log(operator) // + 5 - console.log(num1) // console.log(num2) // 21 console.log(operator) // - The calculator did 5 + 16. I want the values of num1, num2 and operator to be reset back to ' ' if a number button is pressed after the calculator has evaluated (only for a number button not an operator button). An example of the behaviour I want is this: https://mike-monta.github.io/calculator-pro/ https://github.com/Mike-Monta/calculator-pro Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculator</title> <link rel="stylesheet" href="style.css"> <link rel="icon" type="image/x-icon" href="img/favicon.ico"> </head> <body> <div class="calcBody"> <div class="calcDisplay"> <div class="screenDisplay"> <div class="prevDisplay"></div> <div class="currentDisplay">0</div> </div> </div> <div class="buttonsBody"> <div class="numberButtons"> <!--Row 1--> <button class="clearButton inputButton" data-all="AC"><span class="buttonsText">AC</span></button> <button class="deleteButton inputButton" data-all="C"><span class="buttonsText">C</span></button> <button class="percentButton inputButton" data-all="%" data-operator="%"><span class="buttonsText">%</span></button> <button class="divideButton inputButton" data-all="÷" data-operator="÷"><span class="buttonsText">÷</span></button> <!--Row 2--> <button class="sevenButton inputButton" data-all="7" data-num="7"><span class="buttonsText">7</span></button> <button class="eightButton inputButton" data-all="8" data-num="8"><span class="buttonsText">8</span></button> <button class="nineButton inputButton" data-all="9" data-num="9"><span class="buttonsText">9</span></button> <button class="multiplyButton inputButton" data-all="×" data-operator="×"><span class="buttonsText">×</span></button> <!--Row 3--> <button class="fourButton inputButton" data-all="4" data-num="4"><span class="buttonsText">4</span></button> <button class="fiveButton inputButton" data-all="5" data-num="5"><span class="buttonsText">5</span></button> <button class="sixButton inputButton" data-all="6" data-num="6"><span class="buttonsText">6</span></button> <button class="minusButton inputButton" data-all="-" data-operator="-"><span class="buttonsText">-</span></button> <!--Row 4--> <button class="oneButton inputButton" data-all="1" data-num="1"><span class="buttonsText">1</span></button> <button class="twoButton inputButton" data-all="2" data-num="2"><span class="buttonsText">2</span></button> <button class="threeButton inputButton" data-all="3" data-num="3"><span class="buttonsText">3</span></button> <button class="plusButton inputButton" data-all="+" data-operator="+"><span class="buttonsText">+</span></button> <!--Row 5 --> <button class="doubleZeroButton inputButton" data-all="00" data-num="00"><span class="buttonsText">00</span></button> <button class="zeroButton inputButton" data-all="0" data-num="0"><span class="buttonsText">0</span></button> <button class="decimalButton inputButton" data-all="."><span class="buttonsText">.</span></button> <button class="equalsButton inputButton" data-all="="><span class="buttonsText">=</span></button> </div> </div> </div> <script src="script.js"></script> </body> </html> const prevDisplay = document.querySelector('.prevDisplay'); const currentDisplay = document.querySelector('.currentDisplay'); const inputButton = document.querySelectorAll('.inputButton'); const divideButton = document.querySelector('.divideButton'); const equalsButton = document.querySelector('.equalsButton'); const operatorButton = document.querySelectorAll('[data-operator]'); const numberButton = document.querySelectorAll('[data-num]'); const clearButton = document.querySelector('.clearButton'); const deleteButton = document.querySelector('.deleteButton'); const decimalButton = document.querySelector('.decimalButton') //Global variables let num1 = ""; let operator = ""; let num2 = ""; let removeDot; //Current display numberButton.forEach((btn) => { btn.addEventListener('click', (e) => { handleNumber(e.target.textContent); }) } ) function handleNumber(number){ if (num1.length <= 21){ num1 += number; currentDisplay.textContent = num1; } } //Previous display operatorButton.forEach((btn) => { btn.addEventListener('click', (e) => { handleOperator(e.target.textContent); }) }) function handleOperator(op){ if (num1 == '' && num2 == ''){ num1 = '0'; } else if (operator == '' && num2 !== ''){ num2 = '' } else if (num2 === "") { num2 = num1; operatorCheck(op); } else if (num1 === "") { operatorCheck(op); } else { operate(); operator = op; currentDisplay.textContent = "0"; prevDisplay.textContent = num2 + " " + operator; } } function operatorCheck(text) { operator = text; prevDisplay.textContent = num2 + " " + operator; currentDisplay.textContent = "0"; num1 = ""; } //Clear button function clearCalc(){ prevDisplay.textContent = ''; currentDisplay.textContent = ''; num1 = ''; num2 = ''; operator = ''; } clearButton.addEventListener('click', clearCalc) //Delete button function deleteCalc(){ num1 = num1.slice(0, currentDisplay.textContent.length - 1) currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1) } deleteButton.addEventListener('click', deleteCalc) //Equals button function equalsCalc(){ if (num1 != '' && num2 != ''){ operate() } } equalsButton.addEventListener('click', equalsCalc) //Decimal button function decimalCalc(){ if (num1.includes('.') == false){ currentDisplay.textContent = currentDisplay.textContent + '.' num1 = num1 + '.' } } decimalButton.addEventListener('click', decimalCalc) //Doing the calculation function calcPercent(num1, num2){ return (num2 / 100) * num1 } function calcDivide(num1, num2){ return num2 / num1 } function calcMultiply(num1, num2){ return num1 * num2 } function calcSubtract(num1, num2){ return num2 - num1 } function calcAdd(num1, num2){ return num1 + num2 } function operate() { num1 = Number(num1) num2 = Number(num2) switch (operator) { case '+': num2 = calcAdd(num1, num2) break case '-': num2 = calcSubtract(num1, num2) break case '×': num2 = calcMultiply(num1, num2) break case '%': num2 = calcPercent(num1, num2) break case '÷': num2 = num2.toString(); if (num1 == 0){ num2 = "Error, you can't divide by 0" } else{ num2 = calcDivide(num1, num2); } break } num2 = roundNum(num2) prevDisplay.textContent = ""; currentDisplay.textContent = num2; num1 = ''; } //Round Number function roundNum(num){ return Math.round(num * 1000000) / 1000000; } //Event listeners for key presses window.addEventListener('keydown', removeDot = function(e){ switch (e.key){ case "7": handleNumber(7) break case "8": handleNumber(8) break case "9": handleNumber(9) break case "4": handleNumber(4) break case "5": handleNumber(5) break case "6": handleNumber(6) break case "1": handleNumber(1) break case "2": handleNumber(2) break case "3": handleNumber(3) break case "0": handleNumber(0) break case ")": handleNumber(00) break case "Delete": clearCalc(); break case "+": handleOperator('+') break case "-": handleOperator('-') break case "*": handleOperator('×') break case "/": handleOperator('÷') break case "%": handleOperator('%') break case ".": decimalCalc(); break case "Backspace": deleteCalc(); break case "Enter": e.preventDefault(); equalsCalc(); break } }, true)
[ "I think I would generally have a different approach BUT...\nA simple solution would be to capture the = as an operator, and check for it's presence in the handleNumber method. If it is the current operator, just clear num2.\n...\n\nfunction handleNumber(number) {\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') { // <-- Added\n num2 = ''\n }\n}\n\n...\n\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n operator = '=' // <-- Added\n }\n}\n\n...\n\n\n\nconst prevDisplay = document.querySelector('.prevDisplay');\nconst currentDisplay = document.querySelector('.currentDisplay');\nconst inputButton = document.querySelectorAll('.inputButton');\nconst divideButton = document.querySelector('.divideButton');\nconst equalsButton = document.querySelector('.equalsButton');\nconst operatorButton = document.querySelectorAll('[data-operator]');\nconst numberButton = document.querySelectorAll('[data-num]');\nconst clearButton = document.querySelector('.clearButton');\nconst deleteButton = document.querySelector('.deleteButton');\nconst decimalButton = document.querySelector('.decimalButton')\n//Global variables\nlet num1 = \"\";\nlet operator = \"\";\nlet num2 = \"\";\nlet removeDot;\n//Current display\nnumberButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleNumber(e.target.textContent);\n })\n})\n\nfunction handleNumber(number) {\n console.log('handleNumber', num1, operator, num2, '->', number)\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n if (operator === '=') {\n num2 = ''\n }\n console.log('handleNumber END', num1, operator, num2)\n}\n//Previous display\noperatorButton.forEach((btn) => {\n btn.addEventListener('click', (e) => {\n handleOperator(e.target.textContent);\n })\n})\n\nfunction handleOperator(op) {\n console.log('handleOperator', num1, operator, num2, '->', op)\n if (num1 == '' && num2 == '') {\n num1 = '';\n } else if (operator == '' && num2 !== '') {\n num2 = ''\n } else if (num2 === \"\") {\n num2 = num1;\n operatorCheck(op);\n } else if (num1 === \"\") {\n operatorCheck(op);\n } else {\n operate();\n operator = op;\n currentDisplay.textContent = \"0\";\n prevDisplay.textContent = num2 + \" \" + operator;\n }\n console.log('handleOperator END', num1, operator, num2)\n}\n\nfunction operatorCheck(text) {\n operator = text;\n prevDisplay.textContent = num2 + \" \" + operator;\n currentDisplay.textContent = \"0\";\n num1 = \"\";\n}\n//Clear button\nfunction clearCalc() {\n prevDisplay.textContent = '';\n currentDisplay.textContent = '';\n num1 = '';\n num2 = '';\n operator = '';\n}\nclearButton.addEventListener('click', clearCalc)\n//Delete button\nfunction deleteCalc() {\n num1 = num1.slice(0, currentDisplay.textContent.length - 1)\n currentDisplay.textContent = currentDisplay.textContent.slice(0, currentDisplay.textContent.length - 1)\n}\ndeleteButton.addEventListener('click', deleteCalc)\n//Equals button\nfunction equalsCalc() {\n if (num1 != '' && num2 != '') {\n operate()\n console.log('equalsCalc END', num1, operator, num2)\n operator = '='\n }\n}\nequalsButton.addEventListener('click', equalsCalc)\n//Decimal button\nfunction decimalCalc() {\n if (num1.includes('.') == false) {\n currentDisplay.textContent = currentDisplay.textContent + '.'\n num1 = num1 + '.'\n }\n}\ndecimalButton.addEventListener('click', decimalCalc)\n//Doing the calculation\nfunction calcPercent(num1, num2) {\n return (num2 / 100) * num1\n}\n\nfunction calcDivide(num1, num2) {\n return num2 / num1\n}\n\nfunction calcMultiply(num1, num2) {\n return num1 * num2\n}\n\nfunction calcSubtract(num1, num2) {\n return num2 - num1\n}\n\nfunction calcAdd(num1, num2) {\n return num1 + num2\n}\n\nfunction operate() {\n num1 = Number(num1)\n num2 = Number(num2)\n\n switch (operator) {\n case '+':\n num2 = calcAdd(num1, num2)\n break\n case '-':\n num2 = calcSubtract(num1, num2)\n break\n case '×':\n num2 = calcMultiply(num1, num2)\n break\n case '%':\n num2 = calcPercent(num1, num2)\n break\n case '÷':\n num2 = num2.toString();\n if (num1 == 0) {\n num2 = \"Error, you can't divide by 0\"\n } else {\n num2 = calcDivide(num1, num2);\n }\n break\n }\n num2 = roundNum(num2)\n prevDisplay.textContent = \"\";\n currentDisplay.textContent = num2;\n num1 = '';\n}\n//Round Number\nfunction roundNum(num) {\n return Math.round(num * 1000000) / 1000000;\n}\n//Event listeners for key presses\nwindow.addEventListener('keydown', removeDot = function(e) {\n switch (e.key) {\n case \"7\":\n handleNumber(7)\n break\n case \"8\":\n handleNumber(8)\n break\n case \"9\":\n handleNumber(9)\n break\n case \"4\":\n handleNumber(4)\n break\n case \"5\":\n handleNumber(5)\n break\n case \"6\":\n handleNumber(6)\n break\n case \"1\":\n handleNumber(1)\n break\n case \"2\":\n handleNumber(2)\n break\n case \"3\":\n handleNumber(3)\n break\n case \"0\":\n handleNumber(0)\n break\n case \")\":\n handleNumber(00)\n break\n case \"Delete\":\n clearCalc();\n break\n case \"+\":\n handleOperator('+')\n break\n case \"-\":\n handleOperator('-')\n break\n case \"*\":\n handleOperator('×')\n break\n case \"/\":\n handleOperator('÷')\n break\n case \"%\":\n handleOperator('%')\n break\n case \".\":\n decimalCalc();\n break\n case \"Backspace\":\n deleteCalc();\n break\n case \"Enter\":\n e.preventDefault();\n equalsCalc();\n break\n }\n}, true)\nhtml,\nbody {\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100%;\n padding: 0;\n margin: 0;\n}\n\n.calcBody {\n display: flex;\n background-color: rgb(160, 160, 160);\n width: 500px;\n height: 700px;\n border: 2px solid black;\n border-radius: 35px;\n padding-bottom: 25px;\n transform: scale(0.95, 1);\n}\n\n.calcDisplay {\n display: flex;\n height: 200px;\n width: 500px;\n position: absolute;\n justify-content: center;\n border-radius: 30px;\n}\n\n.screenDisplay {\n display: flex;\n align-self: center;\n background-color: rgb(248, 248, 248);\n width: 450px;\n height: 150px;\n justify-content: flex-end;\n border-radius: 45px;\n border: 2px solid black;\n}\n\n.prevDisplay {\n display: flex;\n justify-content: flex-end;\n align-items: flex-start;\n width: 85%;\n height: 50px;\n position: absolute;\n margin-top: 50px;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 20px;\n margin-bottom: 20px;\n}\n\n.currentDisplay {\n display: flex;\n align-self: flex-end;\n justify-self: end;\n height: 50px;\n width: 100%;\n justify-content: flex-end;\n margin-right: 25px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n font-size: 30px;\n margin-bottom: 20px;\n}\n\n.buttonsBody {\n display: flex;\n width: 100%;\n height: 500px;\n align-self: flex-end;\n justify-content: center;\n}\n\n.numberButtons {\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr;\n width: 450px;\n height: 500px;\n gap: 5px;\n}\n\n.inputButton {\n padding: 0px;\n margin: 0px;\n border: 2px solid black;\n border-radius: 20px;\n transition: 200ms;\n background-color: rgb(231, 231, 231);\n}\n\n.buttonsText {\n padding: 0;\n margin: 0;\n font-size: 20px;\n font-family: Verdana, Geneva, Tahoma, sans-serif;\n transition: 150ms;\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n width: 100%;\n}\n\n.inputButton:hover {\n background-color: darkgray;\n cursor: pointer;\n}\n\n.buttonsText:hover {\n font-size: 30px;\n}\n\n.clearButton,\n.deleteButton {\n background-color: rgb(223, 145, 145);\n}\n\n.equalsButton {\n background-color: rgb(187, 238, 110);\n}\n<div class=\"calcBody\">\n <div class=\"calcDisplay\">\n <div class=\"screenDisplay\">\n <div class=\"prevDisplay\"></div>\n <div class=\"currentDisplay\"></div>\n </div>\n </div>\n <div class=\"buttonsBody\">\n <div class=\"numberButtons\">\n <!--Row 1-->\n <button class=\"clearButton inputButton\" data-all=\"AC\"><span class=\"buttonsText\">AC</span></button>\n <button class=\"deleteButton inputButton\" data-all=\"C\"><span class=\"buttonsText\">C</span></button>\n <button class=\"percentButton inputButton\" data-all=\"%\" data-operator=\"%\"><span class=\"buttonsText\">%</span></button>\n <button class=\"divideButton inputButton\" data-all=\"÷\" data-operator=\"÷\"><span class=\"buttonsText\">÷</span></button>\n <!--Row 2-->\n <button class=\"sevenButton inputButton\" data-all=\"7\" data-num=\"7\"><span class=\"buttonsText\">7</span></button>\n <button class=\"eightButton inputButton\" data-all=\"8\" data-num=\"8\"><span class=\"buttonsText\">8</span></button>\n <button class=\"nineButton inputButton\" data-all=\"9\" data-num=\"9\"><span class=\"buttonsText\">9</span></button>\n <button class=\"multiplyButton inputButton\" data-all=\"×\" data-operator=\"×\"><span class=\"buttonsText\">×</span></button>\n <!--Row 3-->\n <button class=\"fourButton inputButton\" data-all=\"4\" data-num=\"4\"><span class=\"buttonsText\">4</span></button>\n <button class=\"fiveButton inputButton\" data-all=\"5\" data-num=\"5\"><span class=\"buttonsText\">5</span></button>\n <button class=\"sixButton inputButton\" data-all=\"6\" data-num=\"6\"><span class=\"buttonsText\">6</span></button>\n <button class=\"minusButton inputButton\" data-all=\"-\" data-operator=\"-\"><span class=\"buttonsText\">-</span></button>\n <!--Row 4-->\n <button class=\"oneButton inputButton\" data-all=\"1\" data-num=\"1\"><span class=\"buttonsText\">1</span></button>\n <button class=\"twoButton inputButton\" data-all=\"2\" data-num=\"2\"><span class=\"buttonsText\">2</span></button>\n <button class=\"threeButton inputButton\" data-all=\"3\" data-num=\"3\"><span class=\"buttonsText\">3</span></button>\n <button class=\"plusButton inputButton\" data-all=\"+\" data-operator=\"+\"><span class=\"buttonsText\">+</span></button>\n <!--Row 5 -->\n <button class=\"doubleZeroButton inputButton\" data-all=\"00\" data-num=\"00\"><span class=\"buttonsText\">00</span></button>\n <button class=\"zeroButton inputButton\" data-all=\"0\" data-num=\"0\"><span class=\"buttonsText\">0</span></button>\n <button class=\"decimalButton inputButton\" data-all=\".\"><span class=\"buttonsText\">.</span></button>\n <button class=\"equalsButton inputButton\" data-all=\"=\"><span class=\"buttonsText\">=</span></button>\n </div>\n </div>\n</div>\n\n\n\n", "You can clear num2 after new number has been clicked. typeof num2 !== 'string' checks if it was operated before.\n function handleNumber(number) {\n if (typeof num2 !== 'string' && operator === '') num2 = ''; // Add this line\n if (num1.length <= 21) {\n num1 += number;\n currentDisplay.textContent = num1;\n }\n }\n\n" ]
[ 1, 0 ]
[]
[]
[ "calculation", "calculator", "javascript" ]
stackoverflow_0074580139_calculation_calculator_javascript.txt
Q: Remove specific things from string in Python I am struggling to remove some characters in a string. This is inside a loop. So if the string contains either of the below, then it needs to remove them and leave the rest behind. Characters to remove: "-" "1)", "2)" etc Here is the loop: for i in item: if i != "": items[heading].append(i) I am just wondering if there is any advice as to where I can look for help please :) Here is what I have tried, without the desired results: for i in item: if i != "": i = i.replace('-', '') i = i[i.find(')'):] items[title].append(i) A: Try this! bl = ["-", "1)", "2)"] string = "-2)Hello1) World!" for item in bl: string = string.replace(item, "") print(string)
Remove specific things from string in Python
I am struggling to remove some characters in a string. This is inside a loop. So if the string contains either of the below, then it needs to remove them and leave the rest behind. Characters to remove: "-" "1)", "2)" etc Here is the loop: for i in item: if i != "": items[heading].append(i) I am just wondering if there is any advice as to where I can look for help please :) Here is what I have tried, without the desired results: for i in item: if i != "": i = i.replace('-', '') i = i[i.find(')'):] items[title].append(i)
[ "Try this!\nbl = [\"-\", \"1)\", \"2)\"]\nstring = \"-2)Hello1) World!\"\n\nfor item in bl:\n string = string.replace(item, \"\")\n\nprint(string)\n\n" ]
[ -1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074657193_python_string.txt
Q: How to update an array after splice in Svelte? I'm learning Svelte, and read in the documentation that arrays need to be reassigned in order for a component or page to update it. For that they devised a more idiomatic solution. Instead of writing: messages.push('hello'); messages = messages; you can write instead: messages = [...messages, 'hello']; Alright, makes sense. But then the documentation says: You can use similar patterns to replace pop, shift, unshift and splice. But how? I cannot see how you can remove items from an array. More to the point, how could I write the following more idiomatically? messages.splice(messages.indexOf('hello'), 1); messages = messages; A: You could e.g. use the filter array method to create a new array without the element 'hello': messages = messages.filter(m => m !== 'hello'); A: As mentioned, Svelte's reactivity is triggered by assignments. The current Svelte tutorial uses JavaScript's (ES6) spread syntax (three dots) to add the next-higher number to an array, providing a more idiomatic solution than a redundant assignment using push: function pushNumber() { numbers = [...numbers, lastnumber]; // 1, 2, 3, 4, 5 } You could use spread syntax to replace pop, shift, unshift and splicethough it might increase the time and complexity of the operation in some cases: function unshiftNumber() { numbers = [firstnumber, ...numbers]; // 0, 1, 2, 3, 4 } function popNumber() { numbers = [...numbers.slice(0,numbers.length - 1)]; // 1, 2, 3 } function shiftNumber() { numbers = [...numbers.slice(1,numbers.length)]; // 2, 3, 4 } function spliceNumber() { numbers = [firstnumber, ...numbers.slice(0,numbers.length-1)];// 0, 1, 2, 3 } Spread is just one way to do it, though. The purpose behind not using pop/push etc is to encourage immutability. So any removal can just be a filter, for example. A: There are several things to consider here. Given this code: messages.splice(messages.indexOf('hello'), 1); messages = messages; What's happening here is: Looking for the first occurrence of the string "hello" in the array Removing such element from the array, based on the index found. The assumption here is that "hello" needs to exists, otherwise the could would remove the last item from the array (since indexOf returns -1). The original array is therefore mutate: depends by the context, that sometimes can be preferable instead of copying the whole array into a new one; otherwise it's generally a better practice avoid such mutation. So. If you want to have this behavior exactly, probably this is the best code you can have. For example, takes the filter example: messages = messages.filter(message => message !== "hello") What's happening here is: Filter out any element equals to "hello" Returns a new array without such element So it's quite different from the original code: first of all, it always loop the whole array. If you have thousands of element, even if you have only one "hello" at the second index, it would always iterate all of them. Maybe it's what you want, maybe not. If the element is unique, such as an id, maybe you want to stop once you find it. Second, it returns a new array. Again, that usually a better practice than mutate the array, but in some context it's preferable mutate it instead of create a new one. So, if you want to mutate the original array, it's probably better to stick to your original code. If, instead, you don't care (such as the example of push), I believe that in the intention of svelte's developers, your code would be roughly translate to: let i = messages.indexOf("hello"); messages = [...messages.slice(0, i), ...messages.slice(i + 1)]; (Still assuming there is a "hello" message and you're interested only in the first occurrence). It's unfortunate that JS doesn't have a better syntax to handles slices. A: In case you're wandering, filter can also be used to remove elements using a given index: let elements = ['a','b', 'c']; let idx = 1; elements = elements.filter( (e,i) => i !== idx ); // => ['a', 'c'] A: You can perform the usual push and pop or `splice on your Array But because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates. According to All about Immutable Arrays and Objects in JavaScript you can do it this way... let messages = ['something', 'another', 'hello', 'word', 'another', 'again']; const indexOfHello = messages.indexOf('hello'); messages = [...messages.slice(0, indexOfHello), ...messages.slice(indexOfHello + 1)]; Note the difference between splice and slice The splice() method adds/removes items to/from an array, and returns the removed item(s). Note: This method changes the original array. Syntax: array.splice(start, deleteCount, itemstoAdd, addThisToo); But The slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. Note: The original array will not be changed. In order words It return a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified. Syntax: array.slice(start, end); A: You can try this: https://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1 use a library called svelox. It allows you to use the Array native api(push/splice...etc.) without reassignment statements.
How to update an array after splice in Svelte?
I'm learning Svelte, and read in the documentation that arrays need to be reassigned in order for a component or page to update it. For that they devised a more idiomatic solution. Instead of writing: messages.push('hello'); messages = messages; you can write instead: messages = [...messages, 'hello']; Alright, makes sense. But then the documentation says: You can use similar patterns to replace pop, shift, unshift and splice. But how? I cannot see how you can remove items from an array. More to the point, how could I write the following more idiomatically? messages.splice(messages.indexOf('hello'), 1); messages = messages;
[ "You could e.g. use the filter array method to create a new array without the element 'hello':\nmessages = messages.filter(m => m !== 'hello');\n\n", "As mentioned, Svelte's reactivity is triggered by assignments. The current Svelte tutorial uses JavaScript's (ES6) spread syntax (three dots) to add the next-higher number to an array, providing a more idiomatic solution than a redundant assignment using push:\nfunction pushNumber() { \n numbers = [...numbers, lastnumber]; // 1, 2, 3, 4, 5\n}\n\nYou could use spread syntax to replace pop, shift, unshift and splicethough it might increase the time and complexity of the operation in some cases:\nfunction unshiftNumber() { \n numbers = [firstnumber, ...numbers]; // 0, 1, 2, 3, 4\n}\n\nfunction popNumber() {\n numbers = [...numbers.slice(0,numbers.length - 1)]; // 1, 2, 3\n}\n\nfunction shiftNumber() {\n numbers = [...numbers.slice(1,numbers.length)]; // 2, 3, 4\n}\n\nfunction spliceNumber() {\n numbers = [firstnumber, ...numbers.slice(0,numbers.length-1)];// 0, 1, 2, 3\n} \n\nSpread is just one way to do it, though. The purpose behind not using pop/push etc is to encourage immutability. So any removal can just be a filter, for example.\n", "There are several things to consider here.\nGiven this code:\nmessages.splice(messages.indexOf('hello'), 1);\nmessages = messages;\n\nWhat's happening here is:\n\nLooking for the first occurrence of the string \"hello\" in the array\nRemoving such element from the array, based on the index found.\n\nThe assumption here is that \"hello\" needs to exists, otherwise the could would remove the last item from the array (since indexOf returns -1).\nThe original array is therefore mutate: depends by the context, that sometimes can be preferable instead of copying the whole array into a new one; otherwise it's generally a better practice avoid such mutation.\nSo. If you want to have this behavior exactly, probably this is the best code you can have. For example, takes the filter example:\nmessages = messages.filter(message => message !== \"hello\")\n\nWhat's happening here is:\n\nFilter out any element equals to \"hello\"\nReturns a new array without such element\n\nSo it's quite different from the original code: first of all, it always loop the whole array. If you have thousands of element, even if you have only one \"hello\" at the second index, it would always iterate all of them. Maybe it's what you want, maybe not. If the element is unique, such as an id, maybe you want to stop once you find it.\nSecond, it returns a new array. Again, that usually a better practice than mutate the array, but in some context it's preferable mutate it instead of create a new one.\nSo, if you want to mutate the original array, it's probably better to stick to your original code.\nIf, instead, you don't care (such as the example of push), I believe that in the intention of svelte's developers, your code would be roughly translate to:\nlet i = messages.indexOf(\"hello\"); \nmessages = [...messages.slice(0, i), ...messages.slice(i + 1)];\n\n(Still assuming there is a \"hello\" message and you're interested only in the first occurrence).\nIt's unfortunate that JS doesn't have a better syntax to handles slices.\n", "In case you're wandering, filter can also be used to remove elements using a given index:\nlet elements = ['a','b', 'c'];\nlet idx = 1;\nelements = elements.filter( (e,i) => i !== idx );\n// => ['a', 'c']\n\n", "You can perform the usual push and pop or `splice on your Array\n\nBut because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates.\n\nAccording to All about Immutable Arrays and Objects in JavaScript you can do it this way...\nlet messages = ['something', 'another', 'hello', 'word', 'another', 'again'];\n\nconst indexOfHello = messages.indexOf('hello');\n\nmessages = [...messages.slice(0, indexOfHello), ...messages.slice(indexOfHello + 1)];\n\nNote the difference between splice and slice\n\nThe splice() method adds/removes items to/from an array, and returns\n the removed item(s). Note: This method changes the original array.\n Syntax: array.splice(start, deleteCount, itemstoAdd, addThisToo);\n\nBut \n\nThe slice() method returns the selected elements in an array, as a new array object. The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.\n Note: The original array will not be changed. \n\nIn order words\n\nIt return a shallow copy of a portion of an array into a new array\n object selected from begin to end (end not included). The original\n array will not be modified.\n Syntax: array.slice(start, end);\n\n", "You can try this: https://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1\nuse a library called svelox. It allows you to use the Array native api(push/splice...etc.) without reassignment statements.\n" ]
[ 27, 15, 6, 3, 1, 0 ]
[ "Spread the spliced array to reassign it to itself ;)\nmessages = [...messages.splice(messages.indexOf('hello'), 1)];\n\nThe goal is to make Svelte detecting that array messages (a property of your component or a variable in the Svelte store) has changed. This is why the array messages must be declared with let or var keyword, not const. This way you're allowed to reassign it. And the reassign operation itself is sufficient to make Svelte detecting that the array has changed.\nPerhaps even, simply by doing so works too:\nmessages = messages.splice(messages.indexOf('hello'), 1);\n\n" ]
[ -1 ]
[ "arrays", "javascript", "svelte" ]
stackoverflow_0058964087_arrays_javascript_svelte.txt
Q: gh API - filter Pull Requests older then certain days ago Is there a way to filter ids of PRs based on the timeago information when they were created/updated: ie. 1 day ago? The only available field in json is createdAt/updatedAt which has following format: 2022-11-29T12:59:17Z I would like to list PRs older than certain amount of days. I am using command gh pr list The output should be ids of the PRs like this: MDExOlB1bGxSZXF1ZXN0NTE1OOI4Jg== MDExOlB1bGxSZXF1ZXN0NTE1OOI4Jg== A: To filter pull requests on GitHub based on their age, you can use the state and created_at parameters in the /pulls endpoint of the GitHub API. The state parameter can be used to specify whether you want to include open or closed pull requests, while the created parameter can be used to filter pull requests based on the date they were created. Here is an example of how you can use these parameters to filter pull requests that are older than 30 days: GET /repos/{owner}/{repo}/pulls?state=all&created_at:<=2022-11-01T00:00:00Z In this example, the state parameter is set to all to include both open and closed pull requests, and the created_at parameter is set to <=2022-11-01T00:00:00Z to filter pull requests that were created before November 1, 2020. This will return a list of all pull requests that are older than 30 days. You can adjust the created_at parameter as needed to filter pull requests based on their age. Keep in mind that the GitHub API has strict rate limiting, so you may need to use pagination to retrieve all of the pull requests that match your filter criteria. You can use the page and per_page parameters to control pagination, as well as the Link header in the API response to navigate to the next or previous page of results.
gh API - filter Pull Requests older then certain days ago
Is there a way to filter ids of PRs based on the timeago information when they were created/updated: ie. 1 day ago? The only available field in json is createdAt/updatedAt which has following format: 2022-11-29T12:59:17Z I would like to list PRs older than certain amount of days. I am using command gh pr list The output should be ids of the PRs like this: MDExOlB1bGxSZXF1ZXN0NTE1OOI4Jg== MDExOlB1bGxSZXF1ZXN0NTE1OOI4Jg==
[ "To filter pull requests on GitHub based on their age, you can use the state and created_at parameters in the /pulls endpoint of the GitHub API. The state parameter can be used to specify whether you want to include open or closed pull requests, while the created parameter can be used to filter pull requests based on the date they were created.\nHere is an example of how you can use these parameters to filter pull requests that are older than 30 days:\nGET /repos/{owner}/{repo}/pulls?state=all&created_at:<=2022-11-01T00:00:00Z\n\nIn this example, the state parameter is set to all to include both open and closed pull requests, and the created_at parameter is set to <=2022-11-01T00:00:00Z to filter pull requests that were created before November 1, 2020. This will return a list of all pull requests that are older than 30 days.\nYou can adjust the created_at parameter as needed to filter pull requests based on their age.\nKeep in mind that the GitHub API has strict rate limiting, so you may need to use pagination to retrieve all of the pull requests that match your filter criteria. You can use the page and per_page parameters to control pagination, as well as the Link header in the API response to navigate to the next or previous page of results.\n" ]
[ 1 ]
[]
[]
[ "github", "github_api" ]
stackoverflow_0074655548_github_github_api.txt
Q: Boxed trait object is still an unknown size The Error: So I'm getting the following error: error[E0277]: the size for values of type 'dyn Getter' cannot be known at compilation time struct PlusFive; impl Operator for PlusFive { fn apply<'a>(&self, a: &'a dyn Getter) -> Box<dyn Getter + 'a> { Box::new(MapGetter { source: a, // A pointer to some Getter f: |n:i32| n + 5 // A way to later compute +5 on source }); } } the trait Sized is not implemented for dyn Getter the trait Getter is implemented for MapGetter<T, F> The Question: I'm not sure what this errors means or how to resolve it. The size dyn Getter can't be known, but the size of MapGetter certainly can! and Since MapGetter is a concrete type that implements the Getter trait, I don't see why I can't Box this up and return it. I'm missing something here. I can Box up the MapGetter, what I can't do is lift it into a trait object? Here's the full example I'm working with if it helps to see it all in context: Note: On the whole, I've been trying to do this with dynamic dispatch. In part because I want to see what can be done and in part because I foresee myself wanting a list of dyn Operators where the concrete types underneath may vary. I don't want to attach operators to the Getter trait directly because eventually I want the operators to represent re-usable pieces of logic, so they can be applied to a Getter after the fact (or more than once) Full Context: trait Getter { fn compute(&self) -> i32; fn pipe(&self, operator: &dyn Operator) -> Box<dyn Getter> where Self: Sized, { operator.apply(&self) } } impl<T: Getter> Getter for &T { fn compute(&self) -> i32 { (*self).compute() } } impl<T: Getter> Getter for Box<T> { fn compute(&self) -> i32 { (*self).compute() } } struct PureGetter<T>(T); impl Getter for PureGetter<i32> { fn compute(&self) -> i32 { self.0 } } struct MapGetter<T, F> { source: T, (*self).compute() f: F, } impl<T, F> Getter for MapGetter<T, F> where T: Getter, F: FnMut(i32) -> i32 + Clone, { fn compute(&self) -> i32 { (self.f.clone())(self.source.compute()) } } trait Operator { fn apply<'a>(&self, a: &'a dyn Getter) -> Box<dyn Getter + 'a>; } struct PlusFive; impl Operator for PlusFive { fn apply<'a>(&self, a: &'a dyn Getter) -> Box<dyn Getter + 'a> { Box::new(MapGetter { source: a, f: |n:i32| n + 5 }) } } fn main() { let result = PureGetter(0).pipe(&PlusFive).compute(); println!("{:#?}", result); } error[E0277]: the size for values of type `dyn Getter` cannot be known at compilation time --> src/main.rs:71:9 | 71 | / Box::new(MapGetter { 72 | | source: a, 73 | | f: |n:i32| n + 5 74 | | }) | |__________^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `dyn Getter` = help: the trait `Getter` is implemented for `MapGetter<T, F>` note: required for `&dyn Getter` to implement `Getter` --> src/main.rs:24:17 | 24 | impl<T: Getter> Getter for &T { | ^^^^^^ ^^ = note: 1 redundant requirement hidden = note: required for `MapGetter<&dyn Getter, [closure@src/main.rs:73:16: 73:23]>` to implement `Getter` = note: required for the cast from `MapGetter<&dyn Getter, [closure@src/main.rs:73:16: 73:23]>` to the object type `dyn Getter` For more information about this error, try `rustc --explain E0277`. error: could not compile `messin` due to previous error A: Minimized example for this specific error: trait Getter {} impl<T: Getter> Getter for &T {} impl Getter for () {} fn main() { let getter: &dyn Getter = &(); let getter: Box<dyn Getter> = Box::new(getter); } Playground The reason is the following: To create a Box<dyn Getter> from Box<&dyn Getter>, &dyn Getter must implement Getter itself. &T has a blanket implementation for Getter. But the generic parameter of this implementation has an implicit Sized bound, therefore it can't be applied to &dyn Getter. To fix the immediate problem, you can simply relax the bound: impl<T: Getter + ?Sized> Getter for &T {} In your original code, the reasoning is similar, just with one more intermediate step - you have to pass impl Getter to MapGetter, so that MapGetter is Getter itself; but the passed-in value is &dyn Getter, which isn't Getter for the reasons above. As an aside, I'd say that it is quite unidiomatic to have both references and Boxes at the same time. You'd probably have an easier way if you restricted yourself to only one of them - either loaning the temporary references all the way down, or Boxing everything to own everything.
Boxed trait object is still an unknown size
The Error: So I'm getting the following error: error[E0277]: the size for values of type 'dyn Getter' cannot be known at compilation time struct PlusFive; impl Operator for PlusFive { fn apply<'a>(&self, a: &'a dyn Getter) -> Box<dyn Getter + 'a> { Box::new(MapGetter { source: a, // A pointer to some Getter f: |n:i32| n + 5 // A way to later compute +5 on source }); } } the trait Sized is not implemented for dyn Getter the trait Getter is implemented for MapGetter<T, F> The Question: I'm not sure what this errors means or how to resolve it. The size dyn Getter can't be known, but the size of MapGetter certainly can! and Since MapGetter is a concrete type that implements the Getter trait, I don't see why I can't Box this up and return it. I'm missing something here. I can Box up the MapGetter, what I can't do is lift it into a trait object? Here's the full example I'm working with if it helps to see it all in context: Note: On the whole, I've been trying to do this with dynamic dispatch. In part because I want to see what can be done and in part because I foresee myself wanting a list of dyn Operators where the concrete types underneath may vary. I don't want to attach operators to the Getter trait directly because eventually I want the operators to represent re-usable pieces of logic, so they can be applied to a Getter after the fact (or more than once) Full Context: trait Getter { fn compute(&self) -> i32; fn pipe(&self, operator: &dyn Operator) -> Box<dyn Getter> where Self: Sized, { operator.apply(&self) } } impl<T: Getter> Getter for &T { fn compute(&self) -> i32 { (*self).compute() } } impl<T: Getter> Getter for Box<T> { fn compute(&self) -> i32 { (*self).compute() } } struct PureGetter<T>(T); impl Getter for PureGetter<i32> { fn compute(&self) -> i32 { self.0 } } struct MapGetter<T, F> { source: T, (*self).compute() f: F, } impl<T, F> Getter for MapGetter<T, F> where T: Getter, F: FnMut(i32) -> i32 + Clone, { fn compute(&self) -> i32 { (self.f.clone())(self.source.compute()) } } trait Operator { fn apply<'a>(&self, a: &'a dyn Getter) -> Box<dyn Getter + 'a>; } struct PlusFive; impl Operator for PlusFive { fn apply<'a>(&self, a: &'a dyn Getter) -> Box<dyn Getter + 'a> { Box::new(MapGetter { source: a, f: |n:i32| n + 5 }) } } fn main() { let result = PureGetter(0).pipe(&PlusFive).compute(); println!("{:#?}", result); } error[E0277]: the size for values of type `dyn Getter` cannot be known at compilation time --> src/main.rs:71:9 | 71 | / Box::new(MapGetter { 72 | | source: a, 73 | | f: |n:i32| n + 5 74 | | }) | |__________^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `dyn Getter` = help: the trait `Getter` is implemented for `MapGetter<T, F>` note: required for `&dyn Getter` to implement `Getter` --> src/main.rs:24:17 | 24 | impl<T: Getter> Getter for &T { | ^^^^^^ ^^ = note: 1 redundant requirement hidden = note: required for `MapGetter<&dyn Getter, [closure@src/main.rs:73:16: 73:23]>` to implement `Getter` = note: required for the cast from `MapGetter<&dyn Getter, [closure@src/main.rs:73:16: 73:23]>` to the object type `dyn Getter` For more information about this error, try `rustc --explain E0277`. error: could not compile `messin` due to previous error
[ "Minimized example for this specific error:\ntrait Getter {}\n\nimpl<T: Getter> Getter for &T {}\n\nimpl Getter for () {}\n\nfn main() {\n let getter: &dyn Getter = &();\n let getter: Box<dyn Getter> = Box::new(getter);\n}\n\nPlayground\nThe reason is the following:\n\nTo create a Box<dyn Getter> from Box<&dyn Getter>, &dyn Getter must implement Getter itself.\n&T has a blanket implementation for Getter.\nBut the generic parameter of this implementation has an implicit Sized bound, therefore it can't be applied to &dyn Getter.\n\nTo fix the immediate problem, you can simply relax the bound:\nimpl<T: Getter + ?Sized> Getter for &T {}\n\nIn your original code, the reasoning is similar, just with one more intermediate step - you have to pass impl Getter to MapGetter, so that MapGetter is Getter itself; but the passed-in value is &dyn Getter, which isn't Getter for the reasons above.\n\nAs an aside, I'd say that it is quite unidiomatic to have both references and Boxes at the same time. You'd probably have an easier way if you restricted yourself to only one of them - either loaning the temporary references all the way down, or Boxing everything to own everything.\n" ]
[ 4 ]
[]
[]
[ "rust" ]
stackoverflow_0074656761_rust.txt
Q: how to create arrow down/up in css How can I create a arrow point down /up in css? I tried to build it from div: .triangle_down { width: 0; height: 0; border-left: 15px solid transparent; border-right: 15px solid transparent; border-top: 15px solid #2f2f2f; font-size: 0; line-height: 0; float: left; } This is the result:. But i tried to build something like this: Any suggestions? A: My proposal is: .triangle_down { width: 0; height: 0; border-left: 15px solid transparent; border-right: 15px solid transparent; border-top: 15px solid #2f2f2f; font-size: 0; line-height: 0; float: left; } .triangle_down1 { position: relative; top: -5px; content: ""; display: inline-block; width: 15px; height: 15px; border-right: 0.2em solid black; border-top: 0.2em solid black; transform: rotate(135deg); margin-right: 0.5em; margin-left: 1.0em; } .triangle_up1 { position: relative; top: -5px; content: ""; display: inline-block; width: 15px; height: 15px; border-right: 0.2em solid black; border-top: 0.2em solid black; transform: rotate(-45deg); margin-right: 0.5em; margin-left: 1.0em; } <div id="dialog1" class="triangle_down"></div> <div id="dialog2" class="triangle_down1"></div> <div id="dialog3" class="triangle_up1"></div> A: If you don't want to use icons you can use ::before and ::after pseudo-class. This is one of the various way you can get an arrow in pure CSS. HTML <div class="arrow"></div> CSS .arrow { position: absolute; top: 20px; left: 20px; } .arrow::before, .arrow::after { position: relative; content: ''; display: block; width: 20px; height: 1px; background: #000; } .arrow::before { transform: rotate(45deg); } .arrow::after { left: 14px; transform: rotate(-45deg); } You can find an example here: https://jsfiddle.net/f3qpujpL/2/ A: What you want is a chevron, not an arrow. Pure CSS solution: .chevron::before { border-style: solid; border-width: 0.15em 0.15em 0 0; content: ''; display: inline-block; height: 0.45em; left: 0.15em; top: 0.15em; vertical-align: top; width: 0.45em; transform: rotate(135deg); } Check out this JSFiddle A: #uparrow:before { content: '\276F'; } #downarrow:before { content: '\276E'; } #uparrow, #downarrow { font-size: 30px; display: inline-block; -ms-transform: rotate(90deg); -webkit-transform: rotate(90deg); transform: rotate(90deg); padding: 10px; } <span id="uparrow"></span><span id="downarrow"></span> You can include unicode characters like that, which are used by pretty much any system nowadays. Check out how it looks here: https://jsfiddle.net/mcdbu2pj/2/ Simply find the correct unicode characters you want. It won't matter which direction they're in, as you can just rotate them (like I did). Remember to set their display property to inline-block! A: Depending on the type of arrow you need, there is a very simple approach using HTML symbol codes. For instance I used &#x2191; for an arrow pointing upwards. I found it here HTML Symbols A: As simple as it gets: .up, .down { content: ""; width: 10px; height: 10px; border: solid black; border-width: 1px 1px 0 0; } .up { transform: rotate(-45deg); } .down { transform: rotate(135deg); } Don't forget: <div class="up"></div> <div class="down"></div>
how to create arrow down/up in css
How can I create a arrow point down /up in css? I tried to build it from div: .triangle_down { width: 0; height: 0; border-left: 15px solid transparent; border-right: 15px solid transparent; border-top: 15px solid #2f2f2f; font-size: 0; line-height: 0; float: left; } This is the result:. But i tried to build something like this: Any suggestions?
[ "My proposal is:\n\n\n.triangle_down {\r\n width: 0;\r\n height: 0;\r\n border-left: 15px solid transparent;\r\n border-right: 15px solid transparent;\r\n border-top: 15px solid #2f2f2f;\r\n font-size: 0;\r\n line-height: 0;\r\n float: left;\r\n}\r\n.triangle_down1 {\r\n position: relative;\r\n top: -5px;\r\n content: \"\";\r\n display: inline-block;\r\n width: 15px;\r\n height: 15px;\r\n border-right: 0.2em solid black;\r\n border-top: 0.2em solid black;\r\n transform: rotate(135deg);\r\n margin-right: 0.5em;\r\n margin-left: 1.0em;\r\n}\r\n .triangle_up1 {\r\n position: relative;\r\n top: -5px;\r\n content: \"\";\r\n display: inline-block;\r\n width: 15px;\r\n height: 15px;\r\n border-right: 0.2em solid black;\r\n border-top: 0.2em solid black;\r\n transform: rotate(-45deg);\r\n margin-right: 0.5em;\r\n margin-left: 1.0em;\r\n }\n<div id=\"dialog1\" class=\"triangle_down\"></div>\r\n<div id=\"dialog2\" class=\"triangle_down1\"></div>\r\n<div id=\"dialog3\" class=\"triangle_up1\"></div>\n\n\n\n", "If you don't want to use icons you can use ::before and ::after pseudo-class.\nThis is one of the various way you can get an arrow in pure CSS.\nHTML\n<div class=\"arrow\"></div>\n\nCSS \n.arrow {\n position: absolute;\n top: 20px;\n left: 20px;\n}\n\n.arrow::before,\n.arrow::after {\n position: relative;\n content: '';\n display: block;\n width: 20px;\n height: 1px;\n background: #000;\n}\n\n.arrow::before {\n transform: rotate(45deg);\n}\n\n.arrow::after {\n left: 14px;\n transform: rotate(-45deg);\n}\n\nYou can find an example here: https://jsfiddle.net/f3qpujpL/2/\n", "What you want is a chevron, not an arrow. Pure CSS solution:\n.chevron::before {\n border-style: solid;\n border-width: 0.15em 0.15em 0 0;\n content: '';\n display: inline-block;\n height: 0.45em;\n left: 0.15em;\n top: 0.15em;\n vertical-align: top;\n width: 0.45em;\n transform: rotate(135deg);\n}\n\nCheck out this JSFiddle\n", "\n\n#uparrow:before {\r\n content: '\\276F';\r\n}\r\n\r\n#downarrow:before {\r\n content: '\\276E';\r\n}\r\n\r\n#uparrow, #downarrow {\r\n font-size: 30px;\r\n display: inline-block;\r\n -ms-transform: rotate(90deg);\r\n -webkit-transform: rotate(90deg);\r\n transform: rotate(90deg);\r\n padding: 10px;\r\n}\n<span id=\"uparrow\"></span><span id=\"downarrow\"></span>\n\n\n\nYou can include unicode characters like that, which are used by pretty much any system nowadays. Check out how it looks here: https://jsfiddle.net/mcdbu2pj/2/\nSimply find the correct unicode characters you want. It won't matter which direction they're in, as you can just rotate them (like I did). Remember to set their display property to inline-block!\n", "Depending on the type of arrow you need, there is a very simple approach using HTML symbol codes. For instance I used &#x2191; for an arrow pointing upwards.\nI found it here HTML Symbols\n", "As simple as it gets:\n.up,\n.down {\n content: \"\";\n width: 10px;\n height: 10px;\n border: solid black;\n border-width: 1px 1px 0 0;\n}\n.up {\n transform: rotate(-45deg);\n}\n.down {\n transform: rotate(135deg);\n}\n\nDon't forget:\n<div class=\"up\"></div>\n<div class=\"down\"></div>\n\n" ]
[ 9, 6, 5, 4, 0, 0 ]
[]
[]
[ "css", "html", "javascript", "jquery" ]
stackoverflow_0034623447_css_html_javascript_jquery.txt
Q: Bootstrap 5 : Footer full width not working I am currently using the Bootstrap footer example and I am having a hard time figuring out how to make the footer in full width. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <div class="container-fluid"> <footer class="py-4 bg-dark"> <ul class="nav justify-content-center border-bottom pb-3 mb-3"> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">Home</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">Features</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">Pricing</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">FAQs</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">About</a></li> </ul> <p class="text-center text-muted">&copy; 2022 Company, Inc</p> </footer> </div> I already tried to add footer {width: 100%;} but it didn't work. A: Bootstrap container classes add padding to the left and right. according to doc you can add px-0 along with container classes. <div class="container-fluid px-0"> .... </div>
Bootstrap 5 : Footer full width not working
I am currently using the Bootstrap footer example and I am having a hard time figuring out how to make the footer in full width. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <div class="container-fluid"> <footer class="py-4 bg-dark"> <ul class="nav justify-content-center border-bottom pb-3 mb-3"> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">Home</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">Features</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">Pricing</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">FAQs</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-muted">About</a></li> </ul> <p class="text-center text-muted">&copy; 2022 Company, Inc</p> </footer> </div> I already tried to add footer {width: 100%;} but it didn't work.
[ "Bootstrap container classes add padding to the left and right. according to doc you can add px-0 along with container classes.\n<div class=\"container-fluid px-0\">\n....\n</div>\n\n" ]
[ 1 ]
[]
[]
[ "bootstrap_5", "css", "html", "twitter_bootstrap" ]
stackoverflow_0074657188_bootstrap_5_css_html_twitter_bootstrap.txt
Q: Java: Both if and else statements run I am trying to refector a 2D array project to include a search method to clean up the code in my main method. However, when I enter a valid name it can find the first row of data but will also print the else statement. If I enter a valid name for second row it will sometimes return it after printing the else statement. I've tried rewriting the code, creating a return variable for the method, using a nested loop, modifying the return array value. static Scanner scan = new Scanner(System.in); public static void main(String[] args) { System.out.println("==== Family Affair ===="); System.out.println("How many members will you add?"); int number = scan.nextInt(); scan.nextLine();//scan.nextLine() ad hoc scan fix //2D Array number of rows by scan/number input String[][] familyData = new String[number][2]; //for loop captures input column data for each row //nested loop created duplicate output for (int i = 0; i < familyData.length; i++) { System.out.print("\tName: "); familyData[i][0] = scan.nextLine(); System.out.print("\tState: "); familyData[i][1] = scan.nextLine(); System.out.println(" "); } System.out.println(" ");//extra space printData(familyData);//call printData() method findData(familyData);//call findData() method } public static void printData(String[][] data) { for (int i = 0; i < data.length; i++) { System.out.print("\tName: " + data[i][0] + " "); System.out.print("\tState: " + data[i][1] + " "); System.out.println(" "); } } public static String[] findData(String[][] data) { System.out.println("SEARCH..."); System.out.println("First Name: "); String name = scan.nextLine(); String[] resultData = new String[0]; for (int i = 0; i < data.length; i++) { if (name.equals(data[i][0])) { System.out.println("--- Search Results ---"); System.out.println("\tName: " + data[i][0]); System.out.println("\tState: " + data[i][1]); }else { System.out.println("Nothing found. Try Again"); System.out.println("First Name: "); name = scan.nextLine(); } } return resultData; //returned as String[] results = findData(param); } A: Let me suggest the use of List<> import java.util.ArrayList; import java.util.List; private static List<String[]> findData(String[][] source, String search) { final List<String[]> data = new ArrayList<>(); for (String[] array : source) { if (search.equals(array[0])) { data.add(array); } } return data; } And here is an example of use public static void main(String args[]) { String[][] familyData = new String[2][2]; familyData[0][0] = "Sulabha"; familyData[0][1] = "Married"; familyData[1][0] = "Bertram"; familyData[1][1] = "Single"; List<String[]> data = findData(familyData, "Sulabha"); if (data.size() == 0) { System.out.println("Nothing found."); } else { for (String[] item : data) { System.out.println("--- Search Results ---"); System.out.println("\tName: " + item[0]); System.out.println("\tState: " + item[1]); } } }
Java: Both if and else statements run
I am trying to refector a 2D array project to include a search method to clean up the code in my main method. However, when I enter a valid name it can find the first row of data but will also print the else statement. If I enter a valid name for second row it will sometimes return it after printing the else statement. I've tried rewriting the code, creating a return variable for the method, using a nested loop, modifying the return array value. static Scanner scan = new Scanner(System.in); public static void main(String[] args) { System.out.println("==== Family Affair ===="); System.out.println("How many members will you add?"); int number = scan.nextInt(); scan.nextLine();//scan.nextLine() ad hoc scan fix //2D Array number of rows by scan/number input String[][] familyData = new String[number][2]; //for loop captures input column data for each row //nested loop created duplicate output for (int i = 0; i < familyData.length; i++) { System.out.print("\tName: "); familyData[i][0] = scan.nextLine(); System.out.print("\tState: "); familyData[i][1] = scan.nextLine(); System.out.println(" "); } System.out.println(" ");//extra space printData(familyData);//call printData() method findData(familyData);//call findData() method } public static void printData(String[][] data) { for (int i = 0; i < data.length; i++) { System.out.print("\tName: " + data[i][0] + " "); System.out.print("\tState: " + data[i][1] + " "); System.out.println(" "); } } public static String[] findData(String[][] data) { System.out.println("SEARCH..."); System.out.println("First Name: "); String name = scan.nextLine(); String[] resultData = new String[0]; for (int i = 0; i < data.length; i++) { if (name.equals(data[i][0])) { System.out.println("--- Search Results ---"); System.out.println("\tName: " + data[i][0]); System.out.println("\tState: " + data[i][1]); }else { System.out.println("Nothing found. Try Again"); System.out.println("First Name: "); name = scan.nextLine(); } } return resultData; //returned as String[] results = findData(param); }
[ "Let me suggest the use of List<>\nimport java.util.ArrayList;\nimport java.util.List;\n\nprivate static List<String[]> findData(String[][] source, String search)\n{\n final List<String[]> data = new ArrayList<>();\n \n for (String[] array : source)\n {\n if (search.equals(array[0]))\n {\n data.add(array);\n }\n }\n \n return data;\n}\n\nAnd here is an example of use\npublic static void main(String args[])\n{\n String[][] familyData = new String[2][2];\n \n familyData[0][0] = \"Sulabha\";\n familyData[0][1] = \"Married\";\n \n familyData[1][0] = \"Bertram\";\n familyData[1][1] = \"Single\";\n \n List<String[]> data = findData(familyData, \"Sulabha\");\n \n if (data.size() == 0)\n {\n System.out.println(\"Nothing found.\");\n }\n else\n {\n for (String[] item : data)\n {\n System.out.println(\"--- Search Results ---\");\n System.out.println(\"\\tName: \" + item[0]);\n System.out.println(\"\\tState: \" + item[1]); \n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "if_statement", "java", "methods" ]
stackoverflow_0074656933_if_statement_java_methods.txt
Q: How can i change the string type value from this enum to an integer? C# using System.Runtime.Serialization; namespace InmofactoryService.Enums { public enum PropertyStatus { [EnumMember(Value = "1")] Disponible = 24000, [EnumMember(Value = "2")] Reservado, [EnumMember(Value = "3")] Captación, [EnumMember(Value = "4")] NoDisponible, [EnumMember(Value = "5")] EnConstruccion } } I want that the EnumMember value change from string to int I see that EnumMember only accepts string A: If you look into EnumMember docs at Microsoft Docs you can see it default return not null string you observed, it already. Hence you can get output and convert it to int inside your parent method.
How can i change the string type value from this enum to an integer? C#
using System.Runtime.Serialization; namespace InmofactoryService.Enums { public enum PropertyStatus { [EnumMember(Value = "1")] Disponible = 24000, [EnumMember(Value = "2")] Reservado, [EnumMember(Value = "3")] Captación, [EnumMember(Value = "4")] NoDisponible, [EnumMember(Value = "5")] EnConstruccion } } I want that the EnumMember value change from string to int I see that EnumMember only accepts string
[ "If you look into EnumMember docs at Microsoft Docs you can see it default return not null string you observed, it already. Hence you can get output and convert it to int inside your parent method.\n" ]
[ 0 ]
[]
[]
[ ".net_core", "c#" ]
stackoverflow_0074657024_.net_core_c#.txt
Q: NodeJS MSSQL results to JSON array I am trying to create an array of JSON objects from an SQL Server query using NodeJS but using just JSON.Stringify on each row I get the results I am looking for as all individual JSON objects but not in an array. Ideally I am just trying to write these results to a file as a JSON array. Any ideas appreciated. Tried the following const sql=require('mssql'); const fs=require('fs'); const config = { // Creds removed }, }; sql.connect(config, err => { console.log(err); const request = new sql.Request() request.stream = true // You can set streaming differently for each request request.query(fs.readFileSync('./new-query.sql').toString()); // or request.execute(procedure) request.on('row', row => { console.log(JSON.stringify(row)); }) request.on('error', err => { console.log(err); // May be emitted multiple times }) request.on('done', result => { // console.log('done emitted', result); sql.close(); }) }) A: As always, reading the library notes in more detail led me to a solution. Using the MSSQL library you can actually work on the entire returned recordset as opposed to every column. Using this code works as I was wanting it to. const sql = require('mssql') const fs=require('fs'); const config = { // cred removed }; sql.connect(config).then(() => { return sql.query(fs.readFileSync('./new-query.sql').toString()) }).then(result => { console.log(JSON.stringify(result.recordsets[0])) }).catch(err => { // ... error checks }) sql.on('error', err => { // ... error handler })
NodeJS MSSQL results to JSON array
I am trying to create an array of JSON objects from an SQL Server query using NodeJS but using just JSON.Stringify on each row I get the results I am looking for as all individual JSON objects but not in an array. Ideally I am just trying to write these results to a file as a JSON array. Any ideas appreciated. Tried the following const sql=require('mssql'); const fs=require('fs'); const config = { // Creds removed }, }; sql.connect(config, err => { console.log(err); const request = new sql.Request() request.stream = true // You can set streaming differently for each request request.query(fs.readFileSync('./new-query.sql').toString()); // or request.execute(procedure) request.on('row', row => { console.log(JSON.stringify(row)); }) request.on('error', err => { console.log(err); // May be emitted multiple times }) request.on('done', result => { // console.log('done emitted', result); sql.close(); }) })
[ "As always, reading the library notes in more detail led me to a solution. Using the MSSQL library you can actually work on the entire returned recordset as opposed to every column. Using this code works as I was wanting it to.\nconst sql = require('mssql')\nconst fs=require('fs');\n\n\nconst config = {\n// cred removed\n};\n\n\nsql.connect(config).then(() => {\n return sql.query(fs.readFileSync('./new-query.sql').toString())\n}).then(result => {\n console.log(JSON.stringify(result.recordsets[0]))\n}).catch(err => {\n // ... error checks\n})\n\nsql.on('error', err => {\n // ... error handler\n})\n\n" ]
[ 0 ]
[]
[]
[ "node.js", "sql_server" ]
stackoverflow_0074648076_node.js_sql_server.txt
Q: Unity get sprite from Image I am trying to get sprite from Image in Unity but I am facing an issue. I am using this code: void Start () { Sprite sprite = this.gameObject.GetComponent<Image> ().sprite; if (sprite == null) { Debug.Log ("NULL"); } else { Debug.Log ("NOT NULL"); } } If the sprite is empty, it does not recognize as "null". Why? and how to fix it? A: It works for me I don't know your use case but I can suggest some solution You shouldn't check references with == operator in Unity and you can read more about that here an here and there you can find a solution for your problem. A: If your component is an Image then the right property is Source Image, but if you are using a Sprite Renderer component then the property is Sprite. The difference between the 2 components are simple, Image component is used for UI elements and the SpriteRenderer is used for the world space environment. You can read more about the 2 components through there documentations.
Unity get sprite from Image
I am trying to get sprite from Image in Unity but I am facing an issue. I am using this code: void Start () { Sprite sprite = this.gameObject.GetComponent<Image> ().sprite; if (sprite == null) { Debug.Log ("NULL"); } else { Debug.Log ("NOT NULL"); } } If the sprite is empty, it does not recognize as "null". Why? and how to fix it?
[ "It works for me\nI don't know your use case but I can suggest some solution\nYou shouldn't check references with == operator in Unity and you can read more about that here an here and there you can find a solution for your problem.\n", "If your component is an Image then the right property is Source Image, but if you are using a Sprite Renderer component then the property is Sprite.\nThe difference between the 2 components are simple, Image component is used for UI elements and the SpriteRenderer is used for the world space environment.\nYou can read more about the 2 components through there documentations.\n" ]
[ 0, 0 ]
[]
[]
[ "c#", "unity3d" ]
stackoverflow_0074655676_c#_unity3d.txt
Q: "'SQL_AUTOCOMMIT_OFF' … is not implemented" error with SQLAlchemy engine I have been connecting to a database using pyodbc: DNS = 'PIODBC' pi_connection = pyodbc.connect("DSN=" + DSN + ";UID=" + uid + ";PWD=" +pw, autocommit = True) pd.read_sql_query(qry, pi_connection) This uses a PI ODBC Driver apparently, which could well be a proprietary thing which lets me connect to and OSIsoft PI database. This has been working fine for me. Recently I started getting the error message: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. I still get what I want but I want to do things properly so I've considered using SQLAlchemy. I don't want to just suppress the error. The code I've used is: from sqlalchemy import create_engine engine_str = "mssql+pyodbc://"+uid+":"+pw+"@"+DSN engine = create_engine(engine_str) with engine.connect() as con: rs = con.execute(qry) Unfortunately that throws up an actual error: DBAPIError: (pyodbc.Error) ('HYC00', "[HYC00] The 'SQL_AUTOCOMMIT_OFF' for the 'SQL_ATTR_AUTOCOMMIT' is not implemented. (0) (SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT))") (Background on this error at: https://sqlalche.me/e/14/dbapi) There are a number of related questions that I have seen: here, here, here, here, and here but I am not getting it. I feel like I've tried a million variations of my code in line with what is being said in the answers to these questions but I haven't managed to move on from both the errors. I'm just not understanding it all I suppose. I'm using Windows 10 (64 bit) and pyodbc 4.0.31 and SQLAlchemy 1.4.44 A: The OSIsoft ODBC driver for PI differs sufficiently from the MS SQL Server implementations that using mssql+pyodbc://… with SQLAlchemy is not going to work. For now you can continue using a plain DBAPI (pyodbc) connection for .read_sql_query() and just ignore the warnings from pandas. For full support with pandas — e.g., for .to_sql() — you will need to find (or create) a proper third-party SQLAlchemy dialect for OSIsoft PI. The technical support group at OSIsoft may be able to help you with that.
"'SQL_AUTOCOMMIT_OFF' … is not implemented" error with SQLAlchemy engine
I have been connecting to a database using pyodbc: DNS = 'PIODBC' pi_connection = pyodbc.connect("DSN=" + DSN + ";UID=" + uid + ";PWD=" +pw, autocommit = True) pd.read_sql_query(qry, pi_connection) This uses a PI ODBC Driver apparently, which could well be a proprietary thing which lets me connect to and OSIsoft PI database. This has been working fine for me. Recently I started getting the error message: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. I still get what I want but I want to do things properly so I've considered using SQLAlchemy. I don't want to just suppress the error. The code I've used is: from sqlalchemy import create_engine engine_str = "mssql+pyodbc://"+uid+":"+pw+"@"+DSN engine = create_engine(engine_str) with engine.connect() as con: rs = con.execute(qry) Unfortunately that throws up an actual error: DBAPIError: (pyodbc.Error) ('HYC00', "[HYC00] The 'SQL_AUTOCOMMIT_OFF' for the 'SQL_ATTR_AUTOCOMMIT' is not implemented. (0) (SQLSetConnectAttr(SQL_ATTR_AUTOCOMMIT))") (Background on this error at: https://sqlalche.me/e/14/dbapi) There are a number of related questions that I have seen: here, here, here, here, and here but I am not getting it. I feel like I've tried a million variations of my code in line with what is being said in the answers to these questions but I haven't managed to move on from both the errors. I'm just not understanding it all I suppose. I'm using Windows 10 (64 bit) and pyodbc 4.0.31 and SQLAlchemy 1.4.44
[ "The OSIsoft ODBC driver for PI differs sufficiently from the MS SQL Server implementations that using mssql+pyodbc://… with SQLAlchemy is not going to work. For now you can continue using a plain DBAPI (pyodbc) connection for .read_sql_query() and just ignore the warnings from pandas.\nFor full support with pandas — e.g., for .to_sql() — you will need to find (or create) a proper third-party SQLAlchemy dialect for OSIsoft PI. The technical support group at OSIsoft may be able to help you with that.\n" ]
[ 0 ]
[]
[]
[ "osisoft", "pandas", "pyodbc", "sqlalchemy" ]
stackoverflow_0074640731_osisoft_pandas_pyodbc_sqlalchemy.txt
Q: How to rerender {#each array} block in svelte after you push something to an array Hello I'm making a comment section for my website which works but when I push an object to an array my {#each} block doesn't update here is this block of code {#each commentsScript as { userName, rating, comment }, i} <div class="flex"> <div class="w-1/4"> <h5>{userName}</h5> <h5>{rating}</h5> </div> <div class="w-3/4"> <p>{comment}</p> </div> </div> {/each} In my script section, I push a new comment to an array and it does show up after I refresh the page but I want to rerender it as soon as the user leaves a comment so the user would see hes/her own comment so is there any way I can rerender it? A: https://svelte.dev/tutorial/updating-arrays-and-objects You have to assign commentsScript = commentsScript, which would be redundant normally, but that is how svelte works. This is true if you are using push function on array. A: In addition to reassignment, there are several existing libraries that help you use the Array native APIs. You can try this: https://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1 use a library called svelox. It allows you to use the Array native api(push/splice...etc.) without reassignment statements. Because it's weird to write a reassignment every time, this is something that every svelte beginner finds strange. Also, using the Array native APIs is not recommended(you should use spread).
How to rerender {#each array} block in svelte after you push something to an array
Hello I'm making a comment section for my website which works but when I push an object to an array my {#each} block doesn't update here is this block of code {#each commentsScript as { userName, rating, comment }, i} <div class="flex"> <div class="w-1/4"> <h5>{userName}</h5> <h5>{rating}</h5> </div> <div class="w-3/4"> <p>{comment}</p> </div> </div> {/each} In my script section, I push a new comment to an array and it does show up after I refresh the page but I want to rerender it as soon as the user leaves a comment so the user would see hes/her own comment so is there any way I can rerender it?
[ "https://svelte.dev/tutorial/updating-arrays-and-objects\nYou have to assign commentsScript = commentsScript, which would be redundant normally, but that is how svelte works. This is true if you are using push function on array.\n", "In addition to reassignment, there are several existing libraries that help you use the Array native APIs.\nYou can try this: https://svelte.dev/repl/0dedb37665014ba99e05415a6107bc21?version=3.53.1\nuse a library called svelox. It allows you to use the Array native api(push/splice...etc.) without reassignment statements.\nBecause it's weird to write a reassignment every time, this is something that every svelte beginner finds strange. Also, using the Array native APIs is not recommended(you should use spread).\n" ]
[ 3, 0 ]
[]
[]
[ "javascript", "svelte" ]
stackoverflow_0070962059_javascript_svelte.txt
Q: How to open a new tab from inside Visual Studio Code's integrated terminal (not with keyboard shortcuts)? I want to open a new terminal tab as part of a project I'm working on requires that I run another script in a new tab once I've got the first portion running. But I am not seeing how to automate this on macOS Big Sur. I am thinking AppleScript is the way to go, but if there's another way to run from ZSH I'd be thrilled. A: TLDR; I am not aware that it is possible, but all terminal shenanigans for spawning multiple background processes are possible in bash/zsh. See examples below, as well as links. Explanation It isn't possible to create a new terminal inside of Vscode from the terminal itself. Same thing goes for Jupyterlab, mainly for security reasons. But it is possible to spawn another terminal as part of the original command. bash -c 'some string command' And the use of operators like & ; && and ||, which execute depending on some condition. Mainly execute and don't wait. Execute regardless of the first command success ;, and execute if successful and unsuccessful the last two. (Check more here) command1 & command2 Example: echo 'something1' & echo 'something2' produces the following: [1] 53159 something1 something2 [1] + done echo 'something1' This can be combined with the first example:bash -c 'sleep 3; echo "something1"' & echo "something2" which produces: [1] 60427 something2 <machine_id>% something1 [1] + done bash -c 'sleep 3; echo "something1"' In addition, you can probably include some waits and signal catching, but that is another can of worms.
How to open a new tab from inside Visual Studio Code's integrated terminal (not with keyboard shortcuts)?
I want to open a new terminal tab as part of a project I'm working on requires that I run another script in a new tab once I've got the first portion running. But I am not seeing how to automate this on macOS Big Sur. I am thinking AppleScript is the way to go, but if there's another way to run from ZSH I'd be thrilled.
[ "TLDR; I am not aware that it is possible, but all terminal shenanigans for spawning multiple background processes are possible in bash/zsh. See examples below, as well as links.\nExplanation\nIt isn't possible to create a new terminal inside of Vscode from the terminal itself. Same thing goes for Jupyterlab, mainly for security reasons. But it is possible to spawn another terminal as part of the original command.\nbash -c 'some string command'\n\nAnd the use of operators like & ; && and ||, which execute depending on some condition. Mainly execute and don't wait. Execute regardless of the first command success ;, and execute if successful and unsuccessful the last two. (Check more here)\ncommand1 & command2 \n\nExample: echo 'something1' & echo 'something2' produces the following:\n[1] 53159\nsomething1\nsomething2\n[1] + done echo 'something1' \n\nThis can be combined with the first example:bash -c 'sleep 3; echo \"something1\"' & echo \"something2\" which produces:\n[1] 60427\nsomething2\n<machine_id>% something1\n\n[1] + done bash -c 'sleep 3; echo \"something1\"'\n\nIn addition, you can probably include some waits and signal catching, but that is another can of worms.\n" ]
[ 1 ]
[]
[]
[ "applescript", "visual_studio_code", "zsh" ]
stackoverflow_0074539607_applescript_visual_studio_code_zsh.txt
Q: changing values in array I am trying to build a battleship game and using functions. I wish to create and randomise 1 & 0 in my array every time I run the function as seen in the array below Since it is a battlefield game, is there any way to make the 1s be in a row /column of 4/3/2/1? , to mimic the different sizes of the battleships let battelfield = [ [0,0,0,1,1,1,1,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0], [0,0,0,0,0,0,1,0,0,0], [1,0,0,0,0,0,1,1,1,1], [1,0,0,0,0,0,0,0,0,0], [1,0,0,1,0,0,0,0,0,0], [1,0,0,1,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0] ]` A: For a battleship, the way I would do it would be (assuming your grid is already filled with 0s): For each ship randomly select a starting position randomly select a direction (up, down, left, right) add your ship (by changing however many 1s you need to, based on the size of the ship). The checks you need to add would be: At step 1, make sure there isn't a boat there already, in which case pick again. At step 2, make sure you're not going to hit the side of your game board, or another ship, in which case try another direction. If all 4 directions have been tried and there isn't enough space for a ship, back to step 1. A: I usually don't give full answers when OP doesn't really show they tried but I liked the challenge. The idea is to: Set your empty board. Choose a random point in the board where the ship will start Choose direction (H or V) With the random point and direction, make sure there is room for the ship according to the limits of the board Create a list of positions the ship will take Test all positions to make sure they are free Set the positions on the board as filled. At any given time, if a check is not fulfilled I've put continue; this will stop the current iteration and back to the beginning of the while. That way, the code runs until it finds a spot, and return to leave the loop. Also, I've made a 1d array instead of 2d because it felt easier for mathing it out and manipulations. Feel free to convert to 2D afterward, or not. let battlefield = new Array(10*10).fill(0); placeShip(3); placeShip(4); placeShip(4); placeShip(5); console.log(battlefield); function placeShip(length){ while(true){ const start = Math.round(Math.random()*99); if(battlefield[start]==='1') continue; const orientation = Math.random() <=.5?'H':'V'; // Fill the positions where the ship will be placed. const positions = new Array(); if(orientation === 'H'){ // First make sure we have room to place it if(10-((start+1) % 10) < length)continue; for(let p=start;p<start+length;p++){ // Set for each length the position the ship will take. positions.push(p); } }else if(orientation === 'V'){ // Same as for H but we divide by 10 because we want rows instead of cells. if(10-((start/10) % 10) < length)continue; for(let p=start;p<start+length*10;p+=10){ // Set for each length the position the ship will take. positions.push(p); } } // Now let's check to make sure there is not a ship already in one of the positions for(let i=0,L=positions.length;i<L;i++){ if(battlefield[positions[i]]!=="0")continue; } // Now let's put the ship in place for(let i=0,L=positions.length;i<L;i++){ battlefield[positions[i]] = 1; } return; } }
changing values in array
I am trying to build a battleship game and using functions. I wish to create and randomise 1 & 0 in my array every time I run the function as seen in the array below Since it is a battlefield game, is there any way to make the 1s be in a row /column of 4/3/2/1? , to mimic the different sizes of the battleships let battelfield = [ [0,0,0,1,1,1,1,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0], [0,0,0,0,0,0,1,0,0,0], [1,0,0,0,0,0,1,1,1,1], [1,0,0,0,0,0,0,0,0,0], [1,0,0,1,0,0,0,0,0,0], [1,0,0,1,0,0,0,0,0,0], [1,0,0,0,0,0,0,0,0,0] ]`
[ "For a battleship, the way I would do it would be (assuming your grid is already filled with 0s):\nFor each ship\n\n\n\nrandomly select a starting position\n\n\n\n\nrandomly select a direction (up, down, left, right)\n\n\n\n\nadd your ship (by changing however many 1s you need to, based on the size of the ship).\n\n\n\nThe checks you need to add would be:\n\nAt step 1, make sure there isn't a boat there already, in which case pick again.\nAt step 2, make sure you're not going to hit the side of your game board, or another ship, in which case try another direction. If all 4 directions have been tried and there isn't enough space for a ship, back to step 1.\n\n", "I usually don't give full answers when OP doesn't really show they tried but I liked the challenge.\nThe idea is to:\n\nSet your empty board.\nChoose a random point in the board where the ship will start\nChoose direction (H or V)\nWith the random point and direction, make sure there is room for the ship according to the limits of the board\nCreate a list of positions the ship will take\nTest all positions to make sure they are free\nSet the positions on the board as filled.\n\nAt any given time, if a check is not fulfilled I've put continue; this will stop the current iteration and back to the beginning of the while. That way, the code runs until it finds a spot, and return to leave the loop.\nAlso, I've made a 1d array instead of 2d because it felt easier for mathing it out and manipulations. Feel free to convert to 2D afterward, or not.\n\n\nlet battlefield = new Array(10*10).fill(0);\nplaceShip(3);\nplaceShip(4);\nplaceShip(4);\nplaceShip(5);\nconsole.log(battlefield);\n\nfunction placeShip(length){\n while(true){\n const start = Math.round(Math.random()*99);\n if(battlefield[start]==='1') continue;\n const orientation = Math.random() <=.5?'H':'V';\n // Fill the positions where the ship will be placed.\n const positions = new Array();\n if(orientation === 'H'){\n // First make sure we have room to place it\n if(10-((start+1) % 10) < length)continue;\n for(let p=start;p<start+length;p++){\n // Set for each length the position the ship will take.\n positions.push(p);\n }\n }else if(orientation === 'V'){\n // Same as for H but we divide by 10 because we want rows instead of cells.\n if(10-((start/10) % 10) < length)continue;\n for(let p=start;p<start+length*10;p+=10){\n // Set for each length the position the ship will take.\n positions.push(p);\n }\n }\n // Now let's check to make sure there is not a ship already in one of the positions\n for(let i=0,L=positions.length;i<L;i++){\n if(battlefield[positions[i]]!==\"0\")continue;\n }\n // Now let's put the ship in place\n for(let i=0,L=positions.length;i<L;i++){\n battlefield[positions[i]] = 1;\n }\n return;\n }\n}\n\n\n\n" ]
[ 1, 0 ]
[]
[]
[ "arrays", "dom", "javascript" ]
stackoverflow_0074656931_arrays_dom_javascript.txt
Q: Find names in string and map with value - SQL I've a data set by list of names: Sample data What I'm trying to achieve is: I want to map them into teams Below are the team views: so I want to map them according to the team, and the names are listed such a way that there can be combination of both teams or multiple people from same team.I created a sql query select name, ( Case when name in ("Tony","Sam", "Ben") then Maverick When name in ("Nick",Savi0","Cruz") then Lakers else "Bundle" end) as team_mapping from people Please find what my output is and what I'm trying to achieve. Some additional context: Row 8, 9, 10 are the names of teams which we need to categorise and they are separated by "enter" or "char(10)" So I want to search names in each row and map based on teams. If 2 people belong to same team then it should there team name and belongs to different then it should show as "bundle". Here is the trix for ref. Let me know how I can achieve this and any inputs on this much appreciated. Thanks in advance. A: Starting with a table tbl containing all player names. The teams table contains the teams and the player, separated by ,. I changed the names to A1 to A3 for easier readability. The teams table is unnested, so that for each player there is a row. In the main part, the table tbl is quered and the names are splitted by a new line this is done by: """ """ This is done in a subquery ((Select ... )). Here the splitted and unnested name parts are joined with the team table to obtain the team_name of each player. If there is a team_name missing, because the player is not known, the count(1) differs from the count(team_name) and "unknown player"``is the output. Otherwise and if the max and the min of the team_nameis the same, all players belong to the same team and theteam_nameis the output. Otherwise"Bundled"` is the output. with tbl as (select * from unnest(["A1","A2","A3","B1","B2","B3","""A1 B1""","""A1 A2""","C"]) name), teams as (select "team a" team_name, "A1,A2,A3" as players union all select "team b","B1,B2,B3"), team as (select team_name, player from teams, unnest(split(players,",")) as player) select *, ((Select if(count(1)!=count(team_name),"unknown player",if(min(team_name)=max(team_name),min(team_name),"Bundle")) from unnest(split(name,""" """)) x left join team on x=player )) from tbl
Find names in string and map with value - SQL
I've a data set by list of names: Sample data What I'm trying to achieve is: I want to map them into teams Below are the team views: so I want to map them according to the team, and the names are listed such a way that there can be combination of both teams or multiple people from same team.I created a sql query select name, ( Case when name in ("Tony","Sam", "Ben") then Maverick When name in ("Nick",Savi0","Cruz") then Lakers else "Bundle" end) as team_mapping from people Please find what my output is and what I'm trying to achieve. Some additional context: Row 8, 9, 10 are the names of teams which we need to categorise and they are separated by "enter" or "char(10)" So I want to search names in each row and map based on teams. If 2 people belong to same team then it should there team name and belongs to different then it should show as "bundle". Here is the trix for ref. Let me know how I can achieve this and any inputs on this much appreciated. Thanks in advance.
[ "Starting with a table tbl containing all player names. The teams table contains the teams and the player, separated by ,. I changed the names to A1 to A3 for easier readability. The teams table is unnested, so that for each player there is a row.\nIn the main part, the table tbl is quered and the names are splitted by a new line this is done by:\n\"\"\"\n\"\"\"\n\nThis is done in a subquery ((Select ... )). Here the splitted and unnested name parts are joined with the team table to obtain the team_name of each player. If there is a team_name missing, because the player is not known, the count(1) differs from the count(team_name) and \"unknown player\"``is the output. Otherwise and if the max and the min of the team_nameis the same, all players belong to the same team and theteam_nameis the output. Otherwise\"Bundled\"` is the output.\nwith tbl as (select * from unnest([\"A1\",\"A2\",\"A3\",\"B1\",\"B2\",\"B3\",\"\"\"A1\nB1\"\"\",\"\"\"A1\nA2\"\"\",\"C\"]) name),\nteams as (select \"team a\" team_name, \"A1,A2,A3\" as players union all select \"team b\",\"B1,B2,B3\"),\nteam as (select team_name, player from teams, unnest(split(players,\",\")) as player)\nselect *,\n((Select if(count(1)!=count(team_name),\"unknown player\",if(min(team_name)=max(team_name),min(team_name),\"Bundle\"))\nfrom unnest(split(name,\"\"\"\n\"\"\")) x \nleft join team\n on x=player\n))\n from tbl\n\n" ]
[ 1 ]
[]
[]
[ "google_bigquery", "mapping", "sql", "string" ]
stackoverflow_0074656888_google_bigquery_mapping_sql_string.txt
Q: Problem to convert date into string in excel I am facing an issue to convert a date into string in excel using TEXT and TODAY(). When I use the following formula: ="today is " & TEXT(TODAY(); "dd/mm/yyyy") into a cell I got a value error. When I test with a different formatting: ="today is " & TEXT(TODAY(); "ddmmyyyy") this time I got "today is dd12yyyy" instead of today is 02122022. I would like to display according the first formatting: "today is 02/12/2022" (For December 2nd 2022). A: I suggest you need: ="today is " & TEXT(TODAY(), "dd/mm/yyyy") I have tested on mine and that works correctly. If you copied that formula from the web then they may have the ; as their separator, something we have learnt to spot.
Problem to convert date into string in excel
I am facing an issue to convert a date into string in excel using TEXT and TODAY(). When I use the following formula: ="today is " & TEXT(TODAY(); "dd/mm/yyyy") into a cell I got a value error. When I test with a different formatting: ="today is " & TEXT(TODAY(); "ddmmyyyy") this time I got "today is dd12yyyy" instead of today is 02122022. I would like to display according the first formatting: "today is 02/12/2022" (For December 2nd 2022).
[ "I suggest you need:\n=\"today is \" & TEXT(TODAY(), \"dd/mm/yyyy\")\n\nI have tested on mine and that works correctly.\nIf you copied that formula from the web then they may have the ; as their separator, something we have learnt to spot.\n\n" ]
[ 0 ]
[]
[]
[ "date", "excel", "excel_formula", "text" ]
stackoverflow_0074656687_date_excel_excel_formula_text.txt
Q: I use Django with PostgreSQL on docker compose, but django-test can't access database I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_service.conf and .pgpass. docker-compose.yml version: "3.9" services: web: build: context: . container_name: web restart: unless-stopped tty: true working_dir: /opt/apps volumes: - .:/opt/apps/ - .pgpass:/root/.pgpass - .pg_service.conf:/root/.pg_service.conf entrypoint: "./entrypoint.sh" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres container_name: db environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - ${DB_PORT}:5432 volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: networks: django-tutorial: compose .env file DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 .pg_service.conf [DB] host=db user=postgres dbname=django_tutorial port=5432 .pgpass db:5432:postgres:postgres:postgres When docker-compose up -d is executed with the above configuration and python manage.py migrate is executed, the migration is performed no problems and the database is accessible. However, when I try to run the test as in python manage.py test polls, I get the following error. (The test is the same as the code in the link at the beginning of this article.) Do I need any additional configuration for the test DB? docker compose exec web python manage.py test polls  ✔  15:20:03  Found 1 test(s). Creating test database for alias 'default'... /usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py:323: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 318, in _nodb_cursor with super()._nodb_cursor() as cursor: File "/usr/local/lib/python3.9/contextlib.py", line 119, in __enter__ return next(self.gen) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 656, in _nodb_cursor with conn.cursor() as cursor: File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 284, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 260, in _cursor self.ensure_connection() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/apps/manage.py", line 22, in <module> main() File "/opt/apps/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 1000, in run_tests old_config = self.setup_databases( File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 898, in setup_databases return _setup_databases( File "/usr/local/lib/python3.9/site-packages/django/test/utils.py", line 220, in setup_databases connection.creation.create_test_db( File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 63, in create_test_db self._create_test_db(verbosity, autoclobber, keepdb) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 199, in _create_test_db with self._nodb_cursor() as cursor: File "/usr/local/lib/python3.9/contextlib.py", line 119, in __enter__ return next(self.gen) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 344, in _nodb_cursor with conn.cursor() as cursor: File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 284, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 260, in _cursor self.ensure_connection() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 224, in connect conn_params = self.get_connection_params() File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 162, in get_connection_params raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value. A: Using a service name for testing purposes is not supported at the moment. I suspect this is why python manage.py test does not work. See the ticket here https://code.djangoproject.com/ticket/33685 If that is the cause of your issue, python manage.py runserver should work. If you need to use tests, try the old config.
I use Django with PostgreSQL on docker compose, but django-test can't access database
I practice Writing your first Django app, part 5, it's django test section. And my environment is: Django 4.0 Python 3.9 Database PostgreSQL 14.2 Docker compose In addition, the connection to PostgreSQL is configured via .pg_service.conf and .pgpass. docker-compose.yml version: "3.9" services: web: build: context: . container_name: web restart: unless-stopped tty: true working_dir: /opt/apps volumes: - .:/opt/apps/ - .pgpass:/root/.pgpass - .pg_service.conf:/root/.pg_service.conf entrypoint: "./entrypoint.sh" command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" depends_on: - db db: image: postgres container_name: db environment: POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: ${DB_PASSWORD} ports: - ${DB_PORT}:5432 volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: networks: django-tutorial: compose .env file DB_USER=postgres DB_PASSWORD=postgres DB_HOST=db DB_PORT=5432 .pg_service.conf [DB] host=db user=postgres dbname=django_tutorial port=5432 .pgpass db:5432:postgres:postgres:postgres When docker-compose up -d is executed with the above configuration and python manage.py migrate is executed, the migration is performed no problems and the database is accessible. However, when I try to run the test as in python manage.py test polls, I get the following error. (The test is the same as the code in the link at the beginning of this article.) Do I need any additional configuration for the test DB? docker compose exec web python manage.py test polls  ✔  15:20:03  Found 1 test(s). Creating test database for alias 'default'... /usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py:323: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 318, in _nodb_cursor with super()._nodb_cursor() as cursor: File "/usr/local/lib/python3.9/contextlib.py", line 119, in __enter__ return next(self.gen) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 656, in _nodb_cursor with conn.cursor() as cursor: File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 284, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 260, in _cursor self.ensure_connection() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/apps/manage.py", line 22, in <module> main() File "/opt/apps/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 1000, in run_tests old_config = self.setup_databases( File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 898, in setup_databases return _setup_databases( File "/usr/local/lib/python3.9/site-packages/django/test/utils.py", line 220, in setup_databases connection.creation.create_test_db( File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 63, in create_test_db self._create_test_db(verbosity, autoclobber, keepdb) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 199, in _create_test_db with self._nodb_cursor() as cursor: File "/usr/local/lib/python3.9/contextlib.py", line 119, in __enter__ return next(self.gen) File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 344, in _nodb_cursor with conn.cursor() as cursor: File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 284, in cursor return self._cursor() File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 260, in _cursor self.ensure_connection() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 244, in ensure_connection self.connect() File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 224, in connect conn_params = self.get_connection_params() File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 162, in get_connection_params raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value.
[ "Using a service name for testing purposes is not supported at the moment.\nI suspect this is why python manage.py test does not work.\nSee the ticket here https://code.djangoproject.com/ticket/33685\nIf that is the cause of your issue, python manage.py runserver should work.\nIf you need to use tests, try the old config.\n" ]
[ 0 ]
[]
[]
[ "django", "docker", "postgresql", "python", "python_3.x" ]
stackoverflow_0072122960_django_docker_postgresql_python_python_3.x.txt
Q: Problem with type inference of awaited function return type in TypeScript and PhpStorm I have the following piece of code class Foo { bar: { baz: number } } class Conflict { bar: { baz: string } } function foo() { return Promise.resolve(new Foo()) } async function problem() { const auto = await foo() const typed: Awaited<ReturnType<typeof foo>> = await foo() typed.bar.baz auto.bar.baz } You can see I defined two classes with almost the same structure, important is they have properties with same names. Then a defined a function foo that returns Promise that resolved to a Foo instance. Then I call it twice with await, once I let the returned type is deduced automatically, once I explicitly set the type to Awaited<ReturnType<typeof foo>> which should be exactly what await foo() returns. My problem is PhpStorm treats the two differently. If I want to jump to definition of auto.bar.baz it takes me correctly to definition of Foo.bar.baz. But when I want to jump to definition of typed.bar.baz it doesn't know where to jump and offers a choice to jump to all known methods of the name baz, in this case Foo.bar.baz or Conflict.bar.baz. My PhpStorm is 2022.2.4, no special plugins, just the bundled TSLint (222.4459.28), TypeScript 4.8.3 Is this some problem with the typings? Is the real type somehow different from the explicit one? Or could it just be a PhpStom issue? This is stripped version of something larger I am trying to build. I've been trying a lot of things and this is the MVE that I could track it down to. I just can't think of any reason why aren't the two treated the same? A: This is a problem with PhpStorm, it doesn't understand Awaited<T>type. Please vote for WEB-53046 to raise its priority and get notified on any progress with it
Problem with type inference of awaited function return type in TypeScript and PhpStorm
I have the following piece of code class Foo { bar: { baz: number } } class Conflict { bar: { baz: string } } function foo() { return Promise.resolve(new Foo()) } async function problem() { const auto = await foo() const typed: Awaited<ReturnType<typeof foo>> = await foo() typed.bar.baz auto.bar.baz } You can see I defined two classes with almost the same structure, important is they have properties with same names. Then a defined a function foo that returns Promise that resolved to a Foo instance. Then I call it twice with await, once I let the returned type is deduced automatically, once I explicitly set the type to Awaited<ReturnType<typeof foo>> which should be exactly what await foo() returns. My problem is PhpStorm treats the two differently. If I want to jump to definition of auto.bar.baz it takes me correctly to definition of Foo.bar.baz. But when I want to jump to definition of typed.bar.baz it doesn't know where to jump and offers a choice to jump to all known methods of the name baz, in this case Foo.bar.baz or Conflict.bar.baz. My PhpStorm is 2022.2.4, no special plugins, just the bundled TSLint (222.4459.28), TypeScript 4.8.3 Is this some problem with the typings? Is the real type somehow different from the explicit one? Or could it just be a PhpStom issue? This is stripped version of something larger I am trying to build. I've been trying a lot of things and this is the MVE that I could track it down to. I just can't think of any reason why aren't the two treated the same?
[ "This is a problem with PhpStorm, it doesn't understand Awaited<T>type. Please vote for WEB-53046 to raise its priority and get notified on any progress with it\n" ]
[ 0 ]
[]
[]
[ "phpstorm", "typescript", "webstorm" ]
stackoverflow_0074645932_phpstorm_typescript_webstorm.txt
Q: I dont want means in my pivot table. I want both data I had a big dataframe with training data: for each day and person the kind of training, and some data points per training. I pivot the table with this code trainingload = trainingload.pivot_table(index=('Date', 'About'), columns='NHV Training', values=['Duration', 'sRPE Cardio', 'sRPE Biomechanical']) It works fine for most data. But sometimes the same person had two the same kind of trainings on one day. In the new dataframe the values duration, sRPE Cardio and sRPE biomechancial are now added as means, while i would like to keep both as seperate rows. I could not find anything about this problem so I'm stuck, who can help me out? A: One solution would be to not use the pivot_table function and instead use the pivot function, which allows you to specify the aggregation function. Instead of using the default mean function, you can use the function that simply concatenates the values together, such as the sum function. Here is an example: trainingload = trainingload.pivot(index=('Date', 'About'), columns='NHV Training', values=['Duration', 'sRPE Cardio', 'sRPE Biomechanical'], aggfunc=sum) This will result in the values for Duration, sRPE Cardio, and sRPE Biomechanical being concatenated together for each person and each day, rather than being averaged.
I dont want means in my pivot table. I want both data
I had a big dataframe with training data: for each day and person the kind of training, and some data points per training. I pivot the table with this code trainingload = trainingload.pivot_table(index=('Date', 'About'), columns='NHV Training', values=['Duration', 'sRPE Cardio', 'sRPE Biomechanical']) It works fine for most data. But sometimes the same person had two the same kind of trainings on one day. In the new dataframe the values duration, sRPE Cardio and sRPE biomechancial are now added as means, while i would like to keep both as seperate rows. I could not find anything about this problem so I'm stuck, who can help me out?
[ "One solution would be to not use the pivot_table function and instead use the pivot function, which allows you to specify the aggregation function. Instead of using the default mean function, you can use the function that simply concatenates the values together, such as the sum function.\nHere is an example:\ntrainingload = trainingload.pivot(index=('Date', 'About'), columns='NHV Training', values=['Duration', 'sRPE Cardio', 'sRPE Biomechanical'], aggfunc=sum)\n\nThis will result in the values for Duration, sRPE Cardio, and sRPE Biomechanical being concatenated together for each person and each day, rather than being averaged.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pivot", "python" ]
stackoverflow_0074657259_dataframe_pivot_python.txt
Q: groovy:combine jsons based on a value is there a simple way to combine two jsons based on the value. In the MainJson , i have an element "downloads" which has multiple id's seprated by a comma. So based on the downloadsID from MainJson,values from SecondJson needs to be appended MainJson: ` { "ProductMaster": [ { "SEODescription": "32742, 396660", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172658,1172659", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": "1172663,1172669,1172670", "highlights": "396658", "id": "1172641", "isNew": "1", "isSparePart": "1172663,1172669,1172670", "name": "Product 1", "productItems": "A4F0630502M1,A1Z1100041M1,A1G1800061M1,A4D1251181E1,105500450100", "relatedProducts": "1172658,1172659", "shortCode": "PROD1", "shortDescription": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", "videos": "396657,396659" }, { "SEODescription": "", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172641", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": "1172663", "highlights": "396657", "id": "1172658", "isNew": "1", "isSparePart": "1172663", "name": "Product 2", "productItems": "613831,613823,613852", "relatedProducts": "1172641", "shortCode": "PROD2", "shortDescription": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", "videos": "396659" } ] } ` SecondJson ` { "downloads": [ { "actualHeight": "1146", "actualWidth": "1146", "categories": "1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396657", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_2.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172669", "mimeType": "IMAGE/JPEG", "name": "Download 2" }, { "actualHeight": "1980", "actualWidth": "1980", "categories": "1172666", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396658", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_1.JPG", "fileSize": "201965", "fileType": "JPG", "id": "1172663", "mimeType": "IMAGE/JPEG", "name": "Download 1" }, { "actualHeight": "2875", "actualWidth": "2875", "categories": "1172666,1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_86356", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/_DEFAULT_UPLOAD_BUCKET/0205800.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172670", "mimeType": "IMAGE/JPEG", "name": "Download 3" } ] } ` Expected Result: ` { "ProductMaster": [ { "SEODescription": "32742, 396660", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172658,1172659", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": [ { "actualHeight": "1146", "actualWidth": "1146", "categories": "1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396657", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_2.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172669", "mimeType": "IMAGE/JPEG", "name": "Download 2" }, { "actualHeight": "1980", "actualWidth": "1980", "categories": "1172666", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396658", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_1.JPG", "fileSize": "201965", "fileType": "JPG", "id": "1172663", "mimeType": "IMAGE/JPEG", "name": "Download 1" }, { "actualHeight": "2875", "actualWidth": "2875", "categories": "1172666,1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_86356", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/_DEFAULT_UPLOAD_BUCKET/0205800.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172670", "mimeType": "IMAGE/JPEG", "name": "Download 3" } ], "highlights": "396658", "id": "1172641", "isNew": "1", "isSparePart": "1172663,1172669,1172670", "name": "Product 1", "productItems": "A4F0630502M1,A1Z1100041M1,A1G1800061M1,A4D1251181E1,105500450100", "relatedProducts": "1172658,1172659", "shortCode": "PROD1", "shortDescription": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", "videos": "396657,396659" }, { "SEODescription": "", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172641", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": [ { "actualHeight": "2875", "actualWidth": "2875", "categories": "1172666,1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_86356", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/_DEFAULT_UPLOAD_BUCKET/0205800.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172670", "mimeType": "IMAGE/JPEG", "name": "Download 3" } ], "highlights": "396657", "id": "1172658", "isNew": "1", "isSparePart": "1172663", "name": "Product 2", "productItems": "613831,613823,613852", "relatedProducts": "1172641", "shortCode": "PROD2", "videos": "396659" } ] } ` is there any groovyfunction which can do the lookup and combine the Jsons A: The code can look roughly as: mainJson.ProductMaster.each{ master -> List<String> dlIds = master.downloads.split( ',' ) master.downloads = secondJson.downloads.findAll{ it.id in dlIds } }
groovy:combine jsons based on a value
is there a simple way to combine two jsons based on the value. In the MainJson , i have an element "downloads" which has multiple id's seprated by a comma. So based on the downloadsID from MainJson,values from SecondJson needs to be appended MainJson: ` { "ProductMaster": [ { "SEODescription": "32742, 396660", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172658,1172659", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": "1172663,1172669,1172670", "highlights": "396658", "id": "1172641", "isNew": "1", "isSparePart": "1172663,1172669,1172670", "name": "Product 1", "productItems": "A4F0630502M1,A1Z1100041M1,A1G1800061M1,A4D1251181E1,105500450100", "relatedProducts": "1172658,1172659", "shortCode": "PROD1", "shortDescription": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", "videos": "396657,396659" }, { "SEODescription": "", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172641", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": "1172663", "highlights": "396657", "id": "1172658", "isNew": "1", "isSparePart": "1172663", "name": "Product 2", "productItems": "613831,613823,613852", "relatedProducts": "1172641", "shortCode": "PROD2", "shortDescription": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", "videos": "396659" } ] } ` SecondJson ` { "downloads": [ { "actualHeight": "1146", "actualWidth": "1146", "categories": "1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396657", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_2.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172669", "mimeType": "IMAGE/JPEG", "name": "Download 2" }, { "actualHeight": "1980", "actualWidth": "1980", "categories": "1172666", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396658", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_1.JPG", "fileSize": "201965", "fileType": "JPG", "id": "1172663", "mimeType": "IMAGE/JPEG", "name": "Download 1" }, { "actualHeight": "2875", "actualWidth": "2875", "categories": "1172666,1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_86356", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/_DEFAULT_UPLOAD_BUCKET/0205800.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172670", "mimeType": "IMAGE/JPEG", "name": "Download 3" } ] } ` Expected Result: ` { "ProductMaster": [ { "SEODescription": "32742, 396660", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172658,1172659", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": [ { "actualHeight": "1146", "actualWidth": "1146", "categories": "1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396657", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_2.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172669", "mimeType": "IMAGE/JPEG", "name": "Download 2" }, { "actualHeight": "1980", "actualWidth": "1980", "categories": "1172666", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_396658", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/PIM-NEW/IMAGE_1.JPG", "fileSize": "201965", "fileType": "JPG", "id": "1172663", "mimeType": "IMAGE/JPEG", "name": "Download 1" }, { "actualHeight": "2875", "actualWidth": "2875", "categories": "1172666,1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_86356", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/_DEFAULT_UPLOAD_BUCKET/0205800.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172670", "mimeType": "IMAGE/JPEG", "name": "Download 3" } ], "highlights": "396658", "id": "1172641", "isNew": "1", "isSparePart": "1172663,1172669,1172670", "name": "Product 1", "productItems": "A4F0630502M1,A1Z1100041M1,A1G1800061M1,A4D1251181E1,105500450100", "relatedProducts": "1172658,1172659", "shortCode": "PROD1", "shortDescription": "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", "videos": "396657,396659" }, { "SEODescription": "", "SEOTitle": "PRODUCT 1 SEO TITLE", "accesoires": "1172641", "applications": "1172647,1172648,1172649", "contactPerson": "1172661", "downloads": [ { "actualHeight": "2875", "actualWidth": "2875", "categories": "1172666,1172668", "deepLink": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/ASSET/DEEPLINK/IMAGE_86356", "effectiveUrl": "HTTPS://ALIAXIS-WEBSITES.DDEV.SITE/_DEFAULT_UPLOAD_BUCKET/0205800.JPG", "fileSize": "0", "fileType": "JPG", "id": "1172670", "mimeType": "IMAGE/JPEG", "name": "Download 3" } ], "highlights": "396657", "id": "1172658", "isNew": "1", "isSparePart": "1172663", "name": "Product 2", "productItems": "613831,613823,613852", "relatedProducts": "1172641", "shortCode": "PROD2", "videos": "396659" } ] } ` is there any groovyfunction which can do the lookup and combine the Jsons
[ "The code can look roughly as:\nmainJson.ProductMaster.each{ master ->\n List<String> dlIds = master.downloads.split( ',' )\n master.downloads = secondJson.downloads.findAll{ it.id in dlIds }\n} \n\n" ]
[ 0 ]
[]
[]
[ "groovy" ]
stackoverflow_0074648986_groovy.txt
Q: Match case statement with multiple 'or' conditions in each case Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists. a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] Then I want to check whether x is in each list. Something like that (of course this is a Syntax Error but I hope you get the point). match x: case in a: return "132" case in b: return "564" case in c: return "798" This can be easy with an if-else scenario. Nonetheless, focusing on the match-case, if one has many lists. And big lists, it would be a mundane task to write them like that: match x: case 1 | 2 | 3: return "132" case 4 | 5 | 6: return "564" case 7 | 8 | 9: return "762" Is there an easy to way to check for multiple conditions for each case, without having to write them down? I checked for duplicates, but I couldn't find them, I hope I don't miss something. Please be kind and let me know if there is a duplicate question. A: As it seems cases accept a "guard" clause starting with Python 3.10, which you can use for this purpose: match x: case w if w in a: # this was the "case in a" in the question case w if w in b: # this was the "case in b" in the question ... the w here actually captures the value of x, part of the syntax here too, but it's more useful in some other fancy cases listed on the linked whatsnew page.
Match case statement with multiple 'or' conditions in each case
Is there a way to assess whether a case statement variable is inside a particular list? Consider the following scenario. We have three lists. a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] Then I want to check whether x is in each list. Something like that (of course this is a Syntax Error but I hope you get the point). match x: case in a: return "132" case in b: return "564" case in c: return "798" This can be easy with an if-else scenario. Nonetheless, focusing on the match-case, if one has many lists. And big lists, it would be a mundane task to write them like that: match x: case 1 | 2 | 3: return "132" case 4 | 5 | 6: return "564" case 7 | 8 | 9: return "762" Is there an easy to way to check for multiple conditions for each case, without having to write them down? I checked for duplicates, but I couldn't find them, I hope I don't miss something. Please be kind and let me know if there is a duplicate question.
[ "As it seems cases accept a \"guard\" clause starting with Python 3.10, which you can use for this purpose:\nmatch x:\n case w if w in a:\n # this was the \"case in a\" in the question\n case w if w in b:\n # this was the \"case in b\" in the question\n ...\n\nthe w here actually captures the value of x, part of the syntax here too, but it's more useful in some other fancy cases listed on the linked whatsnew page.\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074655787_python_python_3.x.txt