content
stringlengths
86
88.9k
title
stringlengths
0
150
question
stringlengths
1
35.8k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
30
130
Q: Django - migrate command not using latest migrations file I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_name ./manage.py migrate --run-syncdb Also, I checked the dbshell, and there is a table already created for the model which is part of migrations file 5. A: Simple thing, because you didn't use migration file value while doing makemigrations. And migration file value is 0005. You must specify that value while doing makemigrations. Use these three commands for migrations: python manage.py makemigrations appname python manage.py sqlmigrate appname 0005 #specified that migration file 5 value here python manage.py migrate Now migrations will apply on that migration file 5 using its value 0005 A: I ended up deleting the migration file 3 which was getting picked up by django and add the operations of migration file 3 to inital file. Then when I ran migrate <app_name>, it picked up the last file (file 5). I did have to resolve some conflicts between file 3 and preceding files though
Django - migrate command not using latest migrations file
I have 5 migration files created. But when I run ./manage.py migrate it always tries to apply the migrations file "3". Even though the latest one is file 5. How can I fix this issue? I have tried: ./manage.py makemigrations app_name ./manage.py migrate app_name ./manage.py migrate --run-syncdb Also, I checked the dbshell, and there is a table already created for the model which is part of migrations file 5.
[ "Simple thing, because you didn't use migration file value while doing makemigrations. And migration file value is 0005. You must specify that value while doing makemigrations.\nUse these three commands for migrations:\npython manage.py makemigrations appname\n\npython manage.py sqlmigrate appname 0005 #specified that migration file 5 value here\n\npython manage.py migrate\n\nNow migrations will apply on that migration file 5 using its value 0005\n", "I ended up deleting the migration file 3 which was getting picked up by django and add the operations of migration file 3 to inital file.\nThen when I ran migrate <app_name>, it picked up the last file (file 5). I did have to resolve some conflicts between file 3 and preceding files though\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_migrations", "python" ]
stackoverflow_0074561280_django_django_migrations_python.txt
Q: AWS S3 bucket 403 I'm trying to host my angular app. But after I make my bucket publicly accessible and enable static website hosting, I still get 403 when I try to access it. It seems like something is wrong with the bucket policy, but I'm not sure where it is wrong. Please give me any advice. Thanks. { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::[my-bucket-name]" } ] } A: Security Advice: The above bucket policy is allowing anyone in the world to do anything with your bucket, including uploading files, download files, deleting files and deleting the bucket itself. Never grant s3:* permissions in a bucket policy. (Well, it has an error, detailed below, that prevents some of these operations, but the warning still stands.) As to your 403 error, some operations in Amazon S3 apply to the bucket itself and some operations apply to objects. For example, listing the contents of a bucket requires permissions on the bucket itself: "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::[my-bucket-name]" Operations on objects within the bucket require permission at the object level: "Action": "s3:GetObject", "Resource": "arn:aws:s3:::[my-bucket-name]/*" The /* at the end grants permission to any object within the bucket. So, if you wish to make the bucket "public" such that anyone can read/download an object in the bucket if they know the name of the object, you could use this policy: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::[my-bucket-name]/*" } ] }
AWS S3 bucket 403
I'm trying to host my angular app. But after I make my bucket publicly accessible and enable static website hosting, I still get 403 when I try to access it. It seems like something is wrong with the bucket policy, but I'm not sure where it is wrong. Please give me any advice. Thanks. { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::[my-bucket-name]" } ] }
[ "Security Advice: The above bucket policy is allowing anyone in the world to do anything with your bucket, including uploading files, download files, deleting files and deleting the bucket itself. Never grant s3:* permissions in a bucket policy. (Well, it has an error, detailed below, that prevents some of these operations, but the warning still stands.)\nAs to your 403 error, some operations in Amazon S3 apply to the bucket itself and some operations apply to objects.\nFor example, listing the contents of a bucket requires permissions on the bucket itself:\n \"Action\": \"s3:ListBucket\",\n \"Resource\": \"arn:aws:s3:::[my-bucket-name]\"\n\nOperations on objects within the bucket require permission at the object level:\n \"Action\": \"s3:GetObject\",\n \"Resource\": \"arn:aws:s3:::[my-bucket-name]/*\"\n\nThe /* at the end grants permission to any object within the bucket.\nSo, if you wish to make the bucket \"public\" such that anyone can read/download an object in the bucket if they know the name of the object, you could use this policy:\n{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Effect\": \"Allow\",\n \"Principal\": \"*\",\n \"Action\": \"s3:GetObject\",\n \"Resource\": \"arn:aws:s3:::[my-bucket-name]/*\"\n }\n ]\n}\n\n" ]
[ 1 ]
[]
[]
[ "amazon_web_services", "angular" ]
stackoverflow_0074673788_amazon_web_services_angular.txt
Q: Why in SQL NULL can't match with NULL? I'm new to SQL concepts, while studying NULL expression I wonder why NULL can't match with NULL can anyone tell me a real world example to simply this concept? A: Rule : Not even a NULL can be equal to NULL. A Non-Technical aspect If you ask two girls, how old they are? may be you would hear them to refuse to answer your question, Both girls are giving you NULL as age and this doesn't mean both have similar age. So there is nothing can be equal to null. A: NULL indicates an absence of a value. The designers of SQL decided that it made sense that, when asked whether A (for which we do not know its value) and B (for which we do not know its value) are equal, the answer must be UNKNOWN - they might be equal, they might not be. We do not have adequate information to decide either way. You might want to read up on Three valued logic - the possible results of any comparison in SQL are TRUE, FALSE and UNKNOWN (mysql treats UNKNOWN and NULL as synonymous. Not all RDBMSs do) A: NULL is an unknown value. Therefore it makes little sense to judge NULL == NULL. That's like asking "is this unknown value equal to that unknown value" - no clue.. See why is null not equal to null false for a possibly better explaination A: NULL is the absence of data in a field. You can check NULL values with IS NULL See IS NULL mysql> SELECT NULL IS NULL; +--------------+ | NULL IS NULL | +--------------+ | 1 | +--------------+ 1 row in set (0.00 sec) A: If you need to make a comparison where NULL does indeed equal NULL, you can use a pair of coalesce methods with a special default value. The easiest example is on a nullable string column. coalesce(MiddleName,'')=coalesce(@MiddleName,'') This comparison returns true if @MiddleName variable has a null value and the MiddleName column also has a null value. Of course, it also matches empty strings too. If that is an issue, you could change the special value to something silly, like coalesce(MiddleName,'<NULL_DEFAULT>')=coalesce(@MiddleName,'<NULL_DEFAULT>') A: You cannot use = for NULL instead you can use IS NULL http://www.w3schools.com/sql/sql_null_values.asp A: Please folllow the link The NULL value is never true in comparison to any other value, even NULL. To check we can use Is Null or Not Null operators .. Document Correct me if 'm wrong A: In SQL the WHERE clause only includes the value if the result of the expression is equal to TRUE. (This is not the same as "if the result of the expression is not FALSE") Any binary operation in SQL that has NULL on one side evaluates to NULL (think of NULL as being a synonym for unknown) so Select ... Where null = null Select ... Where field = null Select ... Where null = field Will all return no rows as in each case the where class evaluates to NULL which is not TRUE A: Actually NULL means UNKNOWN value So how we compare two UNKNOWN values. A: In addition to using IS NULL, another way to match NULL in SQL Server, is the function ISNULL, https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql SELECT * FROM TABLE_A t1 INNER JOIN TABLE_B t2 ON ISNULL(t1.somecol, somevalue) = ISNULL(t2.somecol, somevalue) where somevalue could be 'NULL' or 0 or whatever.
Why in SQL NULL can't match with NULL?
I'm new to SQL concepts, while studying NULL expression I wonder why NULL can't match with NULL can anyone tell me a real world example to simply this concept?
[ "Rule : Not even a NULL can be equal to NULL. \nA Non-Technical aspect \nIf you ask two girls, how old they are? may be you would hear them to refuse to answer your question,\n Both girls are giving you NULL as age and this doesn't mean both have similar age.\n So there is nothing can be equal to null. \n", "NULL indicates an absence of a value. The designers of SQL decided that it made sense that, when asked whether A (for which we do not know its value) and B (for which we do not know its value) are equal, the answer must be UNKNOWN - they might be equal, they might not be. We do not have adequate information to decide either way.\nYou might want to read up on Three valued logic - the possible results of any comparison in SQL are TRUE, FALSE and UNKNOWN (mysql treats UNKNOWN and NULL as synonymous. Not all RDBMSs do)\n", "NULL is an unknown value. Therefore it makes little sense to judge NULL == NULL. That's like asking \"is this unknown value equal to that unknown value\" - no clue..\nSee why is null not equal to null false for a possibly better explaination\n", "NULL is the absence of data in a field.\nYou can check NULL values with IS NULL\nSee IS NULL\nmysql> SELECT NULL IS NULL;\n+--------------+\n| NULL IS NULL |\n+--------------+\n| 1 |\n+--------------+\n\n1 row in set (0.00 sec)\n\n", "If you need to make a comparison where NULL does indeed equal NULL, you can use a pair of coalesce methods with a special default value. The easiest example is on a nullable string column. \ncoalesce(MiddleName,'')=coalesce(@MiddleName,'')\n\nThis comparison returns true if @MiddleName variable has a null value and the MiddleName column also has a null value. Of course, it also matches empty strings too. If that is an issue, you could change the special value to something silly, like\ncoalesce(MiddleName,'<NULL_DEFAULT>')=coalesce(@MiddleName,'<NULL_DEFAULT>')\n\n", "You cannot use = for NULL instead you can use IS NULL\nhttp://www.w3schools.com/sql/sql_null_values.asp \n", "Please folllow the link\nThe NULL value is never true in comparison to any other value, even NULL.\nTo check we can use \nIs Null or Not Null operators ..\n\nDocument\nCorrect me if 'm wrong\n", "In SQL the WHERE clause only includes the value if the result of the expression is equal to TRUE. (This is not the same as \"if the result of the expression is not FALSE\")\nAny binary operation in SQL that has NULL on one side evaluates to NULL (think of NULL as being a synonym for unknown)\nso \nSelect ... Where null = null\n\nSelect ... Where field = null\n\nSelect ... Where null = field\n\nWill all return no rows as in each case the where class evaluates to NULL which is not TRUE\n", "Actually NULL means UNKNOWN value So how we compare two UNKNOWN values.\n", "In addition to using IS NULL, another way to match NULL in SQL Server, is the function ISNULL, https://learn.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql\nSELECT * \nFROM TABLE_A t1\nINNER JOIN TABLE_B t2 ON ISNULL(t1.somecol, somevalue) = ISNULL(t2.somecol, somevalue)\n\nwhere somevalue could be 'NULL' or 0 or whatever.\n" ]
[ 55, 17, 4, 4, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "mysql", "null", "oracle", "sql", "sql_server" ]
stackoverflow_0012853944_mysql_null_oracle_sql_sql_server.txt
Q: Unable to use vscode debugger in a Express js with typscript project Here is my package.json file ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "concurrently \"yarn tsc --watch\" \"yarn tsc-alias --watch\" \"nodemon -q dist/index.js\"" }, "author": "", "license": "ISC", "dependencies": { "dotenv": "^16.0.3", "express": "^4.18.2", "mongoose": "^6.7.5" }, "devDependencies": { "@types/express": "^4.17.14", "@types/mongoose": "^5.11.97", "@types/node": "^18.11.10", "concurrently": "^7.6.0", "nodemon": "^2.0.20", "tsc-alias": "^1.8.1", "typescript": "^4.9.3" } } ` I have tried many ways in launch.json ` { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Attach", "port": 1234, "request": "attach", "skipFiles": [ "<node_internals>/**" ], "type": "node" }, { "name": "Launch Chrome with Debugger", "port": 7999, "request": "launch", "type": "chrome", "webRoot": "${workspaceFolder}/static", }, { "name": "Nodemon: Attach Express.js + TypeScript 2", "type": "node", "request": "attach", "port": 9229, "restart": true, "protocol": "inspector", "cwd": "${workspaceFolder}/backend" } ] } ` Only "Nodemon: Attach Express.js + TypeScript" was working (for this i have to add "--inspect-brk=0.0.0.0:9229" in package.json after where nodemon writter), but it is catching breakpoint of output compiled "js" files not source "ts" files. (and i have to add. A: Just add this to your tsconfig file: "compilerOptions": { "sourceMap": true } It will map compiled javascript back to typescript for debugging purposes, but don't forget to turn it off (maybe having tsconfig.prod file) when you will build your production bundle, because source maps will increase your bundle size
Unable to use vscode debugger in a Express js with typscript project
Here is my package.json file ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "concurrently \"yarn tsc --watch\" \"yarn tsc-alias --watch\" \"nodemon -q dist/index.js\"" }, "author": "", "license": "ISC", "dependencies": { "dotenv": "^16.0.3", "express": "^4.18.2", "mongoose": "^6.7.5" }, "devDependencies": { "@types/express": "^4.17.14", "@types/mongoose": "^5.11.97", "@types/node": "^18.11.10", "concurrently": "^7.6.0", "nodemon": "^2.0.20", "tsc-alias": "^1.8.1", "typescript": "^4.9.3" } } ` I have tried many ways in launch.json ` { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Attach", "port": 1234, "request": "attach", "skipFiles": [ "<node_internals>/**" ], "type": "node" }, { "name": "Launch Chrome with Debugger", "port": 7999, "request": "launch", "type": "chrome", "webRoot": "${workspaceFolder}/static", }, { "name": "Nodemon: Attach Express.js + TypeScript 2", "type": "node", "request": "attach", "port": 9229, "restart": true, "protocol": "inspector", "cwd": "${workspaceFolder}/backend" } ] } ` Only "Nodemon: Attach Express.js + TypeScript" was working (for this i have to add "--inspect-brk=0.0.0.0:9229" in package.json after where nodemon writter), but it is catching breakpoint of output compiled "js" files not source "ts" files. (and i have to add.
[ "Just add this to your tsconfig file:\n\"compilerOptions\": {\n \"sourceMap\": true\n}\n\nIt will map compiled javascript back to typescript for debugging purposes, but don't forget to turn it off (maybe having tsconfig.prod file) when you will build your production bundle, because source maps will increase your bundle size\n" ]
[ 0 ]
[]
[]
[ "debugging", "express", "nodemon", "typescript", "vscode_debugger" ]
stackoverflow_0074666213_debugging_express_nodemon_typescript_vscode_debugger.txt
Q: Discord event on_member_join not working when a member joins the guild I have an event in my discord bot that sends an embed to welcome a member when the join the guild. No errors are produced but the event does not seem to work for me. Here is the code for the event: @bot.event async def on_member_join(member): """ The code in this event is executed every time a member joins the server """ embed = discord.embed(title=f'Welcome to {member.guild.name}', description=f'{member.mention}, welcome to the server! \nMake sure to checkout the rules first. Enjoy your stay <3', color=0x0061ff) if member.guild.icon is not None: embed.set_thumbnail( url=member.guild.icon.url ) await bot.get_channel(1047615507995562014).send(embed=embed) I'm also using the following intents as well and have enabled them properly so I know that is not the issue with my code. intents = discord.Intents.all() intents.members = True A: The reason you're getting an Error, is because the e in discord.embed is lowercase embed = discord.embed(title=f'Welcome to {member.guild.name}', description=f'{member.mention}, welcome to the server! \nMake sure to checkout the rules first. Enjoy your stay <3', color=0x0061ff) Correct version would, obviously, be: embed = discord.Embed(title=f'Welcome to {member.guild.name}', description=f'{member.mention}, welcome to the server! \nMake sure to checkout the rules first. Enjoy your stay <3', color=0x0061ff) A: your bot is probably missing a privileged intent,go to your bot on the discord developer portal, then turn the server members intent on
Discord event on_member_join not working when a member joins the guild
I have an event in my discord bot that sends an embed to welcome a member when the join the guild. No errors are produced but the event does not seem to work for me. Here is the code for the event: @bot.event async def on_member_join(member): """ The code in this event is executed every time a member joins the server """ embed = discord.embed(title=f'Welcome to {member.guild.name}', description=f'{member.mention}, welcome to the server! \nMake sure to checkout the rules first. Enjoy your stay <3', color=0x0061ff) if member.guild.icon is not None: embed.set_thumbnail( url=member.guild.icon.url ) await bot.get_channel(1047615507995562014).send(embed=embed) I'm also using the following intents as well and have enabled them properly so I know that is not the issue with my code. intents = discord.Intents.all() intents.members = True
[ "The reason you're getting an Error, is because the e in discord.embed is lowercase\nembed = discord.embed(title=f'Welcome to {member.guild.name}',\n description=f'{member.mention}, welcome to the server! \\nMake sure to checkout the rules first. Enjoy your stay <3',\n color=0x0061ff)\n\nCorrect version would, obviously, be:\nembed = discord.Embed(title=f'Welcome to {member.guild.name}',\n description=f'{member.mention}, welcome to the server! \\nMake sure to checkout the rules first. Enjoy your stay <3',\n color=0x0061ff)\n\n", "your bot is probably missing a privileged intent,go to your bot on the discord developer portal, then turn the server members intent on\n" ]
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074663887_discord_discord.py_python.txt
Q: How to make website responsive in mobile screen I am working on a Bootstrap project, In my project I am trying to make my website responsive to Mobile screen also but in Mobile screen responsive is not coming. I tried a lot to make a website As responsive. So please help me to achieve this. This is Index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link rel="stylesheet" href="main.css"> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400&display=swap" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="col-12 bg-danger"> <div> <ol> <li class="heading-li">Managing cookies <p class="mt-2 paragraph">9.1. Most browsers allow you to refuse to accept cookies and to delete cookies. The methods for doing so vary from browser to browser, and from version to version. You can however obtain up-to-date information about blocking and deleting cookies via these links: (i) https://support.google.com/chrome/answer/95647?hl=en (Chrome); (ii)https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences (Firefox); (iii) http://www.opera.com/help/tutorials/security/cookies/ (Opera); (iv)https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies (Internet Explorer); (v) https://support.apple.com/kb/PH21411 (Safari); and (vi)https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy (Edge). 9.2. Blocking all cookies will have a negative impact upon the usability of many websites. 9.3. If you block cookies, you will not be able to use all the features on our website. </p> </li> </ol> </div> </div> </div> </div> </body> </html> This is main.css .heading-li { font-size: 16px; font-weight: 600; } .paragraph { font-size: 16px; font-weight: 400 !important; font-family: 'Open Sans', sans-serif; } A: I checked the output of your code. It's responsive. I suggest you read about the concept. It seems you do not know what the term "responsive" means. Simply, it means there is no horizontal scroll bar when viewed in any screen width, mainly, a laptop, a tablet and a mobile phone and bigger and smaller. For visual and conceptual explanations, see: https://www.w3schools.com/html/html_responsive.asp A: To make it responsive use @media only screen max-width(600px) and set your all elements size according to this screen size, but i suggest here don't use px, use here rem value because it sets automatically according to your screen.
How to make website responsive in mobile screen
I am working on a Bootstrap project, In my project I am trying to make my website responsive to Mobile screen also but in Mobile screen responsive is not coming. I tried a lot to make a website As responsive. So please help me to achieve this. This is Index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link rel="stylesheet" href="main.css"> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400&display=swap" rel="stylesheet"> </head> <body> <div class="container"> <div class="row"> <div class="col-12 bg-danger"> <div> <ol> <li class="heading-li">Managing cookies <p class="mt-2 paragraph">9.1. Most browsers allow you to refuse to accept cookies and to delete cookies. The methods for doing so vary from browser to browser, and from version to version. You can however obtain up-to-date information about blocking and deleting cookies via these links: (i) https://support.google.com/chrome/answer/95647?hl=en (Chrome); (ii)https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences (Firefox); (iii) http://www.opera.com/help/tutorials/security/cookies/ (Opera); (iv)https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies (Internet Explorer); (v) https://support.apple.com/kb/PH21411 (Safari); and (vi)https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy (Edge). 9.2. Blocking all cookies will have a negative impact upon the usability of many websites. 9.3. If you block cookies, you will not be able to use all the features on our website. </p> </li> </ol> </div> </div> </div> </div> </body> </html> This is main.css .heading-li { font-size: 16px; font-weight: 600; } .paragraph { font-size: 16px; font-weight: 400 !important; font-family: 'Open Sans', sans-serif; }
[ "I checked the output of your code. It's responsive.\nI suggest you read about the concept. It seems you do not know what the term \"responsive\" means. \nSimply, it means there is no horizontal scroll bar when viewed in any screen width, mainly, a laptop, a tablet and a mobile phone and bigger and smaller.\nFor visual and conceptual explanations, see:\nhttps://www.w3schools.com/html/html_responsive.asp \n", "To make it responsive use @media only screen max-width(600px)\nand set your all elements size according to this screen size, but i suggest here don't use px, use here rem value because it sets automatically according to your screen.\n" ]
[ 1, 0 ]
[]
[]
[ "bootstrap_4" ]
stackoverflow_0061691025_bootstrap_4.txt
Q: How do I fix Memory Exception error on unity? I'm trying 3d model conversion on untiy and I'm using VRM0, everything seems to go just fine until I have to use it and export the 3d model into a file. After not responding for like 5 minutes,an error pops up saying that there's not enough memory. And I'm not sure if it's my old laptop not handling Unity, or if I'm doing something wrong. If anyone could explain, or help, would be appreciated. I tried to lower the quality of the project, but everytime it reset back to "Ultra". Also when I click on the error it takes me to visual studio, so maybe something wrong with the coding? A: This could be caused by various factors, including the size and complexity of your 3D model, the amount of memory available on your computer, and any other programs or processes running on your computer simultaneously. One thing you can try to help address this issue is to lower the quality settings for your project in Unity. You can do this by going to Edit > Project Settings > Quality and selecting a lower quality level, then ensuring this option stays on said quality since you mentioned it gets reset. This will reduce the amount of memory your project uses, which may help prevent the out-of-memory error from occurring. Another thing you can try is to close any other programs or processes that may be using up memory on your computer. This will free up more memory for your 3D model conversion in Unity, which may help prevent the out-of-memory error from occurring. If these steps do not help, you may need to upgrade your computer or consider using a different 3D modelling tool better suited to the size and complexity of your 3D model.
How do I fix Memory Exception error on unity?
I'm trying 3d model conversion on untiy and I'm using VRM0, everything seems to go just fine until I have to use it and export the 3d model into a file. After not responding for like 5 minutes,an error pops up saying that there's not enough memory. And I'm not sure if it's my old laptop not handling Unity, or if I'm doing something wrong. If anyone could explain, or help, would be appreciated. I tried to lower the quality of the project, but everytime it reset back to "Ultra". Also when I click on the error it takes me to visual studio, so maybe something wrong with the coding?
[ "This could be caused by various factors, including the size and complexity of your 3D model, the amount of memory available on your computer, and any other programs or processes running on your computer simultaneously.\nOne thing you can try to help address this issue is to lower the quality settings for your project in Unity. You can do this by going to Edit > Project Settings > Quality and selecting a lower quality level, then ensuring this option stays on said quality since you mentioned it gets reset. This will reduce the amount of memory your project uses, which may help prevent the out-of-memory error from occurring.\nAnother thing you can try is to close any other programs or processes that may be using up memory on your computer. This will free up more memory for your 3D model conversion in Unity, which may help prevent the out-of-memory error from occurring.\nIf these steps do not help, you may need to upgrade your computer or consider using a different 3D modelling tool better suited to the size and complexity of your 3D model.\n" ]
[ 0 ]
[]
[]
[ "unity3d" ]
stackoverflow_0074654894_unity3d.txt
Q: How do i make this fluid player auto pause after its done playing I will like to make the fluid player auto pause after each video is done playing `<script src="https://cdn.fluidplayer.com/v3/current/fluidplayer.min.js"></script> <video id="video-id"><source src="video.mp4" type="video/mp4" /> <script> var myFP = fluidPlayer( 'video-id', { "layoutControls": { "controlBar": { "autoHideTimeout": 3, "animated": true, "autoHide": true }, "htmlOnPauseBlock": { "html": null, "height": null, "width": null }, "autoPlay": true, "mute": true, "allowTheatre": true, "playPauseAnimation": true, "playbackRateEnabled": true, "allowDownload": false, "loop": true, "playButtonShowing": true, "fillToContainer": true, "posterImage": "" }, "vastOptions": { "adList": \[ { "roll": "preRoll", "vastTag": "https://www.videosprofitnetwork.com/watch.xml?key=ddbbe516ba5a32d04f608af9bb011c1a", "adText": "" } \], "adCTAText": false, "adCTATextPosition": "" } }); </script></source></video>`u A: if you check the documentation you have multiple events available that you can hook to, to perform whatever action you desire https://docs.fluidplayer.com/docs/api/events/ in your example it could look somehting like this myFP.on('ended', function(){ myFP.pause();});
How do i make this fluid player auto pause after its done playing
I will like to make the fluid player auto pause after each video is done playing `<script src="https://cdn.fluidplayer.com/v3/current/fluidplayer.min.js"></script> <video id="video-id"><source src="video.mp4" type="video/mp4" /> <script> var myFP = fluidPlayer( 'video-id', { "layoutControls": { "controlBar": { "autoHideTimeout": 3, "animated": true, "autoHide": true }, "htmlOnPauseBlock": { "html": null, "height": null, "width": null }, "autoPlay": true, "mute": true, "allowTheatre": true, "playPauseAnimation": true, "playbackRateEnabled": true, "allowDownload": false, "loop": true, "playButtonShowing": true, "fillToContainer": true, "posterImage": "" }, "vastOptions": { "adList": \[ { "roll": "preRoll", "vastTag": "https://www.videosprofitnetwork.com/watch.xml?key=ddbbe516ba5a32d04f608af9bb011c1a", "adText": "" } \], "adCTAText": false, "adCTATextPosition": "" } }); </script></source></video>`u
[ "if you check the documentation you have multiple events available that you can hook to, to perform whatever action you desire\nhttps://docs.fluidplayer.com/docs/api/events/\nin your example it could look somehting like this\nmyFP.on('ended', function(){ myFP.pause();});\n\n" ]
[ 1 ]
[]
[]
[ "javascript" ]
stackoverflow_0074674840_javascript.txt
Q: How to use graphql-js to call APIs from the client code? I am developing an internal TypeScript library which needs to call a couple of GraphQL endpoints. The library is supposed be imported in front end projects, but it is not dependent on any specific framework (like angular or react). I would like to be able to use a GraphQL library for GraphQL calls. I checked Apollo, but it brings react with it (which I don't need). In the graphql-js documentation, it states that it can be used in browser, at the same time they only provide code samples for server-side code. So far, I am just making plain rest class, but I am interested in generating at least types automatically as it is inconvenient. Q: How to use graphql-js in the client code? Or is there any other way to call graphql endpoints without having to import Apollo with react? Any suggestion is appreciated. A: The Apollo client does not require react. The Apollo client documentation is very react-centric (for Javascript at least) but the client exposes an API which can be used without React. Even when building in react it can be useful to use, for example, client.query() to perform a query outside a component context. See also https://www.brianperry.dev/til/2021/using-apollo-without-react/ for how to import Apollo Client without react: import { ApolloClient, gql, InMemoryCache } from "@apollo/client/core"; A: GraphQL requests can be made over HTTP. Most servers follow the "GraphQL over HTTP" specification. How a request can be done using the POST HTTP method can be found in the documentation and quite a lengthy tutorial here. Here is a simple fetch example: await fetch('http://your.server.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: "...", variables: { "a": "..." }, }), }); For a much better experience and less boilerplate you could use graphql-request. import { request, gql } from 'graphql-request' const query = gql` { ... } ` await request('https://api.spacex.land/graphql/', query) I also like to pair the library with GraphQL Code Generator. You can either create a fully typed SDK or use the simpler typed document node to get typesafe query variables and results. For inspiration on the setup, you could use my repository. It is a bit old and needs some package upgrades, but I think the principles should be the same.
How to use graphql-js to call APIs from the client code?
I am developing an internal TypeScript library which needs to call a couple of GraphQL endpoints. The library is supposed be imported in front end projects, but it is not dependent on any specific framework (like angular or react). I would like to be able to use a GraphQL library for GraphQL calls. I checked Apollo, but it brings react with it (which I don't need). In the graphql-js documentation, it states that it can be used in browser, at the same time they only provide code samples for server-side code. So far, I am just making plain rest class, but I am interested in generating at least types automatically as it is inconvenient. Q: How to use graphql-js in the client code? Or is there any other way to call graphql endpoints without having to import Apollo with react? Any suggestion is appreciated.
[ "The Apollo client does not require react. The Apollo client documentation is very react-centric (for Javascript at least) but the client exposes an API which can be used without React. Even when building in react it can be useful to use, for example, client.query() to perform a query outside a component context.\nSee also https://www.brianperry.dev/til/2021/using-apollo-without-react/ for how to import Apollo Client without react:\nimport { ApolloClient, gql, InMemoryCache } from \"@apollo/client/core\";\n\n", "GraphQL requests can be made over HTTP. Most servers follow the \"GraphQL over HTTP\" specification. How a request can be done using the POST HTTP method can be found in the documentation and quite a lengthy tutorial here. Here is a simple fetch example:\nawait fetch('http://your.server.com/graphql', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n query: \"...\",\n variables: { \"a\": \"...\" },\n }),\n});\n\nFor a much better experience and less boilerplate you could use graphql-request.\nimport { request, gql } from 'graphql-request'\n\nconst query = gql`\n {\n ...\n }\n`\n\nawait request('https://api.spacex.land/graphql/', query)\n\nI also like to pair the library with GraphQL Code Generator. You can either create a fully typed SDK or use the simpler typed document node to get typesafe query variables and results.\nFor inspiration on the setup, you could use my repository. It is a bit old and needs some package upgrades, but I think the principles should be the same.\n" ]
[ 0, 0 ]
[]
[]
[ "graphql", "graphql_js", "javascript", "typescript" ]
stackoverflow_0074548261_graphql_graphql_js_javascript_typescript.txt
Q: How to put a JButton inside a JComboBox I would like to put a JButton inside a JComboBox. This button lets users browse for files. The file the user selects gets added to the JComboBox list. How do I do this? Do I use some kind of a Renderer? Thank you. EDIT: After reading more about ListCellRenderer I tried the following code: JComboBox comboBox = new JComboBox(new String[]{"", "Item1", "Item2"}); ComboBoxRenderer renderer = new ComboBoxRenderer(); comboBox.setRenderer(renderer); class ComboBoxRenderer implements ListCellRenderer { public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JButton jbutton = new JButton("Browse"); return jbutton; } } The problem with the above is that the Button "Browse" will be added 3 times and I want it to display only once and below it to display Item1 and Item2 as normal/regular combobox selection objects. A: I would avoid the JButton. It is perfectly possible to get the image of a JButton inside your combobox, but it will not behave itself as a button. You cannot click it, it never gets visually 'pressed' nor 'released', ... . In short, your combobox will contain an item which behaves unfamiliar to your users. The reason for this is that the components you return in the getListCellRendererComponent method are not contained in the JCombobox. They are only used as a stamp. That also explains why you can (and should) reuse the Component you return in that method, and not create new components the whole time. This is all explained in the JTable tutorial in the part about Renderers and Editors (explained for a JTable but valid for all other Swing components which use renderers and editors). If you really want an item in the combobox that allows to show a file chooser, I would opt for something similar to the following SSCCE: import javax.swing.JComboBox; import javax.swing.JFrame; import java.awt.EventQueue; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class ComboboxTest { public static void main( String[] args ) { EventQueue.invokeLater( new Runnable() { @Override public void run() { JFrame frame = new JFrame( "TestFrame" ); JComboBox<String> comboBox = new JComboBox<>(new String[]{"Item1", "Item2"}); final String browse = "<<BROWSE>>"; comboBox.addItem( browse ); comboBox.addItemListener( new ItemListener() { @Override public void itemStateChanged( ItemEvent e ) { if ( e.getStateChange() == ItemEvent.SELECTED && browse.equals( e.getItem() ) ){ System.out.println("Show filechooser"); } } } ); frame.add( comboBox ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setVisible( true ); frame.pack(); } } ); } } A: After trying out many things I think I figured out the Answer, I am sure it will look very easy when you see it: JComboBox comboBox = new JComboBox(new String[]{"Item1", "Item2"}); ComboBoxRenderer renderer = new ComboBoxRenderer(); comboBox.setRenderer(renderer); comboBox.addItem("<<BROWSE>>"); class ComboBoxRenderer implements ListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value.equals("<<BROWSE>>")) { JButton btn = new JButton("Browse"); return btn; } else { JLabel lbl = new JLabel(value.toString()); lbl.setOpaque(true); return lbl; } } } You can now customize the button and labels any way you wish. A: Indeed, you will have to use a custom renderer as explained on http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer. A: Depending on where you want to put the search button, you could take a look at the xswingx Prompt/Buddy API. You could use this to "buddy" the browse button with the editor field Or you could simply add a browse button next to the combo box. A: This is a very old problem, and these days I want to use swing to write a small application. And I meet same problem, but I finally got a way to make it. After I read the source code of BasicComboPopup, it will check whether ComboBox is editable, if it is, pass action to editor. If you want to add JButton directly into ComboBox, you have to re-write all of ComboPopup and ComboUI. It is a huge work. But there is a easy way. static class MEditor extends JButton implements ComboBoxEditor{ //create a fake editor but it is Jbutton in fact. public MEditor(String text) { super(text); addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseClicked(e); System.out.println(text); //change it to anything you want. } }); } @Override public Component getEditorComponent() { return this; } @Override public void setItem(Object anObject) {} @Override public Object getItem() { return null; } @Override public void selectAll() {} @Override public String toString(){ return getText();// You have to keep this // otherwise the name will be object id in ComboBox } } static class MComboBox<E> extends JComboBox<E>{ public MComboBox(){ setEditable(true); addItemListener(e -> { int stateChange = e.getStateChange(); Object item = e.getItem();// if (stateChange == ItemEvent.SELECTED) { //just make MEditor into front after selected setEditor((MEditor)item); setSelectedItem(item); } }); } } Now you can make the thing you want MComboBox<MEditor> test = new MComboBox<MEditor>(); test.addItem(new MEditor("JButton 1")); test.addItem(new MEditor("JButton 2")); I have tried this, it can work!!
How to put a JButton inside a JComboBox
I would like to put a JButton inside a JComboBox. This button lets users browse for files. The file the user selects gets added to the JComboBox list. How do I do this? Do I use some kind of a Renderer? Thank you. EDIT: After reading more about ListCellRenderer I tried the following code: JComboBox comboBox = new JComboBox(new String[]{"", "Item1", "Item2"}); ComboBoxRenderer renderer = new ComboBoxRenderer(); comboBox.setRenderer(renderer); class ComboBoxRenderer implements ListCellRenderer { public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JButton jbutton = new JButton("Browse"); return jbutton; } } The problem with the above is that the Button "Browse" will be added 3 times and I want it to display only once and below it to display Item1 and Item2 as normal/regular combobox selection objects.
[ "I would avoid the JButton. It is perfectly possible to get the image of a JButton inside your combobox, but it will not behave itself as a button. You cannot click it, it never gets visually 'pressed' nor 'released', ... . In short, your combobox will contain an item which behaves unfamiliar to your users.\nThe reason for this is that the components you return in the getListCellRendererComponent method are not contained in the JCombobox. They are only used as a stamp. That also explains why you can (and should) reuse the Component you return in that method, and not create new components the whole time. This is all explained in the JTable tutorial in the part about Renderers and Editors (explained for a JTable but valid for all other Swing components which use renderers and editors).\nIf you really want an item in the combobox that allows to show a file chooser, I would opt for something similar to the following SSCCE:\nimport javax.swing.JComboBox;\nimport javax.swing.JFrame;\nimport java.awt.EventQueue;\nimport java.awt.event.ItemEvent;\nimport java.awt.event.ItemListener;\n\npublic class ComboboxTest {\n\n public static void main( String[] args ) {\n EventQueue.invokeLater( new Runnable() {\n @Override\n public void run() {\n JFrame frame = new JFrame( \"TestFrame\" );\n JComboBox<String> comboBox = new JComboBox<>(new String[]{\"Item1\", \"Item2\"});\n final String browse = \"<<BROWSE>>\";\n comboBox.addItem( browse );\n comboBox.addItemListener( new ItemListener() {\n @Override\n public void itemStateChanged( ItemEvent e ) {\n if ( e.getStateChange() == ItemEvent.SELECTED && \n browse.equals( e.getItem() ) ){\n System.out.println(\"Show filechooser\");\n }\n }\n } );\n frame.add( comboBox );\n frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n frame.setVisible( true );\n frame.pack();\n }\n } );\n }\n}\n\n", "After trying out many things I think I figured out the Answer, I am sure it will look very easy when you see it:\n JComboBox comboBox = new JComboBox(new String[]{\"Item1\", \"Item2\"});\n ComboBoxRenderer renderer = new ComboBoxRenderer();\n comboBox.setRenderer(renderer);\n comboBox.addItem(\"<<BROWSE>>\");\n\nclass ComboBoxRenderer implements ListCellRenderer {\n\n @Override\n public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {\n if (value.equals(\"<<BROWSE>>\")) {\n JButton btn = new JButton(\"Browse\");\n return btn;\n } else {\n JLabel lbl = new JLabel(value.toString());\n lbl.setOpaque(true);\n return lbl;\n }\n }\n }\n\nYou can now customize the button and labels any way you wish.\n", "Indeed, you will have to use a custom renderer as explained on http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer.\n", "Depending on where you want to put the search button, you could take a look at the xswingx Prompt/Buddy API. You could use this to \"buddy\" the browse button with the editor field\nOr you could simply add a browse button next to the combo box.\n", "This is a very old problem, and these days I want to use swing to write a small application. And I meet same problem, but I finally got a way to make it.\nAfter I read the source code of BasicComboPopup, it will check whether ComboBox is editable, if it is, pass action to editor. If you want to add JButton directly into ComboBox, you have to re-write all of ComboPopup and ComboUI. It is a huge work. But there is a easy way.\nstatic class MEditor extends JButton implements ComboBoxEditor{\n //create a fake editor but it is Jbutton in fact.\n public MEditor(String text) {\n super(text);\n addMouseListener(new MouseAdapter() {\n @Override\n public void mouseReleased(MouseEvent e) {\n super.mouseClicked(e);\n System.out.println(text);\n //change it to anything you want.\n }\n });\n }\n\n @Override\n public Component getEditorComponent() {\n return this;\n }\n @Override\n public void setItem(Object anObject) {}\n\n @Override\n public Object getItem() {\n return null;\n }\n @Override\n public void selectAll() {}\n @Override\n public String toString(){\n return getText();// You have to keep this\n // otherwise the name will be object id in ComboBox\n }\n}\nstatic class MComboBox<E> extends JComboBox<E>{\n public MComboBox(){\n setEditable(true);\n addItemListener(e -> {\n int stateChange = e.getStateChange();\n Object item = e.getItem();// \n if (stateChange == ItemEvent.SELECTED) {\n //just make MEditor into front after selected\n setEditor((MEditor)item);\n setSelectedItem(item);\n }\n });\n }\n\n}\n\nNow you can make the thing you want\n MComboBox<MEditor> test = new MComboBox<MEditor>();\n test.addItem(new MEditor(\"JButton 1\"));\n test.addItem(new MEditor(\"JButton 2\"));\n\nI have tried this, it can work!!\n" ]
[ 5, 2, 1, 1, 0 ]
[]
[]
[ "java", "jbutton", "jcombobox", "render", "swing" ]
stackoverflow_0012098521_java_jbutton_jcombobox_render_swing.txt
Q: Laravel showing "Failed to clear cache. Make sure you have the appropriate permissions" Laravel was displaying to me "Access denied for user 'homestead'@'localhost' (using password: YES)". One solution for this was clearing the cache and the config cache stored, all this with these three commands: php artisan cache:clear php artisan config:clear php artisan config:cache After php artisan cache:clear, terminal says: Failed to clear cache. Make sure you have the appropriate permissions. (with red background) Doing the second and third code (php artisan config:clear and php artisan config:cache) works fine! But it still gives me the error when typing the first line. Can anyone explain why? A: If the data directory doesn't exist under (storage/framework/cache/data), then you will have this error. This data directory doesn't exist by default on a fresh/new installation. Creating the data directory manually at (storage/framework/cache) should fix this issue. A: Try deleting these cached files under bootstrap folder: /bootstrap/cache/packages.php /bootstrap/cache/services.php /bootstrap/cache/config.php Then run php artisan cache:clear A: Calling php artisan config:cache before php artisan cache:clear fixed the issue. A: Just only add folder named data in storage/framework/cache/ and try: php artisan cache:clear A: First try: Check if there is a "data" folder inside "storage/framework/cache/". If there is not, then create it manually. (create a new folder with name "data") Option 2: If there is a "data" folder inside "storage/framework/cache/". Remove ALL existing folders inside there. Then final, running this: php artisan cache:clear This should fix this issue: "Failed to clear cache. Make sure you have the appropriate permissions." A: Calling the following 4 commands should fix most of the permission issues on laravel. sudo chown -R $USER:www-data storage sudo chown -R $USER:www-data bootstrap/cache chmod -R 775 storage chmod -R 775 bootstrap/cache Basically, chown -R $USER:www-data what this does is it set current user $USER as owner and www-data as group and chmod -R 775 gives 7 to user,7 to group and 5 to other. #PS: You need to run above command from the laravel project directory, else, you need to provide full path like /var/www/project_name/storage A: In Laravel 8 I solved my issue by first running composer dump-autoload and then used php artisan config:cache A: Deleting and adding back the ./storage/framework/cache/data folder worked for me. A: You should update the permission using the below steps: Check user using command "whoami" then let output is "ironman" Run below command if "data" folder exists in the cache directory sudo chown -R ironman:ironman storage/framework/cache/data/ This will resolve your below issue A: Delete all subfolders under: storage/framework/cache/data/ A: I ran my project in a docker container, then later tried accessing it via laragon, I had similar issue, this was due to compiled configurations in /bootstrap/cache/config.php. I fixed fit by running php artisan config:clear, this deletes the /bootstrap/cache/config.php file automatically. A: I had the same problem but noticed if you run php artisan config:clear it also by default runs cache:clear right after it so when you run it again there is not cache in it and gives that error. you only need to run php artisan config:clear. I am not sure why cache:clear fails when its ran alone but running the config:clear is a good alternative. Here is a helpful alias i use to clear everything in the app. laraclear='php artisan config:cache && php artisan config:clear && php artisan view:clear && php artisan route:clear && php artisan telescope:clear && php artisan debugbar:clear' Remove any unwanted commands that you do not use in it. A: (For MAC Users) Sometimes, it means current user don't have sufficient permission to the storage/framework/cache/data/ folder. Run sudo chmod -R ug+rwx storage/framework/cache/data/ then php artisan cache:clear Hope sometimes it work for you. A: In my case the problem was I had 'CACHE_DRIVER=memcached' in .env but didn't have memcached installed. Switching to the file driver or installing memcached fixed the problem for me. A: You may need to clear the autoloader with composer dump-autoload If that doesn't work you can manually remove the following non-tracked (usually) files to clear the autoloader and cache if they get jammed up: /bootstrap/cache/packages.php /bootstrap/cache/services.php A: For Laravel Homestead on Windows: In your .env file, change your CACHE_DRIVER from file to memcached. Run php artisan cache:clear. A: Can't this solve it? $php artisan optimize:clear Compiled views cleared! Application cache cleared! Route cache cleared! Configuration cache cleared! Compiled services and packages files removed! A: Had the same problem on my vagrant/homestead VM. All the other things in this thread didn't help. The solution was vagrant reload --provision A: Giving 775 permission to the storage directory solved this problem for me. sudo chmod -R 775 storage A: I am running my project in Homestead. My environment : Ubuntu1~20.04+ Laravel 6.20.26 My output display real fatal info Edit src/Illuminate/Filesystem/Filesystem.php 598:14 original code: if (! $preserve) { @rmdir($directory); } debug code if (! $preserve) { rmdir($directory); } Then re-execute php artisan cache:clear The output changed: Then, I just resolve Text file busy A: Ensure APP_URL is properly set on .env file. Changing http to https in the APP_URL variable on .env file solved it for me. A: Solution : update the permission : get user name by this command : whoami Run command if "data" folderexists in the cache directory. sudo chown -R YourUSERName:YourUSERName storage/framework/cache/data/
Laravel showing "Failed to clear cache. Make sure you have the appropriate permissions"
Laravel was displaying to me "Access denied for user 'homestead'@'localhost' (using password: YES)". One solution for this was clearing the cache and the config cache stored, all this with these three commands: php artisan cache:clear php artisan config:clear php artisan config:cache After php artisan cache:clear, terminal says: Failed to clear cache. Make sure you have the appropriate permissions. (with red background) Doing the second and third code (php artisan config:clear and php artisan config:cache) works fine! But it still gives me the error when typing the first line. Can anyone explain why?
[ "If the data directory doesn't exist under (storage/framework/cache/data), then you will have this error. \nThis data directory doesn't exist by default on a fresh/new installation.\nCreating the data directory manually at (storage/framework/cache) should fix this issue.\n", "Try deleting these cached files under bootstrap folder:\n/bootstrap/cache/packages.php\n/bootstrap/cache/services.php\n/bootstrap/cache/config.php\n\nThen run php artisan cache:clear\n", "Calling \nphp artisan config:cache \n\nbefore\nphp artisan cache:clear\n\nfixed the issue.\n", "Just only add folder named data in storage/framework/cache/ and try:\nphp artisan cache:clear\n\n", "\nFirst try:\nCheck if there is a \"data\" folder inside \"storage/framework/cache/\".\nIf there is not, then create it manually. (create a new folder with name \"data\")\nOption 2:\nIf there is a \"data\" folder inside \"storage/framework/cache/\".\nRemove ALL existing folders inside there.\nThen final, running this:\nphp artisan cache:clear\n\nThis should fix this issue: \"Failed to clear cache. Make sure you have the appropriate permissions.\"\n", "Calling the following 4 commands should fix most of the permission issues on laravel.\nsudo chown -R $USER:www-data storage\nsudo chown -R $USER:www-data bootstrap/cache\nchmod -R 775 storage\nchmod -R 775 bootstrap/cache\n\nBasically, chown -R $USER:www-data what this does is it set current user $USER as owner and www-data as group and chmod -R 775 gives 7 to user,7 to group and 5 to other.\n#PS: You need to run above command from the laravel project directory, else, you need to provide full path like /var/www/project_name/storage\n", "In Laravel 8 I solved my issue by first running composer dump-autoload and then used php artisan config:cache\n", "Deleting and adding back the ./storage/framework/cache/data folder worked for me.\n", "You should update the permission using the below steps:\n\nCheck user using command \"whoami\" then let output is \"ironman\"\nRun below command if \"data\" folder exists in the cache directory\n\nsudo chown -R ironman:ironman storage/framework/cache/data/\nThis will resolve your below issue\n", "Delete all subfolders under:\nstorage/framework/cache/data/\n\n", "I ran my project in a docker container, then later tried accessing it via laragon, I had similar issue, this was due to compiled configurations in /bootstrap/cache/config.php.\nI fixed fit by running php artisan config:clear, this deletes the /bootstrap/cache/config.php file automatically.\n", "I had the same problem but noticed if you run php artisan config:clear it also by default runs cache:clear right after it so when you run it again there is not cache in it and gives that error. you only need to run php artisan config:clear. I am not sure why cache:clear fails when its ran alone but running the config:clear is a good alternative.\nHere is a helpful alias i use to clear everything in the app.\nlaraclear='php artisan config:cache && php artisan config:clear && php artisan view:clear && php artisan route:clear && php artisan telescope:clear && php artisan debugbar:clear'\n\nRemove any unwanted commands that you do not use in it.\n", "(For MAC Users)\nSometimes, it means current user don't have sufficient permission to the storage/framework/cache/data/ folder. Run\n\nsudo chmod -R ug+rwx storage/framework/cache/data/\n\nthen\n\nphp artisan cache:clear\n\nHope sometimes it work for you.\n", "In my case the problem was I had 'CACHE_DRIVER=memcached' in .env but didn't have memcached installed. Switching to the file driver or installing memcached fixed the problem for me.\n", "You may need to clear the autoloader with\ncomposer dump-autoload\nIf that doesn't work you can manually remove the following non-tracked (usually) files to clear the autoloader and cache if they get jammed up:\n/bootstrap/cache/packages.php\n/bootstrap/cache/services.php\n", "For Laravel Homestead on Windows:\nIn your .env file, change your CACHE_DRIVER from file to memcached.\nRun php artisan cache:clear.\n", "Can't this solve it?\n$php artisan optimize:clear\nCompiled views cleared!\nApplication cache cleared!\nRoute cache cleared!\nConfiguration cache cleared!\nCompiled services and packages files removed!\n\n", "Had the same problem on my vagrant/homestead VM. All the other things in this thread didn't help.\nThe solution was vagrant reload --provision\n", "Giving 775 permission to the storage directory solved this problem for me.\nsudo chmod -R 775 storage\n\n", "I am running my project in Homestead.\nMy environment :\n\nUbuntu1~20.04+\nLaravel 6.20.26\n\nMy output\n\ndisplay real fatal info\nEdit src/Illuminate/Filesystem/Filesystem.php 598:14\noriginal code:\nif (! $preserve) {\n @rmdir($directory);\n}\n\ndebug code\nif (! $preserve) {\n rmdir($directory);\n}\n\nThen re-execute php artisan cache:clear\nThe output changed:\n\nThen, I just resolve Text file busy\n", "Ensure APP_URL is properly set on .env file. Changing http to https in the APP_URL variable on .env file solved it for me.\n", "Solution :\nupdate the permission :\n\nget user name by this command : whoami\n\nRun command if \"data\" folderexists in the cache directory.\nsudo chown -R YourUSERName:YourUSERName storage/framework/cache/data/\n\n\n" ]
[ 384, 127, 53, 42, 33, 31, 17, 8, 6, 3, 2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0 ]
[ "got the same error. try giving chmod 777 permission in the concerned folder\n", "My guess is you have a permission/ownership problem. Either set up the permissions correctly or recursively delete the cache folder manually and re-create it:\nsudo rm -Rf storage/framework/cache\nmkdir storage/framework/cache\n\n", "maybe you need to chmod 777 -R storage folder.\nand i think it can also chown www-data:www-data \n", "Incase non of these works for you, simply run your php artisan cache:clear command with sudo.\ne.g. sudo php artisan cache:clear\nThank me later~!\n" ]
[ -1, -2, -3, -3 ]
[ "composer_php", "laravel" ]
stackoverflow_0052231248_composer_php_laravel.txt
Q: Markdown. Replacing Two Matches preg_replace It turns out to make one replacement, but no more than two. **two examples: ** The first doesn't work: $result_do_not_work The Second one work: $result_work $text_does_not_work = ' *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* [>google!<](LINK:https://google.com)'; $text_work = ' *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* [>google!<](LINK:https://google.com)'; $patt = ['~\*spoiler-name\*(.*)\*/spoiler-name\*\*s-content\*\((.*)\)\*/s-content\*~','~\[>(.*)<\]\((.*)\)~']; $repl=['<details><summary>$1</summary>$2</details>','<a href="$2">$1</a>'];/*<a href="$2">$1</a>*/ $result_work = preg_replace($patt, $repl, $text_work); $result_does_not_work = preg_replace($patt, $repl, $text_does_not_work); I tried a many things. For example, this code also does not work: $text='[s]SPOILER[s](content-sp) [s]SPOILER[s](content-sp) [s]SPOILER[s](content-sp)'; $patt = ['/\[s\]([^*]+)\[s\]\(([^*]+)\)/im']; $repl=['<details><summary>$1</summary>$2</details>']; $page = preg_replace($patt, $repl, $text); result: SPOILER[s](content-sp) [s]SPOILER[s](content-sp) [s]SPOILER content-sp A: The * quantifier is greedy so .* will match as many characters as possible, which is probably not what is required here. Changing the (.*) to (.*?) may help solve your issue. See PHP Tutorial: Regex Non-greedy (or Lazy).
Markdown. Replacing Two Matches preg_replace
It turns out to make one replacement, but no more than two. **two examples: ** The first doesn't work: $result_do_not_work The Second one work: $result_work $text_does_not_work = ' *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* [>google!<](LINK:https://google.com)'; $text_work = ' *spoiler-name*spoil*/spoiler-name**s-content*(shadow*010*shadow*)*/s-content* [>google!<](LINK:https://google.com)'; $patt = ['~\*spoiler-name\*(.*)\*/spoiler-name\*\*s-content\*\((.*)\)\*/s-content\*~','~\[>(.*)<\]\((.*)\)~']; $repl=['<details><summary>$1</summary>$2</details>','<a href="$2">$1</a>'];/*<a href="$2">$1</a>*/ $result_work = preg_replace($patt, $repl, $text_work); $result_does_not_work = preg_replace($patt, $repl, $text_does_not_work); I tried a many things. For example, this code also does not work: $text='[s]SPOILER[s](content-sp) [s]SPOILER[s](content-sp) [s]SPOILER[s](content-sp)'; $patt = ['/\[s\]([^*]+)\[s\]\(([^*]+)\)/im']; $repl=['<details><summary>$1</summary>$2</details>']; $page = preg_replace($patt, $repl, $text); result: SPOILER[s](content-sp) [s]SPOILER[s](content-sp) [s]SPOILER content-sp
[ "The * quantifier is greedy so .* will match as many characters as possible, which is probably not what is required here.\nChanging the (.*) to (.*?) may help solve your issue.\nSee PHP Tutorial: Regex Non-greedy (or Lazy).\n" ]
[ 0 ]
[]
[]
[ "markdown", "php", "preg_replace", "regex" ]
stackoverflow_0074674745_markdown_php_preg_replace_regex.txt
Q: Remove a single date from jquery datepicker which has multidate set to true I have an array of date string. I created a date input field using $('#mydatefield').datepicker({ multidate:true; }); Need to add a validation, when someone inputs a date which exists in that array, should be removed with an error message. Or Is it possible to disable those dates on datepicker init? A: Been just playing around with OpenAI to check if can solve random stackoverflow questions like this and its just crazy! Answer after copying your question in: It is possible to use the beforeShowDay option of the jQuery UI datepicker to disable certain dates in the datepicker. You can use this option to specify a callback function that determines which dates should be disabled in the datepicker. This callback function should take a date as an argument and return an array with two values: a boolean value indicating whether the date is selectable, and a string containing the CSS class to apply to the date. Here is an example of how you could use the beforeShowDay option to disable dates that exist in your array of date strings: var datesToDisable = ["2022-12-05", "2022-12-06", "2022-12-07"]; $('#mydatefield').datepicker({ multidate: true, beforeShowDay: function(date) { var string = $.datepicker.formatDate('yy-mm-dd', date); if ($.inArray(string, datesToDisable) != -1) { return [false, ""]; } return [true, ""]; } }); In this example, the beforeShowDay callback checks if the current date is in the datesToDisable array. If it is, the date is disabled in the datepicker and the user cannot select it. Otherwise, the date is enabled and can be selected by the user. You can also use the onSelect event of the datepicker to display an error message if the user tries to select a date that is in the datesToDisable array. Here is an example of how you could do this: $('#mydatefield').datepicker({ multidate: true, beforeShowDay: function(date) { var string = $.datepicker.formatDate('yy-mm-dd', date); if ($.inArray(string, datesToDisable) != -1) { return [false, ""]; } return [true, ""]; }, onSelect: function(dateText) { if ($.inArray(dateText, datesToDisable) != -1) { // Show an error message alert("Sorry, that date is not available. Please select another date."); } } }); In this example, the onSelect event handler checks if the selected date is in the datesToDisable array. If it is, an error message is displayed to the user.
Remove a single date from jquery datepicker which has multidate set to true
I have an array of date string. I created a date input field using $('#mydatefield').datepicker({ multidate:true; }); Need to add a validation, when someone inputs a date which exists in that array, should be removed with an error message. Or Is it possible to disable those dates on datepicker init?
[ "Been just playing around with OpenAI to check if can solve random stackoverflow questions like this and its just crazy!\nAnswer after copying your question in:\nIt is possible to use the beforeShowDay option of the jQuery UI datepicker to disable certain dates in the datepicker. You can use this option to specify a callback function that determines which dates should be disabled in the datepicker. This callback function should take a date as an argument and return an array with two values: a boolean value indicating whether the date is selectable, and a string containing the CSS class to apply to the date.\nHere is an example of how you could use the beforeShowDay option to disable dates that exist in your array of date strings:\nvar datesToDisable = [\"2022-12-05\", \"2022-12-06\", \"2022-12-07\"];\n\n$('#mydatefield').datepicker({\n multidate: true,\n beforeShowDay: function(date) {\n var string = $.datepicker.formatDate('yy-mm-dd', date);\n if ($.inArray(string, datesToDisable) != -1) {\n return [false, \"\"];\n }\n return [true, \"\"];\n }\n});\n\nIn this example, the beforeShowDay callback checks if the current date is in the datesToDisable array. If it is, the date is disabled in the datepicker and the user cannot select it. Otherwise, the date is enabled and can be selected by the user.\nYou can also use the onSelect event of the datepicker to display an error message if the user tries to select a date that is in the datesToDisable array. Here is an example of how you could do this:\n$('#mydatefield').datepicker({\n multidate: true,\n beforeShowDay: function(date) {\n var string = $.datepicker.formatDate('yy-mm-dd', date);\n if ($.inArray(string, datesToDisable) != -1) {\n return [false, \"\"];\n }\n return [true, \"\"];\n },\n onSelect: function(dateText) {\n if ($.inArray(dateText, datesToDisable) != -1) {\n // Show an error message\n alert(\"Sorry, that date is not available. Please select another date.\");\n }\n }\n});\n\nIn this example, the onSelect event handler checks if the selected date is in the datesToDisable array. If it is, an error message is displayed to the user.\n" ]
[ 0 ]
[]
[]
[ "datepicker", "javascript", "jquery" ]
stackoverflow_0074674838_datepicker_javascript_jquery.txt
Q: Argument of type '(fg: FormGroup) => { notmatched: boolean; }' is not assignable to parameter of type I'm getting error like that (as u see in title). I have been working on this project for 2 days. HTML Code: <div class="container pt-5"> <h2 style="text-align: center;">Reactive Forms</h2> <div class="row justify-content-sm-center pt-5"> <div class="col-sm-6 shadow round pb-3"> <h1 class="text-center pt-3 text-secondary">Example Form</h1> <form [formGroup]='exform'> <div class="form-group"> <label class="col-form-label">Email:</label> <input formControlName="email" type="text" class="form-control" > <small *ngIf="email.invalid && email.touched" class="text-danger">Email is Required</small> </div> <div class="form-group" > <label class="col-form-label">Şifre:</label> <input formControlName="password" type="password" class="form-control"> <small *ngIf="password.invalid && password.touched" class="text-danger">Parola Gerekli</small> </div> <div class="form-group"> <label class="col-form-label">Şifre Tekrarı:</label> <input formControlName="password2" type="password" class="form-control" > <small *ngIf="password2.invalid && password2.touched" class="text-danger">Parola Tekrarı Gerekli</small> <small *ngIf="password2.invalid && password2.touched" class="text-danger">Parola Uyuşmuyor</small> </div> <button [disabled]="exform.invalid" type="button" class="btn btn-primary">Send message</button> </form> </div> </div> </div> app.components.ts Code: (problem line: this.passwordMatchValidator); import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { AbstractControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { exform!: FormGroup; message!: string; ngOnInit(){ this.exform= new FormGroup({ email: new FormControl(null, [Validators.required, Validators.minLength(4), Validators.email]), password: new FormControl(null, [Validators.minLength(8), Validators.required]), password2: new FormControl(null,[Validators.required, Validators.minLength(8)]) }, this.passwordMatchValidator); console.log('Im here') } passwordMatchValidator(fg: FormGroup){ return fg.get('password')?.value===fg.get('password2')?.value ? null : {notmatched: true} } clickSub() { console.log("clicked"); this.exform.reset(); } get email(){ return this.exform.get('email'); } get password(){ return this.exform.get('password'); } get password2(){ return this.exform.get('password2'); } } app.modelu.ts Code: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing-module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } app-routing-module.ts Code: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Error: src/app/app.component.ts:27:11 - error TS2345: Argument of type '(fg: FormGroup) => { notmatched: boolean; }' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'. Type '(fg: FormGroup) => { notmatched: boolean; }' is not assignable to type 'ValidatorFn'. Types of parameters 'fg' and 'control' are incompatible. Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more. 27 }, this.passwordMatchValidator); Where is the problem? A: Just change the type of the input. passwordMatchValidator(fg: AbstractControl){ return fg.get('password')?.value === fg.get('password2')?.value ? null : {notmatched: true} } Please read the error correctly, it is written very clearly. A: try to disable the "strictFunctionTypes": false which is in tsconfig "compilerOptions": { "baseUrl": "src", "outDir": "./dist/out-tsc", "forceConsistentCasingInFileNames": true, "strict": true, "strictFunctionTypes":false, "strictNullChecks": false,
Argument of type '(fg: FormGroup) => { notmatched: boolean; }' is not assignable to parameter of type
I'm getting error like that (as u see in title). I have been working on this project for 2 days. HTML Code: <div class="container pt-5"> <h2 style="text-align: center;">Reactive Forms</h2> <div class="row justify-content-sm-center pt-5"> <div class="col-sm-6 shadow round pb-3"> <h1 class="text-center pt-3 text-secondary">Example Form</h1> <form [formGroup]='exform'> <div class="form-group"> <label class="col-form-label">Email:</label> <input formControlName="email" type="text" class="form-control" > <small *ngIf="email.invalid && email.touched" class="text-danger">Email is Required</small> </div> <div class="form-group" > <label class="col-form-label">Şifre:</label> <input formControlName="password" type="password" class="form-control"> <small *ngIf="password.invalid && password.touched" class="text-danger">Parola Gerekli</small> </div> <div class="form-group"> <label class="col-form-label">Şifre Tekrarı:</label> <input formControlName="password2" type="password" class="form-control" > <small *ngIf="password2.invalid && password2.touched" class="text-danger">Parola Tekrarı Gerekli</small> <small *ngIf="password2.invalid && password2.touched" class="text-danger">Parola Uyuşmuyor</small> </div> <button [disabled]="exform.invalid" type="button" class="btn btn-primary">Send message</button> </form> </div> </div> </div> app.components.ts Code: (problem line: this.passwordMatchValidator); import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { AbstractControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { exform!: FormGroup; message!: string; ngOnInit(){ this.exform= new FormGroup({ email: new FormControl(null, [Validators.required, Validators.minLength(4), Validators.email]), password: new FormControl(null, [Validators.minLength(8), Validators.required]), password2: new FormControl(null,[Validators.required, Validators.minLength(8)]) }, this.passwordMatchValidator); console.log('Im here') } passwordMatchValidator(fg: FormGroup){ return fg.get('password')?.value===fg.get('password2')?.value ? null : {notmatched: true} } clickSub() { console.log("clicked"); this.exform.reset(); } get email(){ return this.exform.get('email'); } get password(){ return this.exform.get('password'); } get password2(){ return this.exform.get('password2'); } } app.modelu.ts Code: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing-module'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } app-routing-module.ts Code: import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } Error: src/app/app.component.ts:27:11 - error TS2345: Argument of type '(fg: FormGroup) => { notmatched: boolean; }' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'. Type '(fg: FormGroup) => { notmatched: boolean; }' is not assignable to type 'ValidatorFn'. Types of parameters 'fg' and 'control' are incompatible. Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more. 27 }, this.passwordMatchValidator); Where is the problem?
[ "Just change the type of the input.\n passwordMatchValidator(fg: AbstractControl){\n return fg.get('password')?.value === fg.get('password2')?.value ? null : {notmatched: true}\n }\n\nPlease read the error correctly, it is written very clearly.\n", "try to disable the \"strictFunctionTypes\": false which is in tsconfig\n\"compilerOptions\": {\n\"baseUrl\": \"src\",\n\"outDir\": \"./dist/out-tsc\",\n\"forceConsistentCasingInFileNames\": true,\n\"strict\": true,\n\"strictFunctionTypes\":false,\n\"strictNullChecks\": false,\n" ]
[ 1, 0 ]
[]
[]
[ "angular", "html", "typescript" ]
stackoverflow_0068923236_angular_html_typescript.txt
Q: GitHub Actions Set Output - Assure Parallel Job Access is Safe I have configured my github actions which runs tests in parallel for different platforms. At the end of my tests I want the status to be saved to the outputs. Once all jobs complete I have another job that runs to send the results to a slack webhook. I am having difficulty determining a method to save the output for multiple jobs and assuring there is no issues when they are running in parallel. For example this is my code snippet name: Test Notify on: push: jobs: build: strategy: matrix: config: - name: 'Ubuntu 18.04' runner: 'ubuntu-18.04' id: 'u18' - name: 'Ubuntu 20.04' runner: 'ubuntu-20.04' fail-fast: false runs-on: ${{ matrix.config.runner }} outputs: # Prefer to have one general output I can append to global: ${{ steps.status.outputs.global }} # I can output to separate outputs but I rather have a single one as shown above u18: ${{ steps.status.outputs.u18 }} u20: ${{ steps.status.outputs.u20 }} steps: - name: Test Failure u18 id: step1 if: ${{ matrix.config.id == 'u18' }} run: | exit 1 - name: Doing Step 2 id: step2 run: | echo "DO NOTHING" - name: Output Status id: status if: always() env: JOB_STATUS: "${{ job.status }}" run: | # This works, but is it safe since I have u18 and u20 running in parallel ? echo "${{ matrix.config.id }}=$JOB_STATUS" >> $GITHUB_OUTPUT # Is there a safe way to have a single status string that I add to, for example; # echo "global=${{ github_output.global}}$JOB_STATUS" >> $GITHUB_OUTPUT webhook: needs: build runs-on: 'ubuntu-20.04' if: always() steps: - name: Send webhook update for all jobs env: JSON_RESULTS: "${{ toJSON(needs.build-and-test) }}" run: | # Will add code to properly send the information echo $JSON_RESULTS A: Currently, there is no easy way to reference all outputs of matrix jobs. Moreover combining it into a single output. The issue is that only a single value is available for future jobs that need the strategy.matrix job’s output because even if the output is set by multiple matrix variations of the job, only one is retained. For more detail, see the Community discussion. TL;DR: There are several workarounds: defining separate outputs for a job with strategy.matrix by letting the job variations set different outputs then process these outputs in a separate step that can provide single output for further steps use artifacts to store the matrix jobs' outputs and then post-process it (discussioncomment-3814009)
GitHub Actions Set Output - Assure Parallel Job Access is Safe
I have configured my github actions which runs tests in parallel for different platforms. At the end of my tests I want the status to be saved to the outputs. Once all jobs complete I have another job that runs to send the results to a slack webhook. I am having difficulty determining a method to save the output for multiple jobs and assuring there is no issues when they are running in parallel. For example this is my code snippet name: Test Notify on: push: jobs: build: strategy: matrix: config: - name: 'Ubuntu 18.04' runner: 'ubuntu-18.04' id: 'u18' - name: 'Ubuntu 20.04' runner: 'ubuntu-20.04' fail-fast: false runs-on: ${{ matrix.config.runner }} outputs: # Prefer to have one general output I can append to global: ${{ steps.status.outputs.global }} # I can output to separate outputs but I rather have a single one as shown above u18: ${{ steps.status.outputs.u18 }} u20: ${{ steps.status.outputs.u20 }} steps: - name: Test Failure u18 id: step1 if: ${{ matrix.config.id == 'u18' }} run: | exit 1 - name: Doing Step 2 id: step2 run: | echo "DO NOTHING" - name: Output Status id: status if: always() env: JOB_STATUS: "${{ job.status }}" run: | # This works, but is it safe since I have u18 and u20 running in parallel ? echo "${{ matrix.config.id }}=$JOB_STATUS" >> $GITHUB_OUTPUT # Is there a safe way to have a single status string that I add to, for example; # echo "global=${{ github_output.global}}$JOB_STATUS" >> $GITHUB_OUTPUT webhook: needs: build runs-on: 'ubuntu-20.04' if: always() steps: - name: Send webhook update for all jobs env: JSON_RESULTS: "${{ toJSON(needs.build-and-test) }}" run: | # Will add code to properly send the information echo $JSON_RESULTS
[ "Currently, there is no easy way to reference all outputs of matrix jobs. Moreover combining it into a single output.\nThe issue is that only a single value is available for future jobs that need the strategy.matrix job’s output because even if the output is set by multiple matrix variations of the job, only one is retained.\nFor more detail, see the Community discussion.\nTL;DR:\nThere are several workarounds:\n\ndefining separate outputs for a job with strategy.matrix by letting the job variations set different outputs\n\nthen process these outputs in a separate step that can provide single output for further steps\n\n\nuse artifacts to store the matrix jobs' outputs and then post-process it (discussioncomment-3814009)\n\n\n" ]
[ 0 ]
[]
[]
[ "building_github_actions", "github", "github_actions", "github_pages" ]
stackoverflow_0074381930_building_github_actions_github_github_actions_github_pages.txt
Q: R - Change position of geom_text inside geom_bar I am trying to control the position of two calls of geom_text inside geom_bar, but I just can't get it right. This is what I have so far: However, I would like to change two things in this plot: Put the letters (first geom_text call) at the top left corner of the bars, just before the error bars. Or perhaps on top of the error bars. Put the numbers (second geom_text call) in the middle of the bars. Here are my code and dataset sample: library(ggplot2) dat <- structure(list(ObservationId = c("Control", "Control", "Control", "Control", "Control", "Control", "Control", "Control", "Control" ), Treatment = c("TREATMENT A", "TREATMENT B", "UNTREATED", "TREATMENT A", "TREATMENT B", "UNTREATED", "TREATMENT A", "TREATMENT B", "UNTREATED" ), day_class = c("Time1", "Time1", "Time1", "Time2", "Time2", "Time2", "Time3", "Time3", "Time3"), Estimate = c(100, 99.8, 0.7, 97.2, 91.2, 7.2, 94.6, 87.3, 14.5), SE = c(4.2, 4.4, 3.7, 3.6, 4.1, 3.8, 3.7, 4.1, 3.8), df = c(38.5, 42.3, 37.4, 33.5, 37.4, 37.8, 33.9, 38.5, 38.1), lower.CL = c(91.6, 90.9, -6.9, 89.8, 83, -0.4, 87.2, 79, 6.9), upper.CL = c(108.4, 108.7, 8.3, 104.6, 99.5, 14.8, 102.1, 95.7, 22.1), Class = c("A", "A", "B", "A", "A", "B", "A", "A", "B")), row.names = c(NA, 9L), class = "data.frame") ggplot(dat, aes(x = Treatment, y = Estimate, group = day_class, fill = day_class)) + theme_bw() + geom_col(position = "dodge", color = "black") + geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.2, position = position_dodge(0.9)) + geom_text(aes(label = Class, group = day_class), position = position_dodge(width = 0.9), color = 'blue', size = 5) + geom_text(aes(label = round(Estimate,1), group = day_class), position = position_dodge(width = 0.9), size = 4) How can I achieve those changes? A: You can use y inside geom_text, an example: ggplot(dat, aes(x = Treatment, y = Estimate, group = day_class, fill = day_class)) + theme_bw() + geom_col(position = "dodge", color = "black") + geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.2, position = position_dodge(0.9)) + geom_text(aes(label = Class, group = day_class,y = upper.CL), position = position_dodge(width = 0.9), color = 'blue', size = 5) + geom_text(aes(label = round(Estimate,1), group = day_class, y = (upper.CL+Estimate)/2 ), position = position_dodge(width = 0.9), size = 4) A: hjust and vjust offers flexibility to nudge labels: <as your code> + geom_text(aes(label = Class, group = day_class), position = position_dodge(width = 0.9), color = 'blue', hjust = 4, vjust = -3, size = 5) + geom_text(aes(label = round(Estimate,1), group = day_class), position = position_dodge(width = 0.9), hjust = 0.5, vjust = 2, size = 4)
R - Change position of geom_text inside geom_bar
I am trying to control the position of two calls of geom_text inside geom_bar, but I just can't get it right. This is what I have so far: However, I would like to change two things in this plot: Put the letters (first geom_text call) at the top left corner of the bars, just before the error bars. Or perhaps on top of the error bars. Put the numbers (second geom_text call) in the middle of the bars. Here are my code and dataset sample: library(ggplot2) dat <- structure(list(ObservationId = c("Control", "Control", "Control", "Control", "Control", "Control", "Control", "Control", "Control" ), Treatment = c("TREATMENT A", "TREATMENT B", "UNTREATED", "TREATMENT A", "TREATMENT B", "UNTREATED", "TREATMENT A", "TREATMENT B", "UNTREATED" ), day_class = c("Time1", "Time1", "Time1", "Time2", "Time2", "Time2", "Time3", "Time3", "Time3"), Estimate = c(100, 99.8, 0.7, 97.2, 91.2, 7.2, 94.6, 87.3, 14.5), SE = c(4.2, 4.4, 3.7, 3.6, 4.1, 3.8, 3.7, 4.1, 3.8), df = c(38.5, 42.3, 37.4, 33.5, 37.4, 37.8, 33.9, 38.5, 38.1), lower.CL = c(91.6, 90.9, -6.9, 89.8, 83, -0.4, 87.2, 79, 6.9), upper.CL = c(108.4, 108.7, 8.3, 104.6, 99.5, 14.8, 102.1, 95.7, 22.1), Class = c("A", "A", "B", "A", "A", "B", "A", "A", "B")), row.names = c(NA, 9L), class = "data.frame") ggplot(dat, aes(x = Treatment, y = Estimate, group = day_class, fill = day_class)) + theme_bw() + geom_col(position = "dodge", color = "black") + geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.2, position = position_dodge(0.9)) + geom_text(aes(label = Class, group = day_class), position = position_dodge(width = 0.9), color = 'blue', size = 5) + geom_text(aes(label = round(Estimate,1), group = day_class), position = position_dodge(width = 0.9), size = 4) How can I achieve those changes?
[ "You can use y inside geom_text, an example:\nggplot(dat,\n aes(x = Treatment,\n y = Estimate,\n group = day_class,\n fill = day_class)) +\n theme_bw() +\n geom_col(position = \"dodge\", color = \"black\") +\n geom_errorbar(aes(ymin = lower.CL,\n ymax = upper.CL),\n width = 0.2, position = position_dodge(0.9)) +\n geom_text(aes(label = Class, group = day_class,y = upper.CL),\n position = position_dodge(width = 0.9),\n color = 'blue',\n size = 5) +\n geom_text(aes(label = round(Estimate,1), group = day_class, y = (upper.CL+Estimate)/2 ),\n position = position_dodge(width = 0.9),\n size = 4) \n\n\n", "hjust and vjust offers flexibility to nudge labels:\n<as your code> +\n geom_text(aes(label = Class, group = day_class),\n position = position_dodge(width = 0.9),\n color = 'blue',\n hjust = 4, vjust = -3,\n size = 5) + \n geom_text(aes(label = round(Estimate,1), group = day_class),\n position = position_dodge(width = 0.9),\n hjust = 0.5, vjust = 2,\n size = 4) \n\n\n" ]
[ 1, 1 ]
[]
[]
[ "bar_chart", "ggplot2", "plot", "r" ]
stackoverflow_0074671920_bar_chart_ggplot2_plot_r.txt
Q: shouldDirty of 'react-hook-form' is not re-rendering the component I have written the following code with react-hook-form. I am using material ui. When I click the checkbox the first time(uncheck->check), everything works fine. "Comment1" appears on the page. But when I click the checkbox 2nd time(check->uncheck), the checkbox does not change state. It stays in the checked state. "Comment1" does not disappear. I am using {shouldDirty: true}. 'shouldDirty' should rerender the component with every click. Correct ? const { register, setValue, getValues, formState: { isDirty, dirtyFields }, } = useForm(); const onSubmit = (data: any) => { console.log("Data == ", data); }; return ( <> <FormControlLabel label={"First Check"} control={ <Checkbox {...register("first")} onChange={(event) => { setValue("first", event.target.checked, { shouldDirty: true, }); }} checked={!!getValues("first")} /> } /> {getValues("first") ? <Typography>{"Comment1"}</Typography> : <></>} </> ); };``` Thanks, Sachin A: setValue does not trigger a re-render in most cases. From the documentation: Only the following conditions will trigger a re-render: When an error is triggered or corrected by a value update When setValue cause state update, such as dirty and touched. When you click for the first time, your input becomes dirty so the component re-renders (and "Comment1" appears). This is not the case for second time you click because none of the two conditions above are satisfied. If you'd like to have a consistent re-render, you might want to use reset method instead.
shouldDirty of 'react-hook-form' is not re-rendering the component
I have written the following code with react-hook-form. I am using material ui. When I click the checkbox the first time(uncheck->check), everything works fine. "Comment1" appears on the page. But when I click the checkbox 2nd time(check->uncheck), the checkbox does not change state. It stays in the checked state. "Comment1" does not disappear. I am using {shouldDirty: true}. 'shouldDirty' should rerender the component with every click. Correct ? const { register, setValue, getValues, formState: { isDirty, dirtyFields }, } = useForm(); const onSubmit = (data: any) => { console.log("Data == ", data); }; return ( <> <FormControlLabel label={"First Check"} control={ <Checkbox {...register("first")} onChange={(event) => { setValue("first", event.target.checked, { shouldDirty: true, }); }} checked={!!getValues("first")} /> } /> {getValues("first") ? <Typography>{"Comment1"}</Typography> : <></>} </> ); };``` Thanks, Sachin
[ "setValue does not trigger a re-render in most cases. From the documentation:\n\nOnly the following conditions will trigger a re-render:\nWhen an error is triggered or corrected by a value update\nWhen setValue cause state update, such as dirty and touched.\n\nWhen you click for the first time, your input becomes dirty so the component re-renders (and \"Comment1\" appears). This is not the case for second time you click because none of the two conditions above are satisfied.\nIf you'd like to have a consistent re-render, you might want to use reset method instead.\n" ]
[ 0 ]
[]
[]
[ "react_hook_form", "reactjs" ]
stackoverflow_0074553724_react_hook_form_reactjs.txt
Q: How to use translation by reference in i18n react? The React site has two languages ​​(en, ru). From different sources, we need to send to a different translation. Now there is an initial en, it can be switched by the button to ru. Is it possible to make it so that a different translation opens like this: https://sitename.com?en or https://sitename.com/en to English translation? A: To use translation by reference in i18n react, you can use the react-i18next library. Here are the steps to follow: Install the react-i18next library by running the following command in the terminal: npm install react-i18next Create a JSON file for each language that you want to support. For example, if you want to support English and Russian, you can create two JSON files named "en.json" and "ru.json" respectively. In the "en.json" file, define the translations for English. For example: { "hello": "Hello" } In the "ru.json" file, define the translations for Russian. For example: { "hello": "Привет" } In the root component of your app, import the i18n instance from the react-i18next library and initialize it with the languages and the translation files. For example: import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; i18n .use(initReactI18next) .init({ lng: 'en', resources: { en: { translation: require('./en.json') }, ru: { translation: require('./ru.json') } } }); Use the useTranslation hook provided by the react-i18next library in your components to access the translations. For example: import { useTranslation } from 'react-i18next'; function MyComponent() { const { t } = useTranslation(); return ( <p>{t('hello')}</p> ); } To switch between languages, use the i18n.changeLanguage() method. For example: import i18n from 'i18next'; function changeLanguage(language) { i18n.changeLanguage(language); } To use the translation by reference in the URL, you can create a custom route in your app that accepts the language code as a parameter. For example: <Router> <Switch> <Route path="/:language" component={App} /> </Switch> </Router> In the App component, you can use the language parameter from the URL to switch the language using the changeLanguage() method. For example: import { useLocation } from 'react-router-dom'; import i18n from 'i18next'; function App() { const { language } = useLocation().params; i18n.changeLanguage(language); // ... } Now, when you visit https://sitename.com/en, it will automatically switch to the English translation, and when you visit https://sitename.com/ru, it will switch to the Russian translation.
How to use translation by reference in i18n react?
The React site has two languages ​​(en, ru). From different sources, we need to send to a different translation. Now there is an initial en, it can be switched by the button to ru. Is it possible to make it so that a different translation opens like this: https://sitename.com?en or https://sitename.com/en to English translation?
[ "To use translation by reference in i18n react, you can use the react-i18next library. Here are the steps to follow:\nInstall the react-i18next library by running the following command in the terminal:\nnpm install react-i18next\n\nCreate a JSON file for each language that you want to support. For example, if you want to support English and Russian, you can create two JSON files named \"en.json\" and \"ru.json\" respectively.\nIn the \"en.json\" file, define the translations for English. For example:\n{\n \"hello\": \"Hello\"\n}\n\nIn the \"ru.json\" file, define the translations for Russian. For example:\n{\n \"hello\": \"Привет\"\n}\n\nIn the root component of your app, import the i18n instance from the react-i18next library and initialize it with the languages and the translation files. For example:\nimport i18n from 'i18next';\nimport { initReactI18next } from 'react-i18next';\n\ni18n\n .use(initReactI18next)\n .init({\n lng: 'en',\n resources: {\n en: {\n translation: require('./en.json')\n },\n ru: {\n translation: require('./ru.json')\n }\n }\n });\n\nUse the useTranslation hook provided by the react-i18next library in your components to access the translations. For example:\nimport { useTranslation } from 'react-i18next';\n\nfunction MyComponent() {\n const { t } = useTranslation();\n return (\n <p>{t('hello')}</p>\n );\n}\n\nTo switch between languages, use the i18n.changeLanguage() method. For example:\nimport i18n from 'i18next';\n\nfunction changeLanguage(language) {\n i18n.changeLanguage(language);\n}\n\nTo use the translation by reference in the URL, you can create a custom route in your app that accepts the language code as a parameter. For example:\n<Router>\n <Switch>\n <Route path=\"/:language\" component={App} />\n </Switch>\n</Router>\n\nIn the App component, you can use the language parameter from the URL to switch the language using the changeLanguage() method. For example:\nimport { useLocation } from 'react-router-dom';\nimport i18n from 'i18next';\n\nfunction App() {\n const { language } = useLocation().params;\n i18n.changeLanguage(language);\n // ...\n}\n\nNow, when you visit https://sitename.com/en, it will automatically switch to the English translation, and when you visit https://sitename.com/ru, it will switch to the Russian translation.\n" ]
[ 0 ]
[]
[]
[ "i18next", "react_i18next", "reactjs" ]
stackoverflow_0074674783_i18next_react_i18next_reactjs.txt
Q: Output specific fields using bash I have a test.fasta file with the following data: >PPP.0124.1.PC lib=RU01 length=410 description=Protein description goes here 1 serine/threonine MLEAPKFTGIIGLNNNHDNYDLSQGFYHKLGEGSNMSIDSFGSLQLSNGG GSVAMSVSSVGSNDSHTRILNHQGLKRVNGNYSVARSVNRGKVSHGLSDD ALAQ >PPP.14552.PC lib=RU01 length=104 description=Protein description goes here 2 uncharacterized protein LOC11441 MKSVVGMVVSNKMQKSVVVAVDRLFHHKLYDRYVKRTSKFMAHDEHNLCN IGDRVRL >PPP.94014.PC lib=RU01 length=206 description=Protein description goes here 3 some more chemicals and stuff MDLGPTLTLQKGRQRRGKGPYAGVRSRGGRWVSEIRIPKTKTRIWLGSHH SPEKAARAYDAALYCLKGEHGSFNFPNNRGPYLANRSVGSLPVDEIQCIA AEFSCFDDSA I would like to take the ID and the description and output them into a .tsv file, with the first column being the ID and the second column holding the description. Desired output: | ID | Description | | -------- | -------------- | | 0124 | Protein description goes here 1 serine/threonine | | 14552 | Protein description goes here 2 uncharacterized protein LOC11441 | | 94014 | Protein description goes here 3 some more chemicals and stuff | Any ideas on a one-line Bash command to achieve this? I currently have this: grep -a '^>' test.fasta | awk '{print $1} which gives me the first lines and the ID's but cant seem to figure out the rest! A: You can use the following one-line bash command to extract the IDs and descriptions from your test.fasta file and output them in a tab-separated values (TSV) format: grep -a '^>' test.fasta | awk '{gsub(/^>/, ""); print $1 "\t" $2}' A: Using awk: awk 'BEGIN{print "id\tdescription"} \ /.PC / && !/uncharac/ { \ split($1,b,"."); id=b[2]; \ $1=""; $2=""; $3=""; $(NF)=""; $(NF-1)=""; $(NF-2)=""; \ gsub("description=",""); print id"\t"$0} \ /.PC / && /uncharac/ { \ split($1,b,"."); id=b[2]; \ $1=""; $2=""; $3=""; $(NF)=""; $(NF-1)=""; \ gsub("description=",""); print id"\t"$0}' test.fasta id description 0124 Protein description goes here 1 || serine/threonine 14552 Protein description goes here 2 || uncharacterized protein LOC11441 94014 UProtein description goes here 3 || some more chemicals and stuff Since the description can span n columns, you need to remove 'known', unwanted columns. In your test data there seem to be records that can be differentiated by 'uncharacterized protein' or not. Records that have 'uncharacterized protein' only need to have 2 trailing columns removed, while other records need to have 3 trailing columns removed. Parse the id from the first column: split($1,b,"."); id=b[2]; Remove unwanted columns: $1=""; $2=""; $3=""; $(NF)=""; $(NF-1)=""; $(NF-2)=""; OR $1=""; $2=""; $3=""; $(NF)=""; $(NF-1)=""; (if uncharacterized protein). Clean the description by removing 'description=': gsub("description=",""); A: Here's a simple sed script: sed -n '/^>[^0-9]*\([0-9][0-9]*\).*description=/\1\t/p' test.fasta The same could easily be recast into Awk, though it's arguably less elegant. awk -F . 'BEGIN { OFS="\t" } /^>/ { d=$0; sub(/.*description=/, "", d); print $2, d }' test.fasta which assumes the interesting part of the ID is between the first and second dots always, and avoids the useless grep. (The sed variant assumes the first sequence of digits on the line is the ID. It alse requires that your sed interprets \t as a literal tab, which isn't entirely portable.) I had to guess some requirements; if my guesses are wrong, please edit your question to clarify exactly how the numeric ID should be extracted, for example.
Output specific fields using bash
I have a test.fasta file with the following data: >PPP.0124.1.PC lib=RU01 length=410 description=Protein description goes here 1 serine/threonine MLEAPKFTGIIGLNNNHDNYDLSQGFYHKLGEGSNMSIDSFGSLQLSNGG GSVAMSVSSVGSNDSHTRILNHQGLKRVNGNYSVARSVNRGKVSHGLSDD ALAQ >PPP.14552.PC lib=RU01 length=104 description=Protein description goes here 2 uncharacterized protein LOC11441 MKSVVGMVVSNKMQKSVVVAVDRLFHHKLYDRYVKRTSKFMAHDEHNLCN IGDRVRL >PPP.94014.PC lib=RU01 length=206 description=Protein description goes here 3 some more chemicals and stuff MDLGPTLTLQKGRQRRGKGPYAGVRSRGGRWVSEIRIPKTKTRIWLGSHH SPEKAARAYDAALYCLKGEHGSFNFPNNRGPYLANRSVGSLPVDEIQCIA AEFSCFDDSA I would like to take the ID and the description and output them into a .tsv file, with the first column being the ID and the second column holding the description. Desired output: | ID | Description | | -------- | -------------- | | 0124 | Protein description goes here 1 serine/threonine | | 14552 | Protein description goes here 2 uncharacterized protein LOC11441 | | 94014 | Protein description goes here 3 some more chemicals and stuff | Any ideas on a one-line Bash command to achieve this? I currently have this: grep -a '^>' test.fasta | awk '{print $1} which gives me the first lines and the ID's but cant seem to figure out the rest!
[ "You can use the following one-line bash command to extract the IDs and descriptions from your test.fasta file and output them in a tab-separated values (TSV) format:\ngrep -a '^>' test.fasta | awk '{gsub(/^>/, \"\"); print $1 \"\\t\" $2}'\n\n", "Using awk:\nawk 'BEGIN{print \"id\\tdescription\"} \\\n/.PC / && !/uncharac/ { \\\nsplit($1,b,\".\"); id=b[2]; \\\n$1=\"\"; $2=\"\"; $3=\"\"; $(NF)=\"\"; $(NF-1)=\"\"; $(NF-2)=\"\"; \\\ngsub(\"description=\",\"\"); print id\"\\t\"$0} \\\n/.PC / && /uncharac/ { \\\nsplit($1,b,\".\"); id=b[2]; \\\n$1=\"\"; $2=\"\"; $3=\"\"; $(NF)=\"\"; $(NF-1)=\"\"; \\\ngsub(\"description=\",\"\"); print id\"\\t\"$0}' test.fasta\n\nid description\n0124 Protein description goes here 1 || serine/threonine \n14552 Protein description goes here 2 || uncharacterized protein LOC11441 \n94014 UProtein description goes here 3 || some more chemicals and stuff \n\nSince the description can span n columns, you need to remove 'known', unwanted columns. In your test data there seem to be records that can be differentiated by 'uncharacterized protein' or not. Records that have 'uncharacterized protein' only need to have 2 trailing columns removed, while other records need to have 3 trailing columns removed.\nParse the id from the first column: split($1,b,\".\"); id=b[2];\nRemove unwanted columns: $1=\"\"; $2=\"\"; $3=\"\"; $(NF)=\"\"; $(NF-1)=\"\"; $(NF-2)=\"\"; OR $1=\"\"; $2=\"\"; $3=\"\"; $(NF)=\"\"; $(NF-1)=\"\"; (if uncharacterized protein).\nClean the description by removing 'description=': gsub(\"description=\",\"\");\n", "Here's a simple sed script:\nsed -n '/^>[^0-9]*\\([0-9][0-9]*\\).*description=/\\1\\t/p' test.fasta\n\nThe same could easily be recast into Awk, though it's arguably less elegant.\nawk -F . 'BEGIN { OFS=\"\\t\" }\n /^>/ { d=$0; sub(/.*description=/, \"\", d); print $2, d }' test.fasta\n\nwhich assumes the interesting part of the ID is between the first and second dots always, and avoids the useless grep.\n(The sed variant assumes the first sequence of digits on the line is the ID. It alse requires that your sed interprets \\t as a literal tab, which isn't entirely portable.)\nI had to guess some requirements; if my guesses are wrong, please edit your question to clarify exactly how the numeric ID should be extracted, for example.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "bash", "fasta" ]
stackoverflow_0074672925_bash_fasta.txt
Q: How to refer to an enum from another Module in VB I declare an enum in a Module: friend Module M Enum E Elem1 Elem2 end Enum end Module and use it in another class: Class C console.writeline(M.E.Elem1) ' this works End Class But I would like to simplify the writing of M.E to MyE so I tried: Class C private myE as M.E ' and variations of this using getype console.writeline(myE.Elem1) end Class Is there a way to do this? That is, declare myE as M.E. I tried variations using getype but no success. A: You can use import alias to simplify the name of any type or namespace. In your case: Imports myE = M.E Class C Public Sub Test() Console.WriteLine(myE.Elem1) End Sub End Class Just don't forget that Imports statements must be placed at the beginning of the file.
How to refer to an enum from another Module in VB
I declare an enum in a Module: friend Module M Enum E Elem1 Elem2 end Enum end Module and use it in another class: Class C console.writeline(M.E.Elem1) ' this works End Class But I would like to simplify the writing of M.E to MyE so I tried: Class C private myE as M.E ' and variations of this using getype console.writeline(myE.Elem1) end Class Is there a way to do this? That is, declare myE as M.E. I tried variations using getype but no success.
[ "You can use import alias to simplify the name of any type or namespace. In your case:\nImports myE = M.E\n\nClass C\n\n Public Sub Test()\n Console.WriteLine(myE.Elem1)\n End Sub\n\nEnd Class\n\nJust don't forget that Imports statements must be placed at the beginning of the file.\n" ]
[ 1 ]
[]
[]
[ "enums", "vb.net" ]
stackoverflow_0074673986_enums_vb.net.txt
Q: WSL Ubuntu 20.04, The command 'docker' could not be found in this WSL 2 distro I'm having an issue with running Docker commands in Ubuntu 20.04 on WSL. I followed the official documentation to setup Docker and run it with Ubuntu on WSL distribution. Now, I want to do the same in another distribution, Ubuntu 20.04. Here is what I have tried so far: Using PowerShell with admin privileges, Ubuntu 20.04 is shown and set as the default, according to the Docker docs: wsl.exe -l -v wsl.exe --set-version Ubuntu-20.04 2 wsl.exe --set-default-version 2 With Docker desktop application, Resources --> WSL Integration, Ubuntu-20.04 is added and Docker restarted and shown as active. In the regular Ubuntu WSL distribution, I get the following: george@DESKTOP-P9I14LM:~$ ls -l /mnt/wsl/docker-desktop/cli-tools/usr/bin total 158574 -rwxr-xr-x 1 root root 60513128 May 12 2022 com.docker.cli -rwxr-xr-x 1 root root 60178432 May 31 2022 docker -rwxr-xr-x 1 root root 6348800 May 31 2022 docker-compose -rwxr-xr-x 1 root root 12737304 May 31 2022 docker-compose-v1 -rwxrwxr-x 1 root root 9395712 May 31 2022 docker-credential-desktop.exe -rwxr-xr-x 1 root root 13205504 May 31 2022 hub-tool While on Ubuntu-20.04 I get No such file or directory. On Ubuntu 20.04: george@DESKTOP-P9I14LM:~$ ls -la /usr/bin/docker lrwxrwxrwx 1 root root 48 Dec 4 12:52 /usr/bin/docker -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker george@DESKTOP-P9I14LM:~$ ls /mnt/wsl/docker-desktop/cli-tools/usr/bin/ ls: cannot access '/mnt/wsl/docker-desktop/cli-tools/usr/bin/': No such file or directory Am not familiar with this kind of issues, so please let me know in comments if there is any missing info I should add.
WSL Ubuntu 20.04, The command 'docker' could not be found in this WSL 2 distro
I'm having an issue with running Docker commands in Ubuntu 20.04 on WSL. I followed the official documentation to setup Docker and run it with Ubuntu on WSL distribution. Now, I want to do the same in another distribution, Ubuntu 20.04. Here is what I have tried so far: Using PowerShell with admin privileges, Ubuntu 20.04 is shown and set as the default, according to the Docker docs: wsl.exe -l -v wsl.exe --set-version Ubuntu-20.04 2 wsl.exe --set-default-version 2 With Docker desktop application, Resources --> WSL Integration, Ubuntu-20.04 is added and Docker restarted and shown as active. In the regular Ubuntu WSL distribution, I get the following: george@DESKTOP-P9I14LM:~$ ls -l /mnt/wsl/docker-desktop/cli-tools/usr/bin total 158574 -rwxr-xr-x 1 root root 60513128 May 12 2022 com.docker.cli -rwxr-xr-x 1 root root 60178432 May 31 2022 docker -rwxr-xr-x 1 root root 6348800 May 31 2022 docker-compose -rwxr-xr-x 1 root root 12737304 May 31 2022 docker-compose-v1 -rwxrwxr-x 1 root root 9395712 May 31 2022 docker-credential-desktop.exe -rwxr-xr-x 1 root root 13205504 May 31 2022 hub-tool While on Ubuntu-20.04 I get No such file or directory. On Ubuntu 20.04: george@DESKTOP-P9I14LM:~$ ls -la /usr/bin/docker lrwxrwxrwx 1 root root 48 Dec 4 12:52 /usr/bin/docker -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker george@DESKTOP-P9I14LM:~$ ls /mnt/wsl/docker-desktop/cli-tools/usr/bin/ ls: cannot access '/mnt/wsl/docker-desktop/cli-tools/usr/bin/': No such file or directory Am not familiar with this kind of issues, so please let me know in comments if there is any missing info I should add.
[]
[]
[ "I would recommend you to install Virtual Box and download an Ubuntu virtual machine there. You would save yourself a lot of trouble.\n" ]
[ -2 ]
[ "docker", "powershell", "windows", "windows_subsystem_for_linux" ]
stackoverflow_0074674614_docker_powershell_windows_windows_subsystem_for_linux.txt
Q: Pass variables inside render to outside? It seems impossible for the outside caller to use any variable inside a render? Take this for example: test.liquid: {% assign test_xyz = '123abc' %} template.liquid: {% render 'test' %} {{ test_xyz }} Which outputs nothing. How can the outside use variables inside render? Can render return anything? Or is it not possible in Shopify any more since include has been deprecated? A: How can the outside use variables inside render? It can't. That would violate encapsulation. When a partial template is rendered, the code inside it can’t access its parent’s variables and its variables won’t be accessible by its parent. This encapsulation makes partials easier to understand and maintain. Can render return anything? Unfortunately not. But maybe we are doing a mistake by thinking about render tag as of a function (which doesn't exist). My guess is that Shopify is trying its best to simplify liquid as much as possible, thus making server side rendering faster. Or is it not possible in Shopify any more since include has been deprecated? include tag is deprecated already for around 3 years already and it still can be used as there are no plans for removing it (at least I could not find any announcement stating that). It definitely affects the publishing process though, if you'd like to sell your theme in market place. The best option is to rethink the theme structure I guess.
Pass variables inside render to outside?
It seems impossible for the outside caller to use any variable inside a render? Take this for example: test.liquid: {% assign test_xyz = '123abc' %} template.liquid: {% render 'test' %} {{ test_xyz }} Which outputs nothing. How can the outside use variables inside render? Can render return anything? Or is it not possible in Shopify any more since include has been deprecated?
[ "\nHow can the outside use variables inside render?\n\nIt can't. That would violate encapsulation. When a partial template is rendered, the code inside it can’t access its parent’s variables and its variables won’t be accessible by its parent. This encapsulation makes partials easier to understand and maintain.\n\nCan render return anything?\n\nUnfortunately not. But maybe we are doing a mistake by thinking about render tag as of a function (which doesn't exist). My guess is that Shopify is trying its best to simplify liquid as much as possible, thus making server side rendering faster.\n\nOr is it not possible in Shopify any more since include has been deprecated?\n\ninclude tag is deprecated already for around 3 years already and it still can be used as there are no plans for removing it (at least I could not find any announcement stating that). It definitely affects the publishing process though, if you'd like to sell your theme in market place. The best option is to rethink the theme structure I guess.\n" ]
[ 1 ]
[]
[]
[ "liquid", "shopify" ]
stackoverflow_0074672545_liquid_shopify.txt
Q: Where and how do you store your access_token and refresh_token in Oauth2.0 authorization flow How should access and refresh tokens obtained from the Twitter API v2 be stored and used in a secure manner? I can't just store access_token and refresh_token alone, right? I will need some kind of identifier. And probably save that identifier in the client. Are there any recommended approaches or best practices for this? I would appreciate any guidance. A: To create a unique identifier for a user in a secure manner, you can generate a random string using a cryptographically secure function such as crypto.randomBytes in Node.js or secrets.token_hex in Python. For example, in Node.js you could generate a secure identifier like this: THIS IS JS EXAMPLE const crypto = require("crypto"); function generateIdentifier() { return crypto.randomBytes(8).toString("hex"); } To save the refresh token securely on the client-side, you can use a browser feature such as the Web Storage API or IndexedDB to store the refresh token in the user's browser. This will prevent the refresh token from being accessed by unauthorized parties, and will allow you to retrieve the refresh token whenever it is needed, such as when refreshing the access token function saveRefreshToken(identifier, refreshToken) { localStorage.setItem(`refreshToken-${identifier}`, refreshToken); } t is important to note that the Web Storage API and other browser storage mechanisms are not always secure, and can be accessed by other scripts or applications on the user's device. If you need to store sensitive information, you should consider using a more secure method, such as encrypting the refresh token and storing it in a secure database A: Here's some info from the OWASP JWT for Java Cheatsheet (the example code they have is in Javascript). Store the token using the browser sessionStorage container, or use JavaScript closures with private variables Add it as a Bearer HTTP Authentication header with JavaScript when calling services. Add fingerprint information to the token. or (4). An alternative to storing token in browser sessionStorage is to use JavaScript private variable or Closures. In this, access to all web requests are routed through a JavaScript module that encapsulates the token in a private variable which can not be accessed other than from within the module. And here are the implementation examples. /* Handle request for JWT token and local storage*/ function authenticate() { const login = $("#login").val(); const postData = "login=" + encodeURIComponent(login) + "&password=test"; $.post("/services/authenticate", postData, function (data) { if (data.status == "Authentication successful!") { ... sessionStorage.setItem("token", data.token); } else { ... sessionStorage.removeItem("token"); } }) .fail(function (jqXHR, textStatus, error) { ... sessionStorage.removeItem("token"); }); } /* Handle request for JWT token validation */ function validateToken() { var token = sessionStorage.getItem("token"); if (token == undefined || token == "") { $("#infoZone").removeClass(); $("#infoZone").addClass("alert alert-warning"); $("#infoZone").text("Obtain a JWT token first :)"); return; } $.ajax({ url: "/services/validate", type: "POST", beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "bearer " + token); }, success: function (data) { ... }, error: function (jqXHR, textStatus, error) { ... }, }); } function myFetchModule() { // Protect the original 'fetch' from getting overwritten via XSS const fetch = window.fetch; const authOrigins = ["https://yourorigin", "http://localhost"]; let token = ''; this.setToken = (value) => { token = value } this.fetch = (resource, options) => { let req = new Request(resource, options); destOrigin = new URL(req.url).origin; if (token && authOrigins.includes(destOrigin)) { req.headers.set('Authorization', token); } return fetch(req) } } ... // usage: const myFetch = new myFetchModule() function login() { fetch("/api/login") .then((res) => { if (res.status == 200) { return res.json() } else { throw Error(res.statusText) } }) .then(data => { myFetch.setToken(data.token) console.log("Token received and stored.") }) .catch(console.error) } ... // after login, subsequent api calls: function makeRequest() { myFetch.fetch("/api/hello", {headers: {"MyHeader": "foobar"}}) .then((res) => { if (res.status == 200) { return res.text() } else { throw Error(res.statusText) } }).then(responseText => console.log("helloResponse", responseText)) .catch(console.error) } Hope this helps!
Where and how do you store your access_token and refresh_token in Oauth2.0 authorization flow
How should access and refresh tokens obtained from the Twitter API v2 be stored and used in a secure manner? I can't just store access_token and refresh_token alone, right? I will need some kind of identifier. And probably save that identifier in the client. Are there any recommended approaches or best practices for this? I would appreciate any guidance.
[ "To create a unique identifier for a user in a secure manner, you can generate a random string using a cryptographically secure function such as crypto.randomBytes in Node.js or secrets.token_hex in Python. For example, in Node.js you could generate a secure identifier like this:\nTHIS IS JS EXAMPLE\nconst crypto = require(\"crypto\");\n\nfunction generateIdentifier() {\n return crypto.randomBytes(8).toString(\"hex\");\n}\n\nTo save the refresh token securely on the client-side, you can use a browser feature such as the Web Storage API or IndexedDB to store the refresh token in the user's browser. This will prevent the refresh token from being accessed by unauthorized parties, and will allow you to retrieve the refresh token whenever it is needed, such as when refreshing the access token\nfunction saveRefreshToken(identifier, refreshToken) {\n localStorage.setItem(`refreshToken-${identifier}`, refreshToken);\n}\n\nt is important to note that the Web Storage API and other browser storage mechanisms are not always secure, and can be accessed by other scripts or applications on the user's device. If you need to store sensitive information, you should consider using a more secure method, such as encrypting the refresh token and storing it in a secure database\n", "Here's some info from the OWASP JWT for Java Cheatsheet (the example code they have is in Javascript).\n\n\nStore the token using the browser sessionStorage container, or use JavaScript closures with private variables\nAdd it as a Bearer HTTP Authentication header with JavaScript when calling services.\nAdd fingerprint information to the token.\n\n\nor\n\n(4). An alternative to storing token in browser sessionStorage is to use JavaScript private variable or Closures. In this, access to all web requests are routed through a JavaScript module that encapsulates the token in a private variable which can not be accessed other than from within the module.\nAnd here are the implementation examples.\n\n\n\n/* Handle request for JWT token and local storage*/\nfunction authenticate() {\n const login = $(\"#login\").val();\n const postData = \"login=\" + encodeURIComponent(login) + \"&password=test\";\n\n $.post(\"/services/authenticate\", postData, function (data) {\n if (data.status == \"Authentication successful!\") {\n ...\n sessionStorage.setItem(\"token\", data.token);\n }\n else {\n ...\n sessionStorage.removeItem(\"token\");\n }\n })\n .fail(function (jqXHR, textStatus, error) {\n ...\n sessionStorage.removeItem(\"token\");\n });\n}\n\n\n\n/* Handle request for JWT token validation */\nfunction validateToken() {\n var token = sessionStorage.getItem(\"token\");\n\n if (token == undefined || token == \"\") {\n $(\"#infoZone\").removeClass();\n $(\"#infoZone\").addClass(\"alert alert-warning\");\n $(\"#infoZone\").text(\"Obtain a JWT token first :)\");\n return;\n }\n\n $.ajax({\n url: \"/services/validate\",\n type: \"POST\",\n beforeSend: function (xhr) {\n xhr.setRequestHeader(\"Authorization\", \"bearer \" + token);\n },\n success: function (data) {\n ...\n },\n error: function (jqXHR, textStatus, error) {\n ...\n },\n });\n}\n\n\n\nfunction myFetchModule() {\n // Protect the original 'fetch' from getting overwritten via XSS\n const fetch = window.fetch;\n\n const authOrigins = [\"https://yourorigin\", \"http://localhost\"];\n let token = '';\n\n this.setToken = (value) => {\n token = value\n }\n\n this.fetch = (resource, options) => {\n let req = new Request(resource, options);\n destOrigin = new URL(req.url).origin;\n if (token && authOrigins.includes(destOrigin)) {\n req.headers.set('Authorization', token);\n }\n return fetch(req)\n }\n}\n\n...\n\n// usage:\nconst myFetch = new myFetchModule()\n\nfunction login() {\n fetch(\"/api/login\")\n .then((res) => {\n if (res.status == 200) {\n return res.json()\n } else {\n throw Error(res.statusText)\n }\n })\n .then(data => {\n myFetch.setToken(data.token)\n console.log(\"Token received and stored.\")\n })\n .catch(console.error)\n}\n\n...\n\n// after login, subsequent api calls:\nfunction makeRequest() {\n myFetch.fetch(\"/api/hello\", {headers: {\"MyHeader\": \"foobar\"}})\n .then((res) => {\n if (res.status == 200) {\n return res.text()\n } else {\n throw Error(res.statusText)\n }\n }).then(responseText => console.log(\"helloResponse\", responseText))\n .catch(console.error)\n}\n\n\n\nHope this helps!\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "oauth_2.0", "twitter", "twitter_oauth" ]
stackoverflow_0074673484_javascript_oauth_2.0_twitter_twitter_oauth.txt
Q: Switching Values in Dataframe with Lambda expression I have a dataframe with 3 columns For each TicketID, I want to iterate through all the other rows in the dataframe, searching for the TicketID as a String somewhere within the TicketStatus. If we find a match for the ticketID within another row's TicketStatus, we will switch the Odds fields for that matching pair. Example input: TicketID, Odds, TicketStatus 123456, 4.0, 'Hello' 654799, 11.0, 'Yes 123456' Example output: TicketID, Odds, TicketStatus 123456, 11.0, 'Hello' 654799, 4.0, 'Yes 123456' df['Odds'] = df.apply(lambda x: df.loc[df['TicketStatus'].str.contains(x['TicketID']), 'Odds'].values[0] if df['TicketStatus'].str.contains(x['TicketID']).any() else x['Odds'], axis=1) I'm returning a TypeError: first argument must be string or compiled pattern, but can't figure out what I'm doing wrong. A: You can iterate through the rows of the dataframe and use the str.contains() method to check if the TicketStatus of a row contains a given TicketID. If a match is found, you can update the Odds value for both rows. Here is an example implementation: import pandas as pd # define the function that will be applied to each row in the dataframe def switch_odds(row): # get the current TicketID and Odds for the current row ticket_id = row['TicketID'] odds = row['Odds'] # search for matches of the current TicketID in the TicketStatus of other rows matches = df[df['TicketStatus'].str.contains(ticket_id)] # iterate through the matching rows for match in matches.itertuples(): # get the index of the matching row index = match.Index # switch the Odds values for the current row and the matching row df.loc[index, 'Odds'] = odds df.loc[row.name, 'Odds'] = match.Odds # load the data into a dataframe df = pd.DataFrame([ [123456, 4.0, 'Hello'], [654799, 11.0, 'Yes 123456'] ], columns=['TicketID', 'Odds', 'TicketStatus']) # apply the function to each row in the dataframe df.apply(switch_odds, axis=1)
Switching Values in Dataframe with Lambda expression
I have a dataframe with 3 columns For each TicketID, I want to iterate through all the other rows in the dataframe, searching for the TicketID as a String somewhere within the TicketStatus. If we find a match for the ticketID within another row's TicketStatus, we will switch the Odds fields for that matching pair. Example input: TicketID, Odds, TicketStatus 123456, 4.0, 'Hello' 654799, 11.0, 'Yes 123456' Example output: TicketID, Odds, TicketStatus 123456, 11.0, 'Hello' 654799, 4.0, 'Yes 123456' df['Odds'] = df.apply(lambda x: df.loc[df['TicketStatus'].str.contains(x['TicketID']), 'Odds'].values[0] if df['TicketStatus'].str.contains(x['TicketID']).any() else x['Odds'], axis=1) I'm returning a TypeError: first argument must be string or compiled pattern, but can't figure out what I'm doing wrong.
[ "You can iterate through the rows of the dataframe and use the str.contains() method to check if the TicketStatus of a row contains a given TicketID. If a match is found, you can update the Odds value for both rows.\nHere is an example implementation:\nimport pandas as pd\n\n# define the function that will be applied to each row in the dataframe\ndef switch_odds(row):\n # get the current TicketID and Odds for the current row\n ticket_id = row['TicketID']\n odds = row['Odds']\n\n # search for matches of the current TicketID in the TicketStatus of other rows\n matches = df[df['TicketStatus'].str.contains(ticket_id)]\n\n # iterate through the matching rows\n for match in matches.itertuples():\n # get the index of the matching row\n index = match.Index\n\n # switch the Odds values for the current row and the matching row\n df.loc[index, 'Odds'] = odds\n df.loc[row.name, 'Odds'] = match.Odds\n\n# load the data into a dataframe\ndf = pd.DataFrame([\n [123456, 4.0, 'Hello'],\n [654799, 11.0, 'Yes 123456']\n], columns=['TicketID', 'Odds', 'TicketStatus'])\n\n# apply the function to each row in the dataframe\ndf.apply(switch_odds, axis=1)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "lambda", "python" ]
stackoverflow_0074674843_dataframe_lambda_python.txt
Q: primeng how to inline style checkbox? How can I use the style input of p-checkbox to change the border and background color of a checkbox? I already tried [style]="{'background': '#ff0000'}". But this only applies the style to the div which holds the actual checkbox. So its useless. Instead I need to change the border-color and background of the div which has the classes p-checkbox-box and p-highlight. Note: I cant use CSS here because the colors are dynamic and dependant on the content. A: You can use renderer2 to manipulate DOM elements and then add style: Get all checkboxes using document.getElementsByClassName('p-checkbox-box') Iterate over each element and add the style you want using renderer2.setStyle() try this piece of code and add it in ngAfterViewInit(): let chkboxes = document.getElementsByClassName('p-checkbox-box') for (let index = 0; index < chkboxes.length; index++) { const element = chkboxes[index]; this._renderer2.setStyle(element,'background-color','#bf2222'); this._renderer2.setStyle(element,'border-color','#bf2222'); } A: To inline style the p-checkbox component, you can use the [ngStyle] input to bind the desired styles to the component. This will apply the styles directly to the element, rather than to a parent element. For example, to change the border and background color of a p-checkbox, you can use the following code: <p-checkbox [ngStyle]="{'border-color': '#ff0000', 'background-color': '#ff0000'}"></p-checkbox> The [ngStyle] input accepts an object of CSS styles and their corresponding values, which will be applied to the element. In this case, we are setting the border and background color to red. You can also use interpolation to dynamically set the styles based on a variable or expression, like this: <p-checkbox [ngStyle]="{'border-color': myBorderColor, 'background-color': myBackgroundColor}"></p-checkbox> Where myBorderColor and myBackgroundColor are variables or expressions that resolve to the desired color values. Note that you may need to use the classes p-checkbox-box and p-highlight to target the specific elements within the p-checkbox component that you want to style. <p-checkbox [ngStyle]="{'.p-checkbox-box': {'border-color': '#ff0000'}, '.p-highlight': {'background-color': '#ff0000'}}"></p-checkbox> This will apply the styles to the elements with the specified classes within the p-checkbox component.
primeng how to inline style checkbox?
How can I use the style input of p-checkbox to change the border and background color of a checkbox? I already tried [style]="{'background': '#ff0000'}". But this only applies the style to the div which holds the actual checkbox. So its useless. Instead I need to change the border-color and background of the div which has the classes p-checkbox-box and p-highlight. Note: I cant use CSS here because the colors are dynamic and dependant on the content.
[ "You can use renderer2 to manipulate DOM elements and then add style:\n\nGet all checkboxes using document.getElementsByClassName('p-checkbox-box')\n\nIterate over each element and add the style you want using renderer2.setStyle()\n\n\ntry this piece of code and add it in ngAfterViewInit():\n let chkboxes = document.getElementsByClassName('p-checkbox-box')\n for (let index = 0; index < chkboxes.length; index++) {\n const element = chkboxes[index];\n this._renderer2.setStyle(element,'background-color','#bf2222');\n this._renderer2.setStyle(element,'border-color','#bf2222');\n }\n\n", "To inline style the p-checkbox component, you can use the [ngStyle] input to bind the desired styles to the component. This will apply the styles directly to the element, rather than to a parent element.\nFor example, to change the border and background color of a p-checkbox, you can use the following code:\n<p-checkbox [ngStyle]=\"{'border-color': '#ff0000', 'background-color': '#ff0000'}\"></p-checkbox>\n\nThe [ngStyle] input accepts an object of CSS styles and their corresponding values, which will be applied to the element. In this case, we are setting the border and background color to red.\nYou can also use interpolation to dynamically set the styles based on a variable or expression, like this:\n<p-checkbox [ngStyle]=\"{'border-color': myBorderColor, 'background-color': myBackgroundColor}\"></p-checkbox>\n\nWhere myBorderColor and myBackgroundColor are variables or expressions that resolve to the desired color values.\nNote that you may need to use the classes p-checkbox-box and p-highlight to target the specific elements within the p-checkbox component that you want to style.\n<p-checkbox [ngStyle]=\"{'.p-checkbox-box': {'border-color': '#ff0000'}, '.p-highlight': {'background-color': '#ff0000'}}\"></p-checkbox>\n\nThis will apply the styles to the elements with the specified classes within the p-checkbox component.\n" ]
[ 1, 0 ]
[]
[]
[ "html", "primeng", "primeng_checkbox" ]
stackoverflow_0074659078_html_primeng_primeng_checkbox.txt
Q: List of available Svelte live templates "code snippets" in JetBrains IDEs I am using JetBrains IDEs (PyCharm, WebStorm, etc.) to edit Svelte components with .svelte file extension. The plugin https://plugins.jetbrains.com/plugin/12375-svelte clearly offers some live code templates. If I type if and press Tab it expands it to {#if }{/if}. However, I could not find on the plugin page or in the IDE settings itself the list of what autocompletes are supported and what are the keywords. Would anyone with more JetBrains IDE experience give a hint? A: As per LazyOne's suggetion you can see some of templates if you type {# (the marker of Svelte template directive) and press Ctrl + Space / Cmd + Space There are not many of them according to this.
List of available Svelte live templates "code snippets" in JetBrains IDEs
I am using JetBrains IDEs (PyCharm, WebStorm, etc.) to edit Svelte components with .svelte file extension. The plugin https://plugins.jetbrains.com/plugin/12375-svelte clearly offers some live code templates. If I type if and press Tab it expands it to {#if }{/if}. However, I could not find on the plugin page or in the IDE settings itself the list of what autocompletes are supported and what are the keywords. Would anyone with more JetBrains IDE experience give a hint?
[ "As per LazyOne's suggetion you can see some of templates if you type {# (the marker of Svelte template directive) and press Ctrl + Space / Cmd + Space\n\nThere are not many of them according to this.\n" ]
[ 0 ]
[]
[]
[ "jetbrains_ide", "pycharm", "svelte", "webstorm" ]
stackoverflow_0074648110_jetbrains_ide_pycharm_svelte_webstorm.txt
Q: How do I remove tag and its content from HTML using php Below is the text I need to remove <p> tags from <p> Addiction, stress and subjective wellbeing</p> <p> The need and significance of traditional shop lot pavements in the context of town conservation in Malaysia</p> <p> The role of wage and benefit in engaging employee commitment</p> I tried this $title= preg_replace('#<p>(.*?)</p>#', '', $title['result']);** But still am Getting <p> tags, any ideas? A: You must use this regular expression to catch <p> tag and all of its content: '/<p\b[^>]*>(.*?)<\/p>/i' Working example to catch and remove <p> tag and all of its content: $title = "<div>Text to keep<p class='classExample'>Text to remove</p></div>"; $result = preg_replace('/<p\b[^>]*>(.*?)<\/p>/i', '', $title); echo $result; Please see live demo on Codepad If you want to use regular expressions to parse HTML - then you will not be able to do this. Read more about your matter here: How do you parse and process HTML/XML in PHP? A: just to remove p tags you can do this $text=str_ireplace('<p>','',$text); $text=str_ireplace('</p>','',$text); A: Try: If you want to remove <p> tag only $html = " <p> Addiction, stress and subjective wellbeing</p> <p> The need and significance of traditional shop lot pavements town</p> <p> The role of wage and benefit in engaging employee commitment</p> "; echo strip_tags($html); If you want to remove <p> tags and its content $html = preg_replace('#\<p>[{\w},\s\d"]+\</p>#', "", $html); A: echo "<div id=\"main_content\">" . strip_tags($row[main_content]) . "</div>"; A: If you just need to strip all the markup, go with strip_tags(). A: $text = '<p>Test paragraph.</p> <a href="#fragment">Other text</a>'; echo strip_tags($text); echo "\n"; // Allow p and a tag echo strip_tags($text, '<p><a>'); A: This code removes one p-tag: function parse($html) { $dom = new DOMDocument(); @$dom->loadHTML($html); $ps = $dom->getElementsByTagName('p'); //die('<pre>'.print_r($ps,1).'</pre>'); if ($ps->length === 1){ $p = $ps->item(0); return $p->nodeValue; } else { return ''; } } A: Here is another example to strip all <p> tags with or without the closing / after the first < $content = '<p> Addiction, stress and subjective wellbeing</p> <p> The need and significance of traditional shop lot pavements in the context of town conservation in Malaysia</p> <p> The role of wage and benefit in engaging employee commitment</p>'; $new_content = preg_replace('/<(|\/)p>/', '', $content); dump($new_content); die('HERE');
How do I remove tag and its content from HTML using php
Below is the text I need to remove <p> tags from <p> Addiction, stress and subjective wellbeing</p> <p> The need and significance of traditional shop lot pavements in the context of town conservation in Malaysia</p> <p> The role of wage and benefit in engaging employee commitment</p> I tried this $title= preg_replace('#<p>(.*?)</p>#', '', $title['result']);** But still am Getting <p> tags, any ideas?
[ "You must use this regular expression to catch <p> tag and all of its content:\n'/<p\\b[^>]*>(.*?)<\\/p>/i'\n\nWorking example to catch and remove <p> tag and all of its content:\n$title = \"<div>Text to keep<p class='classExample'>Text to remove</p></div>\";\n$result = preg_replace('/<p\\b[^>]*>(.*?)<\\/p>/i', '', $title);\necho $result;\n\nPlease see live demo on Codepad\nIf you want to use regular expressions to parse HTML - then you will not be able to do this.\nRead more about your matter here: How do you parse and process HTML/XML in PHP?\n", "just to remove p tags you can do this \n$text=str_ireplace('<p>','',$text);\n$text=str_ireplace('</p>','',$text); \n\n", "Try:\nIf you want to remove <p> tag only\n$html = \"\n<p> Addiction, stress and subjective wellbeing</p> \n<p> The need and significance of traditional shop lot pavements town</p> \n<p> The role of wage and benefit in engaging employee commitment</p>\n\";\n\necho strip_tags($html);\n\nIf you want to remove <p> tags and its content\n$html = preg_replace('#\\<p>[{\\w},\\s\\d\"]+\\</p>#', \"\", $html);\n\n", "echo \"<div id=\\\"main_content\\\">\" . strip_tags($row[main_content]) . \"</div>\";\n\n", "If you just need to strip all the markup, go with strip_tags().\n", "$text = '<p>Test paragraph.</p> <a href=\"#fragment\">Other text</a>';\necho strip_tags($text);\necho \"\\n\";\n\n// Allow p and a tag\necho strip_tags($text, '<p><a>');\n\n", "This code removes one p-tag:\nfunction parse($html) {\n $dom = new DOMDocument();\n @$dom->loadHTML($html);\n $ps = $dom->getElementsByTagName('p');\n //die('<pre>'.print_r($ps,1).'</pre>');\n if ($ps->length === 1){\n $p = $ps->item(0);\n return $p->nodeValue;\n } else {\n return '';\n }\n}\n\n", "Here is another example to strip all <p> tags with or without the closing / after the first <\n$content = '<p> Addiction, stress and subjective wellbeing</p>\n<p> The need and significance of traditional shop lot pavements in the context of town conservation in Malaysia</p>\n<p> The role of wage and benefit in engaging employee commitment</p>';\n $new_content = preg_replace('/<(|\\/)p>/', '', $content);\n dump($new_content);\n die('HERE');\n\n\n\n" ]
[ 21, 6, 6, 3, 2, 2, 0, 0 ]
[]
[]
[ "html", "php" ]
stackoverflow_0012130966_html_php.txt
Q: MFC CEdit placeholder text How do I have a CEdit control display placeholder text when it's empty, similar to the behavior of NSTextFields in Cocoa? A: Ages ago, I wrote a custom paint routine to do it, seemed to work fine. Sometime after, they introduced SetCueBanner to CEdit, but I can remember it: a) not working correctly or - b) not behaving the way I wanted Perhaps it will work fine for you. If not, I can see if I can find my old code and post what I did in the custom paint routine. EDIT I just checked the Win32 docs, I think this is why I abandoned it: You cannot set a cue banner on a multiline edit control A: you could create a small window over the top of it that contains the placeholder text. Then when the user sets the keyboard focus to it hide the window and if the focus is removed and nothing is in the box then show it. A: The SetCueBanner banner function is now working.
MFC CEdit placeholder text
How do I have a CEdit control display placeholder text when it's empty, similar to the behavior of NSTextFields in Cocoa?
[ "Ages ago, I wrote a custom paint routine to do it, seemed to work fine.\nSometime after, they introduced SetCueBanner to CEdit, but I can remember it:\na) not working correctly\n\nor -\n\nb) not behaving the way I wanted\nPerhaps it will work fine for you. If not, I can see if I can find my old code and post what I did in the custom paint routine.\nEDIT\nI just checked the Win32 docs, I think this is why I abandoned it:\nYou cannot set a cue banner on a multiline edit control\n", "you could create a small window over the top of it that contains the placeholder text. Then when the user sets the keyboard focus to it hide the window and if the focus is removed and nothing is in the box then show it.\n", "The SetCueBanner banner function is now working.\n" ]
[ 5, 0, 0 ]
[]
[]
[ "mfc" ]
stackoverflow_0001306791_mfc.txt
Q: white line in PNG images in Unity I am currently making a simple game, but my assets even though they are png and there are no lines or anything with them before I export them, they keep having white lines when I put them in Unity. The dialog box with white lines in Unity This is the dialog box when viewed from the png file or from the resources There is also one image tho it does not have any white line, it does have white edges in Unity The phone asset in Unity This is the phone when viewed from the file manager Here are the import settings of both of the image dialog box import settings phone image import settings What should I do to fix this in Unity? A: I solved my problem by tweaking either the Wrap Mode or the Filter Mode. In the dialog box or in the case of the white lines, when I change the wrap mode to Clamp, Mirror, or Mirror once, the line disappears as well as when changing the filter mode to Point(No filter). In case of the white edges, Wrap Mode has no effect on it, it can only be removed when setting the Filter Mode to Point(No filter).
white line in PNG images in Unity
I am currently making a simple game, but my assets even though they are png and there are no lines or anything with them before I export them, they keep having white lines when I put them in Unity. The dialog box with white lines in Unity This is the dialog box when viewed from the png file or from the resources There is also one image tho it does not have any white line, it does have white edges in Unity The phone asset in Unity This is the phone when viewed from the file manager Here are the import settings of both of the image dialog box import settings phone image import settings What should I do to fix this in Unity?
[ "I solved my problem by tweaking either the Wrap Mode or the Filter Mode.\nIn the dialog box or in the case of the white lines, when I change the wrap mode to Clamp, Mirror, or Mirror once, the line disappears as well as when changing the filter mode to Point(No filter).\nIn case of the white edges, Wrap Mode has no effect on it, it can only be removed when setting the Filter Mode to Point(No filter).\n" ]
[ 0 ]
[]
[]
[ "assets", "image", "png", "unity3d" ]
stackoverflow_0074673320_assets_image_png_unity3d.txt
Q: Use MikroORM migrations with NestJs I'm running into problem using command mikro-orm migration:create. Console shows me Error: MikroORM config file not found in ['./dist/mikro-orm.config.js', './mikro-orm.config.js']. My app.module looks like this: @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), MikroOrmCoreModule.forRootAsync({ useFactory: (configService: ConfigService) => ({ entitiesTs: [`./shared/db/entities`], entities: [`./dist/shared/db/entities`], user: configService.get<string>('DB_NAME'), password: configService.get<string>('DB_PASSWORD'), dbName: configService.get<string>('DB_NAME'), port: configService.get<number>('DB_PORT'), type: 'postgresql', migrations: { tableName: 'migrations', path: `./dist/shared/db/migrations`, pathTs: `./shared/db/entities`, glob: '!(*.d).{js,ts}', transactional: true, allOrNothing: true, emit: 'ts', }, }), inject: [ConfigService], }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} Aslo I've tried to create mikro-orm.config file with same setup, but then console shows me something like Error: No entities discovered. I've tried different ways of define paths in all related fields (entitiesTs, entities, path, pathTs) such as using */__dirname/process.pwd() in path, but it didn't help. A: Keep the configuration only in the mikro-orm.config.ts file, configure the ORM to find it as described in docs (namely the configPaths and useTsNode in your package.json), then you can use this config in your app.module.ts, just import it and spread to the place where you have the options now. Then you can use the npx mikro-orm debug command to check how the paths look for the ORM. import config from './mikro-orm.config'; @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), MikroOrmCoreModule.forRootAsync({ useFactory: (configService: ConfigService) => ({ ...config, }), inject: [ConfigService], }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} This way you get a single source of truth for both the CLI and your app, so you can use the CLI to debug the config easily.
Use MikroORM migrations with NestJs
I'm running into problem using command mikro-orm migration:create. Console shows me Error: MikroORM config file not found in ['./dist/mikro-orm.config.js', './mikro-orm.config.js']. My app.module looks like this: @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true }), MikroOrmCoreModule.forRootAsync({ useFactory: (configService: ConfigService) => ({ entitiesTs: [`./shared/db/entities`], entities: [`./dist/shared/db/entities`], user: configService.get<string>('DB_NAME'), password: configService.get<string>('DB_PASSWORD'), dbName: configService.get<string>('DB_NAME'), port: configService.get<number>('DB_PORT'), type: 'postgresql', migrations: { tableName: 'migrations', path: `./dist/shared/db/migrations`, pathTs: `./shared/db/entities`, glob: '!(*.d).{js,ts}', transactional: true, allOrNothing: true, emit: 'ts', }, }), inject: [ConfigService], }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} Aslo I've tried to create mikro-orm.config file with same setup, but then console shows me something like Error: No entities discovered. I've tried different ways of define paths in all related fields (entitiesTs, entities, path, pathTs) such as using */__dirname/process.pwd() in path, but it didn't help.
[ "Keep the configuration only in the mikro-orm.config.ts file, configure the ORM to find it as described in docs (namely the configPaths and useTsNode in your package.json), then you can use this config in your app.module.ts, just import it and spread to the place where you have the options now. Then you can use the npx mikro-orm debug command to check how the paths look for the ORM.\nimport config from './mikro-orm.config';\n\n@Module({\n imports: [\n ConfigModule.forRoot({ isGlobal: true }),\n MikroOrmCoreModule.forRootAsync({\n useFactory: (configService: ConfigService) => ({\n ...config,\n }),\n inject: [ConfigService],\n }),\n ],\n controllers: [AppController],\n providers: [AppService],\n})\nexport class AppModule {}\n\nThis way you get a single source of truth for both the CLI and your app, so you can use the CLI to debug the config easily.\n" ]
[ 0 ]
[]
[]
[ "mikro_orm", "nestjs" ]
stackoverflow_0074674726_mikro_orm_nestjs.txt
Q: How to use react-query to replace context I read an article on using react-query as a state manager and I am now trying to replace a context in my app with react-query (version 4). Previously, I created a context with useContext() that stored a user account object for the logged-in user. I used react-query to fetch this data, and then useReducer() to modify the account object. However, I realized this is a mess and the relevant data is in react-query anyway, so I should get rid of the context and reducer and just use react-query directly (I am generating the user account object in the query that I make with react-query). I generate the user account object in a custom hook: function useUser(): UseQueryResult<User, Error> { const query = getInitialUserUrl; const platform = usePlatformContext(); return useQuery<User, Error>( queryKeyUseUser, async () => { const data = await fetchAuth(query); if (didQueryReturnData(data)) { return new User(platform, data[0]); } return new User(platform); }, { refetchOnReconnect: 'always', refetchInterval: false, }, ); } export default useUser; Now I have a mutation where I verify the user's email address (old way using context): const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { const { userObject } = useUserContext(); return useMutation( (data: FormEmailVerifyInput) => verifyEmail(userObject.id, data.validation_code), }, ); }; I tried to replace the call to context with a direct call to useUser(): const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { const { data: userObject } = useUser(); return useMutation( (data: FormEmailVerifyInput) => verifyEmail(userObject.id, data.validation_code), }, ); }; However, TypeScript complains that Object is possibly 'undefined' for userObject. I'm not sure why, because as far as I understand, useUser() always returns a User object. How can I update my custom hook to return a User object so that I can use it instead of context? UPDATE I can wrap my useUser() hook in another hook: function useUserObject() { const { data: userObject } = useUser(); if (userObject instanceof User) { return userObject; } throw new Error('Failed to get account info!'); } And then I can do const userObject = useUserObject() to get the user account object... but is this really the optimal way? Do I need to create a custom hook for a custom hook just to use my user objects like I do with useContext()? A: I wrote the article you've mentioned in your question. It is not guaranteed that useQuery returns data when you call it, because data could not be fetched yet or fetching could have failed. Now you might guarantee this in your app because you only call the hook when data has already been fetched - but TypeScript doesn't know that. As stated at the end of the article, this is a tradeoff. What it gives you is that each hook is self-contained. If you call useMutationVerifyEmail in a place where you don't have a user object yet for whatever reason, it will go and try to fetch it. There are various ways to "work around / with" that issue / limitation: You can ignore it and use a type assertion / the bang operator (!) const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { const { data: userObject } = useUser(); return useMutation( (data: FormEmailVerifyInput) => verifyEmail(userObject!.id, data.validation_code), ); }; This might err at runtime if you move the component that uses this hook to a place where a user isn't available, but it's fine if you know that this is the case :) You can check inside the mutationFn as an invariant, and make the mutation error if there is no user: const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { const { data: userObject } = useUser(); return useMutation( async (data: FormEmailVerifyInput) => { if (!userObject) { throw new Error("no user available") } return verifyEmail(userObject.id, data.validation_code) }, ); }; you can move the useUser call out of your custom mutation hook and just make the userId part of the input that is passed to the mutation. const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { return useMutation( ({ id, ...data} : FormEmailVerifyInput & { id: number }) => verifyEmail(id, data.validation_code), ); }; Then, the component can call useQuery, maybe return null, a loading spinner or an error if there is no user, or you can disable the button that triggers the mutation as long as there is no user. You can take a step back and keep your context, but populate it with data from useQuery: const UserProvider = ({ children }) => { const { data } = useUser() if (data.isLoading) return "loading ..." if (data.isError) return "error" return <UserContext.Provider value={data}>{children}</UserContext.Provider> } I might have to write about this pattern some more, because it is not state syncing / duplication. It is also not managing state with react context. All it does is distribute data from react-query via react-context. data is guaranteed to be defined when you read it through useContext(), so it takes away the undefined checks. It will also always give you the "latest" data of react-query, because you still have your subscription via useQuery - just further up the tree. Context consumers will be notified of changes because the value updates. Now there are tradeoffs to this as well, namely: You cannot do partial subscriptions anymore via select, because react-context has no selectors. If you do this with multiple Providers, you risk getting into waterfall fetches: fetching the user "blocks" the rest of the app, because it doesn't render children until the user is fetched. That's why user is defined when accessing it in children (which is desired), but it will also block all other fetches that would happen in the children. I've done this before with something like an EssentialDataProvider. It triggers a bunch of useQuery calls, like user and stack related information that we need everywhere in the app - so it doesn't make sense to render the app without it. We then distribute it via context so that we don't have to null check it everywhere. We also prefetch these queries on the server. It's a good tool to have at your disposal, but as everything, it has pros and cons :) A: The reason TS complains is because the types for react-query do make your user object undefined. In full details, the query has states: export type QueryStatus = 'loading' | 'error' | 'success' and it uses unions to, in short, make sure that when your query is in loading or error state (with the exception of refetch error), the data from the query is undefined, very simplified it looks like this: type QueryObserverResult = { status: 'success', data: TData } | { status: 'error', data: undefined } | { status: 'loading', data: undefined } Since your use case is to use error boundary and rely on user being set, an approach here is to cast the useUser return value. function useUser(): DefinedUseQueryResult<User, Error> { ... ... return useQuery(...) as DefinedUseQueryResult<User, Error> }
How to use react-query to replace context
I read an article on using react-query as a state manager and I am now trying to replace a context in my app with react-query (version 4). Previously, I created a context with useContext() that stored a user account object for the logged-in user. I used react-query to fetch this data, and then useReducer() to modify the account object. However, I realized this is a mess and the relevant data is in react-query anyway, so I should get rid of the context and reducer and just use react-query directly (I am generating the user account object in the query that I make with react-query). I generate the user account object in a custom hook: function useUser(): UseQueryResult<User, Error> { const query = getInitialUserUrl; const platform = usePlatformContext(); return useQuery<User, Error>( queryKeyUseUser, async () => { const data = await fetchAuth(query); if (didQueryReturnData(data)) { return new User(platform, data[0]); } return new User(platform); }, { refetchOnReconnect: 'always', refetchInterval: false, }, ); } export default useUser; Now I have a mutation where I verify the user's email address (old way using context): const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { const { userObject } = useUserContext(); return useMutation( (data: FormEmailVerifyInput) => verifyEmail(userObject.id, data.validation_code), }, ); }; I tried to replace the call to context with a direct call to useUser(): const useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => { const { data: userObject } = useUser(); return useMutation( (data: FormEmailVerifyInput) => verifyEmail(userObject.id, data.validation_code), }, ); }; However, TypeScript complains that Object is possibly 'undefined' for userObject. I'm not sure why, because as far as I understand, useUser() always returns a User object. How can I update my custom hook to return a User object so that I can use it instead of context? UPDATE I can wrap my useUser() hook in another hook: function useUserObject() { const { data: userObject } = useUser(); if (userObject instanceof User) { return userObject; } throw new Error('Failed to get account info!'); } And then I can do const userObject = useUserObject() to get the user account object... but is this really the optimal way? Do I need to create a custom hook for a custom hook just to use my user objects like I do with useContext()?
[ "I wrote the article you've mentioned in your question.\nIt is not guaranteed that useQuery returns data when you call it, because data could not be fetched yet or fetching could have failed.\nNow you might guarantee this in your app because you only call the hook when data has already been fetched - but TypeScript doesn't know that.\nAs stated at the end of the article, this is a tradeoff. What it gives you is that each hook is self-contained. If you call useMutationVerifyEmail in a place where you don't have a user object yet for whatever reason, it will go and try to fetch it.\nThere are various ways to \"work around / with\" that issue / limitation:\n\nYou can ignore it and use a type assertion / the bang operator (!)\n\nconst useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n const { data: userObject } = useUser();\n\n return useMutation(\n (data: FormEmailVerifyInput) => verifyEmail(userObject!.id, data.validation_code),\n );\n};\n\nThis might err at runtime if you move the component that uses this hook to a place where a user isn't available, but it's fine if you know that this is the case :)\n\nYou can check inside the mutationFn as an invariant, and make the mutation error if there is no user:\n\nconst useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n const { data: userObject } = useUser();\n\n return useMutation(\n async (data: FormEmailVerifyInput) => {\n if (!userObject) {\n throw new Error(\"no user available\")\n }\n return verifyEmail(userObject.id, data.validation_code)\n },\n );\n};\n\n\nyou can move the useUser call out of your custom mutation hook and just make the userId part of the input that is passed to the mutation.\n\nconst useMutationVerifyEmail = (): UseMutationResult<RpcResponseEmailVerify, Error, FormEmailVerifyInput> => {\n return useMutation(\n ({ id, ...data} : FormEmailVerifyInput & { id: number }) => verifyEmail(id, data.validation_code),\n );\n};\n\nThen, the component can call useQuery, maybe return null, a loading spinner or an error if there is no user, or you can disable the button that triggers the mutation as long as there is no user.\n\nYou can take a step back and keep your context, but populate it with data from useQuery:\n\nconst UserProvider = ({ children }) => {\n const { data } = useUser()\n\n if (data.isLoading) return \"loading ...\"\n if (data.isError) return \"error\"\n\n return <UserContext.Provider value={data}>{children}</UserContext.Provider>\n}\n\nI might have to write about this pattern some more, because it is not state syncing / duplication. It is also not managing state with react context. All it does is distribute data from react-query via react-context. data is guaranteed to be defined when you read it through useContext(), so it takes away the undefined checks.\nIt will also always give you the \"latest\" data of react-query, because you still have your subscription via useQuery - just further up the tree. Context consumers will be notified of changes because the value updates.\nNow there are tradeoffs to this as well, namely:\n\nYou cannot do partial subscriptions anymore via select, because react-context has no selectors.\nIf you do this with multiple Providers, you risk getting into waterfall fetches: fetching the user \"blocks\" the rest of the app, because it doesn't render children until the user is fetched. That's why user is defined when accessing it in children (which is desired), but it will also block all other fetches that would happen in the children.\n\nI've done this before with something like an EssentialDataProvider. It triggers a bunch of useQuery calls, like user and stack related information that we need everywhere in the app - so it doesn't make sense to render the app without it. We then distribute it via context so that we don't have to null check it everywhere. We also prefetch these queries on the server.\nIt's a good tool to have at your disposal, but as everything, it has pros and cons :)\n", "The reason TS complains is because the types for react-query do make your user object undefined. In full details, the query has states:\nexport type QueryStatus = 'loading' | 'error' | 'success'\n\nand it uses unions to, in short, make sure that when your query is in loading or error state (with the exception of refetch error), the data from the query is undefined, very simplified it looks like this:\ntype QueryObserverResult = {\n status: 'success',\n data: TData\n} | {\n status: 'error',\n data: undefined\n} | {\n status: 'loading',\n data: undefined\n}\n\nSince your use case is to use error boundary and rely on user being set, an approach here is to cast the useUser return value.\nfunction useUser(): DefinedUseQueryResult<User, Error> {\n ...\n ...\n return useQuery(...) as DefinedUseQueryResult<User, Error>\n}\n\n" ]
[ 7, 2 ]
[]
[]
[ "react_query", "typescript" ]
stackoverflow_0074667427_react_query_typescript.txt
Q: How to remove Duplicates given a Random String of letters in Google Sheets? I have been trying to find all duplicates within a string of letters, but I do not know where to start. I had stretched out of all of the letters into separate tiles thinking that I would be able to use to compare tiles with If Then statements. I tried to manually compare each letter with if(b1=b2,"Ignore",b1). This could work, but I would have to type out the grid coordinates to compare all 81 combinations for the string. A: try: =BYROW(A10:A11, LAMBDA(x, JOIN(, UNIQUE(REGEXEXTRACT(x&"", REPT("(.)", LEN(x))), 1)))) if the latter case does not matter you can do: =BYROW(A10:A11, LAMBDA(x, JOIN(, UNIQUE(REGEXEXTRACT(LOWER(x)&"", REPT("(.)", LEN(x))), 1))))
How to remove Duplicates given a Random String of letters in Google Sheets?
I have been trying to find all duplicates within a string of letters, but I do not know where to start. I had stretched out of all of the letters into separate tiles thinking that I would be able to use to compare tiles with If Then statements. I tried to manually compare each letter with if(b1=b2,"Ignore",b1). This could work, but I would have to type out the grid coordinates to compare all 81 combinations for the string.
[ "try:\n=BYROW(A10:A11, LAMBDA(x, JOIN(, UNIQUE(REGEXEXTRACT(x&\"\", REPT(\"(.)\", LEN(x))), 1))))\n\n\nif the latter case does not matter you can do:\n=BYROW(A10:A11, LAMBDA(x, JOIN(, UNIQUE(REGEXEXTRACT(LOWER(x)&\"\", REPT(\"(.)\", LEN(x))), 1))))\n\n\n" ]
[ 0 ]
[]
[]
[ "google_sheets", "string" ]
stackoverflow_0074669475_google_sheets_string.txt
Q: Obtaining a bucket retention period with golang and InfluxDB fellow programmers, I have a use case where I run a influxDB instance in another container (and possibly host) for the purpose of collecting some data. I would want to obtain the retention period of the InfluxDB bucket before writing to it, so that I omit errors, which occur if it is violated. However, I do not seem to find an option to do that using the InfluxDB Golang client. Any idea on how that could be achieved. I also looked in the Flux language specification, but nothing seems to serve my use case as well. I tried looking into the Flux documentation and the Golang Influx Client API. A: You can use the SHOW RETENTION POLICIES query in InfluxDB to obtain the retention period of a bucket. Here is an example of how to do this using the InfluxDB Golang client:` package main import ( "fmt" "log" "github.com/influxdata/influxdb-client-go" ) func main() { // Create a new InfluxDB client client := influxdb.NewClient("http://localhost:9999", "my-token") // Use the `SHOW RETENTION POLICIES` query to obtain the retention period of a bucket query := `SHOW RETENTION POLICIES ON "my-bucket"` result, err := client.Query(influxdb.NewQuery(query, "", "")) if err != nil { log.Fatal(err) } // Print the retention period of the bucket fmt.Println("Retention period:", result.Results[0].Tables[0].Rows[0].Values[1]) } In this code, we use the SHOW RETENTION POLICIES query to obtain the retention period of a bucket named my-bucket. The query returns the retention period in seconds, which we can then access from the Result object returned by the Query method. You can also use the SHOW RETENTION POLICIES query in Flux to obtain the retention period of a bucket. Here is an example of how to do this: from(bucket: "my-bucket") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "retention_policy") |> last() |> yield(name: "retention_period") In this code, we use the from and range functions to query the retention_policy measurement in the my-bucket bucket. We then use the last function to get the most recent record, and the yield function to return the retention_period value from that record. You can then use the FluxTable.ToString() method to obtain the retention_period value as a string, which you can parse and use in your application as needed. Overall, the SHOW RETENTION POLICIES query can be used in both the InfluxDB Golang client and in Flux to obtain the retention period of a bucket. You can use this information to ensure that your writes to the bucket do not violate the retention period and cause errors.
Obtaining a bucket retention period with golang and InfluxDB
fellow programmers, I have a use case where I run a influxDB instance in another container (and possibly host) for the purpose of collecting some data. I would want to obtain the retention period of the InfluxDB bucket before writing to it, so that I omit errors, which occur if it is violated. However, I do not seem to find an option to do that using the InfluxDB Golang client. Any idea on how that could be achieved. I also looked in the Flux language specification, but nothing seems to serve my use case as well. I tried looking into the Flux documentation and the Golang Influx Client API.
[ "You can use the SHOW RETENTION POLICIES query in InfluxDB to obtain the retention period of a bucket. Here is an example of how to do this using the InfluxDB Golang client:`\npackage main\n\nimport (\n \"fmt\"\n \"log\"\n\n \"github.com/influxdata/influxdb-client-go\"\n)\n\nfunc main() {\n // Create a new InfluxDB client\n client := influxdb.NewClient(\"http://localhost:9999\", \"my-token\")\n\n // Use the `SHOW RETENTION POLICIES` query to obtain the retention period of a bucket\n query := `SHOW RETENTION POLICIES ON \"my-bucket\"`\n result, err := client.Query(influxdb.NewQuery(query, \"\", \"\"))\n if err != nil {\n log.Fatal(err)\n }\n\n // Print the retention period of the bucket\n fmt.Println(\"Retention period:\", result.Results[0].Tables[0].Rows[0].Values[1])\n}\n\nIn this code, we use the SHOW RETENTION POLICIES query to obtain the retention period of a bucket named my-bucket. The query returns the retention period in seconds, which we can then access from the Result object returned by the Query method.\nYou can also use the SHOW RETENTION POLICIES query in Flux to obtain the retention period of a bucket. Here is an example of how to do this:\nfrom(bucket: \"my-bucket\")\n |> range(start: -1h)\n |> filter(fn: (r) => r._measurement == \"retention_policy\")\n |> last()\n |> yield(name: \"retention_period\")\n\nIn this code, we use the from and range functions to query the retention_policy measurement in the my-bucket bucket. We then use the last function to get the most recent record, and the yield function to return the retention_period value from that record.\nYou can then use the FluxTable.ToString() method to obtain the retention_period value as a string, which you can parse and use in your application as needed.\nOverall, the SHOW RETENTION POLICIES query can be used in both the InfluxDB Golang client and in Flux to obtain the retention period of a bucket. You can use this information to ensure that your writes to the bucket do not violate the retention period and cause errors.\n" ]
[ 0 ]
[]
[]
[ "flux", "go", "influxdb", "retention" ]
stackoverflow_0074674860_flux_go_influxdb_retention.txt
Q: How to initialize SharedPreferences 2.0.15 in flutter? (Dart - Flutter) I am using shared_preferences: ^2.0.15 and save my values in local. But when i change my screen and get my values app give me error be like this. My question "How can i initialize SharedPreferences in best way?". Video late SharedPreferences _preferences; @override void initState() { super.initState(); getLocalData(); } Future getLocalData() async { _preferences = await SharedPreferences.getInstance(); } A: I've checked the video you shared. You're just missing to call the getLocalData method inside the LoginViewModel. I'd suggest adding a line inside your loginRequest method to call getLocalData method. Well, don't forget to await. await getLocalData(); That's it :) A: actually you are not fetching data from your shared preference you have to get the data that u saved first set data that you want to save addStringToSF() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setString('email', "[email protected]"); } then in your second screen you can get your data late SharedPreferences _preferences; late String email; @override void initState() { super.initState(); getLocalData(); } Future getLocalData() async { _preferences = await SharedPreferences.getInstance(); // for exemple you saved a string value with key ='email' email= _preferences.getString('email'); } check this : https://medium.flutterdevs.com/using-sharedpreferences-in-flutter-251755f07127
How to initialize SharedPreferences 2.0.15 in flutter? (Dart - Flutter)
I am using shared_preferences: ^2.0.15 and save my values in local. But when i change my screen and get my values app give me error be like this. My question "How can i initialize SharedPreferences in best way?". Video late SharedPreferences _preferences; @override void initState() { super.initState(); getLocalData(); } Future getLocalData() async { _preferences = await SharedPreferences.getInstance(); }
[ "I've checked the video you shared.\nYou're just missing to call the getLocalData method inside the LoginViewModel.\nI'd suggest adding a line inside your loginRequest method to call getLocalData method. Well, don't forget to await.\nawait getLocalData();\n\nThat's it :)\n", "actually you are not fetching data from your shared preference\nyou have to get the data that u saved\nfirst set data that you want to save\n\n\naddStringToSF() async {\n SharedPreferences prefs = await SharedPreferences.getInstance();\n prefs.setString('email', \"[email protected]\");\n}\n\n\n\nthen in your second screen you can get your data\n late SharedPreferences _preferences;\n late String email; \n\n @override\n void initState() {\n super.initState();\n getLocalData();\n }\n\n Future getLocalData() async {\n _preferences = await SharedPreferences.getInstance();\n // for exemple you saved a string value with key ='email'\n email= _preferences.getString('email');\n }\n\ncheck this : https://medium.flutterdevs.com/using-sharedpreferences-in-flutter-251755f07127\n" ]
[ 0, 0 ]
[]
[]
[ "dart", "flutter", "sharedpreferences" ]
stackoverflow_0074674202_dart_flutter_sharedpreferences.txt
Q: Why when I go to localhost/my_app/admin I was redirected to localhost/my_app/webroot/admin ? Cakephp I'm using Cakephp 3.8 and I have developed an admin access, but when I try to access to them by the url : localhost/admin my browser (chrome) redirects me systematically to localhost/my_app/webroot/admin This problem doesn't appear when I put a slash at the end : localhost/my_app/admin/ Also, I tested on Edge and Firefox and there is no problem, I can access to localhost/admin (without the slash at the end) The route.php : $routes->connect('/admin', ['controller' => 'Users', 'action' => 'login', 'prefix' => 'admin']); Router::prefix('admin', ['param' => 'value'], function ($routes) { $routes->connect('/:controller'); $routes->connect('/:controller/:action'); $routes->connect('/:controller/:action/**'); }); Sorry for my bad english, Thank you very much for you'r help. A: After 2 years, I found the real solution : My problem is that I've a folder named "admin" in my webroot, just give another name to the folder and clear navigator cache and it solve the problem. A: I think that your application have outdated cache. Try to clear all your sessions and cache and refresh your page. I think that it will solve your problem.
Why when I go to localhost/my_app/admin I was redirected to localhost/my_app/webroot/admin ? Cakephp
I'm using Cakephp 3.8 and I have developed an admin access, but when I try to access to them by the url : localhost/admin my browser (chrome) redirects me systematically to localhost/my_app/webroot/admin This problem doesn't appear when I put a slash at the end : localhost/my_app/admin/ Also, I tested on Edge and Firefox and there is no problem, I can access to localhost/admin (without the slash at the end) The route.php : $routes->connect('/admin', ['controller' => 'Users', 'action' => 'login', 'prefix' => 'admin']); Router::prefix('admin', ['param' => 'value'], function ($routes) { $routes->connect('/:controller'); $routes->connect('/:controller/:action'); $routes->connect('/:controller/:action/**'); }); Sorry for my bad english, Thank you very much for you'r help.
[ "After 2 years, I found the real solution :\nMy problem is that I've a folder named \"admin\" in my webroot, just give another name to the folder and clear navigator cache and it solve the problem.\n", "I think that your application have outdated cache. Try to clear all your sessions and cache and refresh your page. I think that it will solve your problem.\n" ]
[ 1, 0 ]
[]
[]
[ "cakephp", "cakephp_3.0", "php" ]
stackoverflow_0061021230_cakephp_cakephp_3.0_php.txt
Q: Firebase creates user in database but task is never successfull User is created in database but "ok" is never true fun signUp(userEmail: String, userPassword: String, firstName: String, lastName: String):Boolean { var ok:Boolean= false val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance() firebaseAuth.createUserWithEmailAndPassword(userEmail,userPassword) .addOnCompleteListener { task-> if(task.isSuccessful){ ok=true } } return ok} } I'm trying to write mvvm code for login in android studio. Everything works fine but "ok" always remains false and I need it for navigation in another file A: (From OpenAI) There are a few issues with the code you have provided that may be causing the problem you are experiencing. First, the createUserWithEmailAndPassword method of the FirebaseAuth class is asynchronous, which means that it returns immediately without waiting for the user to be created on the server. This means that the ok variable is returned before the user is actually created, so it will always be false in the current code. To fix this problem, you can use a callback or a coroutine to wait for the user to be created before returning the ok variable. Here is an example of how you could use a callback to fix this issue: fun signUp(userEmail: String, userPassword: String, firstName: String, lastName: String, callback: (Boolean) -> Unit) { val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance() firebaseAuth.createUserWithEmailAndPassword(userEmail,userPassword) .addOnCompleteListener { task-> if(task.isSuccessful){ callback(true) } else { callback(false) } } }
Firebase creates user in database but task is never successfull
User is created in database but "ok" is never true fun signUp(userEmail: String, userPassword: String, firstName: String, lastName: String):Boolean { var ok:Boolean= false val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance() firebaseAuth.createUserWithEmailAndPassword(userEmail,userPassword) .addOnCompleteListener { task-> if(task.isSuccessful){ ok=true } } return ok} } I'm trying to write mvvm code for login in android studio. Everything works fine but "ok" always remains false and I need it for navigation in another file
[ "(From OpenAI)\nThere are a few issues with the code you have provided that may be causing the problem you are experiencing.\nFirst, the createUserWithEmailAndPassword method of the FirebaseAuth class is asynchronous, which means that it returns immediately without waiting for the user to be created on the server. This means that the ok variable is returned before the user is actually created, so it will always be false in the current code.\nTo fix this problem, you can use a callback or a coroutine to wait for the user to be created before returning the ok variable. Here is an example of how you could use a callback to fix this issue:\nfun signUp(userEmail: String, userPassword: String, firstName: String, lastName: String, callback: (Boolean) -> Unit) {\n val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance()\n firebaseAuth.createUserWithEmailAndPassword(userEmail,userPassword)\n .addOnCompleteListener { task->\n if(task.isSuccessful){\n callback(true)\n } else {\n callback(false)\n }\n }\n}\n\n" ]
[ 1 ]
[]
[]
[ "android", "firebase", "firebase_authentication", "kotlin" ]
stackoverflow_0074674941_android_firebase_firebase_authentication_kotlin.txt
Q: React.js Images are flickering on Slow 3G even though the images are preloaded and cached in a Ref variable My code is shared on my codesandbox and cleaned up into one file. https://codesandbox.io/s/stackoverflow1-miwjv4?file=/src/App.js I preloaded the necessary images by those two functions. export const preloadImage = (src) => { return new Promise((resolve, reject) => { const img = new Image(); img.src = src; // img.onload = resolve(img); img.onload = () => { resolve(img); }; // img.onerror = img.onabort = reject(src); img.onerror = img.onabort = () => { reject(src); }; }); }; export const preloadAllImages = async (srcArr) => { const promises = srcArr.map((src) => { return preloadImage(src); }); return await Promise.all(promises); }; and use them as below const srcArr = items.map((item) => item.src); console.log(srcArr); preloadAllImages(srcArr).then((images) => { // console.log(images); // console.log(images[0].naturalHeight); slidesRef.current = images.map((image, idx) => { return ( <img key={Math.random().toString()} src={image.src} // Elements with ARIA roles must use a valid, non-abstract ARIA role. role={`${items[idx].role || "presentation"}`} alt={`${items[idx].alt || ""}`} /> ); }); console.log(slidesRef.current); setIsLoading(false); }); If you test the buttons on carousel of my codesandbox with the dev tools on slow 3G, you still can see white screens between the pictures swapped, and also there are unnecessary HTTP requests to the server made. I've been struggling with this for almost 10 hours now. But didn't work out well still. Please help. I don't know why these are happening and how to remove the flickering using 3 pictures preloaded at the same time at the initial loading time. A: Found one problem in my code and found another issue that might have caused this problem. One problem was that there was a key prop in the img JSX element which was stored in slidesRef ref variable even though it was not being used in some loop or Array.map in the DOM and that might have casued the React diff algorithm to consider those JSX img elements have been changed. So I removed the key prop which was added by mistake when I was testing those elements in the Array.map method. With the first problem fixed, the problem still existed; the flickering caused by the unnecessary HTTP requests to the server. The possible issue that might have caused this, I think, in my assumption is that, if the img element gets mounted and unmounted repeatedly, then the browser, after some seconds later, finds the images that are used in those JSX img elments not exist in the browser cache, and seems like it sends a request to the server again for those images. I fixed the above problem by using blob for the images that are being used in the JSX elements which get mounted and unmounted repeatedly and this perfectly solved my issue.
React.js Images are flickering on Slow 3G even though the images are preloaded and cached in a Ref variable
My code is shared on my codesandbox and cleaned up into one file. https://codesandbox.io/s/stackoverflow1-miwjv4?file=/src/App.js I preloaded the necessary images by those two functions. export const preloadImage = (src) => { return new Promise((resolve, reject) => { const img = new Image(); img.src = src; // img.onload = resolve(img); img.onload = () => { resolve(img); }; // img.onerror = img.onabort = reject(src); img.onerror = img.onabort = () => { reject(src); }; }); }; export const preloadAllImages = async (srcArr) => { const promises = srcArr.map((src) => { return preloadImage(src); }); return await Promise.all(promises); }; and use them as below const srcArr = items.map((item) => item.src); console.log(srcArr); preloadAllImages(srcArr).then((images) => { // console.log(images); // console.log(images[0].naturalHeight); slidesRef.current = images.map((image, idx) => { return ( <img key={Math.random().toString()} src={image.src} // Elements with ARIA roles must use a valid, non-abstract ARIA role. role={`${items[idx].role || "presentation"}`} alt={`${items[idx].alt || ""}`} /> ); }); console.log(slidesRef.current); setIsLoading(false); }); If you test the buttons on carousel of my codesandbox with the dev tools on slow 3G, you still can see white screens between the pictures swapped, and also there are unnecessary HTTP requests to the server made. I've been struggling with this for almost 10 hours now. But didn't work out well still. Please help. I don't know why these are happening and how to remove the flickering using 3 pictures preloaded at the same time at the initial loading time.
[ "Found one problem in my code and found another issue that might have caused this problem. One problem was that there was a key prop in the img JSX element which was stored in slidesRef ref variable even though it was not being used in some loop or Array.map in the DOM and that might have casued the React diff algorithm to consider those JSX img elements have been changed. So I removed the key prop which was added by mistake when I was testing those elements in the Array.map method.\nWith the first problem fixed, the problem still existed; the flickering caused by the unnecessary HTTP requests to the server. The possible issue that might have caused this, I think, in my assumption is that, if the img element gets mounted and unmounted repeatedly, then the browser, after some seconds later, finds the images that are used in those JSX img elments not exist in the browser cache, and seems like it sends a request to the server again for those images.\nI fixed the above problem by using blob for the images that are being used in the JSX elements which get mounted and unmounted repeatedly and this perfectly solved my issue.\n" ]
[ 0 ]
[]
[]
[ "browser_cache", "flicker", "javascript", "preload", "reactjs" ]
stackoverflow_0074667995_browser_cache_flicker_javascript_preload_reactjs.txt
Q: How to solve "AttributeError: 'float' object has no attribute 'lower'" enter image description here Getting issues with my code unable to understand what to do next can anyone help me out # Importing the libraries import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Embedding, LSTM, SpatialDropout1D from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical import pickle import re # Importing the dataset filename = "MoviePlots.csv" data = pd.read_csv(filename, encoding= 'unicode_escape') # Keeping only the neccessary columns data = data[['Plot']] # Clean the data data['Plot'] = data['Plot'].apply(lambda x: x.lower()) data['Plot'] = data['Plot'].apply((lambda x: re.sub('[^a-zA-z0-9\s]', '', x))) # Create the tokenizer tokenizer = Tokenizer(num_words=5000, split=" ") tokenizer.fit_on_texts(data['Plot'].values) # Save the tokenizer with open('tokenizer.pickle', 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) # Create the sequences X = tokenizer.texts_to_sequences(data['Plot'].values) X = pad_sequences(X) # Create the model model = Sequential() model.add(Embedding(5000, 256, input_length=X.shape[1])) model.add(Bidirectional(LSTM(256, return_sequences=True, dropout=0.1, recurrent_dropout=0.1))) model.add(LSTM(256, return_sequences=True, dropout=0.1, recurrent_dropout=0.1)) model.add(LSTM(256, dropout=0.1, recurrent_dropout=0.1)) model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01))) model.add(Dense(5000, activation='softmax')) # Compile the model model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.01), metrics=['accuracy']) # Train the model model.fit(X, X, epochs=100, batch_size=128, verbose=1) # Saving the model model.save('visioniser.h5') This is my code and error in the image attached Anyone please help me out solve this problem of my code please diagnose it A: It appears that the error is happening with data['Plot'] = data['Plot'].apply(lambda x: x.lower()) (you are calling the apply function on a column of data -> one of the values in the column is not a string so it doesn't have the lower method)! You could fix this by checking if the instance is actually of type string: data['Plot'] = data['Plot'].apply(lambda x: x.lower() if isinstance(x, str) else x) or instead of using a lambda function: data['Plot'] = data['Plot'].str.lower() whereas panda´s str.lower skips values that are not strings! A: It seems like your column Plot holds some NaN values (considered as float by pandas), hence the error. Try then to cast the column as str with pandas.Series.astype before calling pandas.Series.apply : data['Plot'] = data['Plot'].astype(str).apply(lambda x: x.lower()) Or simply use pandas.Series.str.lower : data['Plot'] = data['Plot'].astype(str).str.lower() The same goes with re.sub, you could use pandas.Series.replace : data['Plot'] = data['Plot'].astype(str).replace(r'[^a-zA-z0-9\s]', '', regex=True)
How to solve "AttributeError: 'float' object has no attribute 'lower'"
enter image description here Getting issues with my code unable to understand what to do next can anyone help me out # Importing the libraries import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Embedding, LSTM, SpatialDropout1D from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical import pickle import re # Importing the dataset filename = "MoviePlots.csv" data = pd.read_csv(filename, encoding= 'unicode_escape') # Keeping only the neccessary columns data = data[['Plot']] # Clean the data data['Plot'] = data['Plot'].apply(lambda x: x.lower()) data['Plot'] = data['Plot'].apply((lambda x: re.sub('[^a-zA-z0-9\s]', '', x))) # Create the tokenizer tokenizer = Tokenizer(num_words=5000, split=" ") tokenizer.fit_on_texts(data['Plot'].values) # Save the tokenizer with open('tokenizer.pickle', 'wb') as handle: pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL) # Create the sequences X = tokenizer.texts_to_sequences(data['Plot'].values) X = pad_sequences(X) # Create the model model = Sequential() model.add(Embedding(5000, 256, input_length=X.shape[1])) model.add(Bidirectional(LSTM(256, return_sequences=True, dropout=0.1, recurrent_dropout=0.1))) model.add(LSTM(256, return_sequences=True, dropout=0.1, recurrent_dropout=0.1)) model.add(LSTM(256, dropout=0.1, recurrent_dropout=0.1)) model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01))) model.add(Dense(5000, activation='softmax')) # Compile the model model.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.01), metrics=['accuracy']) # Train the model model.fit(X, X, epochs=100, batch_size=128, verbose=1) # Saving the model model.save('visioniser.h5') This is my code and error in the image attached Anyone please help me out solve this problem of my code please diagnose it
[ "It appears that the error is happening with data['Plot'] = data['Plot'].apply(lambda x: x.lower()) (you are calling the apply function on a column of data -> one of the values in the column is not a string so it doesn't have the lower method)!\nYou could fix this by checking if the instance is actually of type string:\ndata['Plot'] = data['Plot'].apply(lambda x: x.lower() if isinstance(x, str) else x) \nor instead of using a lambda function:\ndata['Plot'] = data['Plot'].str.lower() whereas panda´s str.lower skips values that are not strings!\n", "It seems like your column Plot holds some NaN values (considered as float by pandas), hence the error. Try then to cast the column as str with pandas.Series.astype before calling pandas.Series.apply :\ndata['Plot'] = data['Plot'].astype(str).apply(lambda x: x.lower())\n\nOr simply use pandas.Series.str.lower :\ndata['Plot'] = data['Plot'].astype(str).str.lower()\n\nThe same goes with re.sub, you could use pandas.Series.replace :\ndata['Plot'] = data['Plot'].astype(str).replace(r'[^a-zA-z0-9\\s]', '', regex=True)\n\n" ]
[ 0, 0 ]
[]
[]
[ "artificial_intelligence", "attributeerror", "pandas", "python" ]
stackoverflow_0074674913_artificial_intelligence_attributeerror_pandas_python.txt
Q: Time complexity of fun()? I was going through this question to calculate time complexity. int fun(int n) { int count = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) count += 1; return count; } My first impression was O(n log n) but the answer is O(n). Please help me understand why it is O(n). A: The inner loop does n iterations, then n/2, then n/4, etc. So the total number of inner loop iterations is: n + n/2 + n/4 + n/8 + ... + 1 <= n * (1 + 1/2 + 1/4 + 1/8 + ...) = 2n (See Geometric series), and therefore is O(n). A: For an input integer n, for i=n, j loop will run n times, then for i= n/2, j loop will run n/2 times, . . so on, . . till i=1, where j loop will run 1 time. So, T(n) = (n + n/2 + n/4 + n/8 + ...... + 1) T(n) = n(1 + 1/2 + 1/4 + 1/8 + ..... + 1/n) .....(1) let 1/n = 1/2^k so, k = logn now, using summation of geometric series in eq 1 T(n) = n((1-1/2^k) / 1-1/2) T(n) = 2n(1-1/2^k) using k = logn T(n) = 2n(1-1/2^logn) now for larger value of n, logn tends to infinite and 1/2^infinite will tend to 0. so, T(n) = 2n so, T(n) = O(n) A: For a input integer n, the innermost statement of fun() is executed following times. n + n/2 + n/4 + ... 1 So time complexity T(n) can be written as T(n) = O(n + n/2 + n/4 + ... 1) = O(n) The value of count is also n + n/2 + n/4 + .. + 1 The outermost loop iterates in O(logn) so it is ignored as O(n) is high A: let's have i and j table where n = 8 i -> less than 0 j -> less than i i j 8 [0,7] 4 [0,3] 2 [0,1] 1 [0,0] "i" which is outer loop is logn Now check for "j" inner loop [0, 7] -> b - a + 1 -> 8 -> n [0, 3] -> b - a + 1 -> 4 -> n/2 [0, 1] -> b - a + 1 -> 2 -> n/4 [0, 0] -> b - a + 1 -> 1 -> n/n if you see it's [n + n/2 + n/4....1] it's moving to infinity not logn times it's infinite series right if we look closely it's GP with infinite series n[1 + 1/2 + 1/4 + .......] where (r < 1) sum of series will gives us 2 (for GP proof you check google) which is n[1 + 1/2 + 1/4 + .......] -> 2n so logn + 2n => O(n)
Time complexity of fun()?
I was going through this question to calculate time complexity. int fun(int n) { int count = 0; for (int i = n; i > 0; i /= 2) for (int j = 0; j < i; j++) count += 1; return count; } My first impression was O(n log n) but the answer is O(n). Please help me understand why it is O(n).
[ "The inner loop does n iterations, then n/2, then n/4, etc. So the total number of inner loop iterations is:\n n + n/2 + n/4 + n/8 + ... + 1 \n<= n * (1 + 1/2 + 1/4 + 1/8 + ...) \n = 2n\n\n(See Geometric series), and therefore is O(n).\n", "For an input integer n,\nfor i=n, j loop will run n times,\nthen for i= n/2, j loop will run n/2 times,\n.\n.\nso on,\n.\n.\ntill i=1, where j loop will run 1 time.\nSo,\nT(n) = (n + n/2 + n/4 + n/8 + ...... + 1) \n T(n) = n(1 + 1/2 + 1/4 + 1/8 + ..... + 1/n) .....(1)\nlet 1/n = 1/2^k\n\nso, k = logn\nnow, using summation of geometric series in eq 1\nT(n) = n((1-1/2^k) / 1-1/2)\nT(n) = 2n(1-1/2^k)\n\nusing k = logn\nT(n) = 2n(1-1/2^logn)\n\nnow for larger value of n, logn tends to infinite and 1/2^infinite will tend to 0.\nso, T(n) = 2n\nso, T(n) = O(n)\n", "For a input integer n, \nthe innermost statement of fun() is executed following times. n + n/2 + n/4 + ... 1 So time complexity T(n) can be written as \nT(n) = O(n + n/2 + n/4 + ... 1) = O(n) The value of count is also n + n/2 + n/4 + .. + 1\nThe outermost loop iterates in O(logn) so it is ignored as O(n) is high\n", "let's have i and j table\nwhere n = 8\n\ni -> less than 0\nj -> less than i\n\n\n\n\ni\nj\n\n\n\n\n8\n[0,7]\n\n\n4\n[0,3]\n\n\n2\n[0,1]\n\n\n1\n[0,0]\n\n\n\n\n\"i\" which is outer loop is logn\nNow check for \"j\" inner loop\n[0, 7] -> b - a + 1 -> 8 -> n\n\n[0, 3] -> b - a + 1 -> 4 -> n/2\n\n[0, 1] -> b - a + 1 -> 2 -> n/4\n[0, 0] -> b - a + 1 -> 1 -> n/n\n\nif you see it's [n + n/2 + n/4....1] it's moving to infinity not logn times\nit's infinite series right if we look closely it's GP with infinite series n[1 + 1/2 + 1/4 + .......] where (r < 1)\nsum of series will gives us 2 (for GP proof you check google)\nwhich is\nn[1 + 1/2 + 1/4 + .......] -> 2n\n\nso logn + 2n => O(n)\n" ]
[ 14, 1, 0, 0 ]
[]
[]
[ "algorithm", "time_complexity" ]
stackoverflow_0033676979_algorithm_time_complexity.txt
Q: Naive bayes with python but seperated two file as 'trainset.csv' and 'testset.csv' I need to apply the naive Bayes algorithm with these files but I search for the algorithm and every example contains '1 CSV file and manually separated train and test set'. I already have 2 CSV file for the train and test set how can I apply a naive Bayes algorithm? I tried to use sklearn train_test_split without(test_size) command but I could not do anything A: It sounds like you want to use the Naive Bayes algorithm to train a model on one CSV file and then test that model using another CSV file. If that's the case, you can use the pandas library to load the two CSV files into separate dataframes, and then use the sklearn library to train a Naive Bayes model using the first dataframe and evaluate the model using the second dataframe. Here's an example of how you might do this: # Load the training and test data into separate dataframes using pandas import pandas as pd train_df = pd.read_csv("trainset.csv") test_df = pd.read_csv("testset.csv") # Extract the input features and target labels from the training data X_train = train_df.drop("target_label", axis=1) y_train = train_df["target_label"] # Extract the input features from the test data X_test = test_df.drop("target_label", axis=1) # Import the GaussianNB classifier from sklearn from sklearn.naive_bayes import GaussianNB # Create a GaussianNB classifier instance nb = GaussianNB() # Train the classifier using the training data nb.fit(X_train, y_train) # Use the trained classifier to make predictions on the test data y_pred = nb.predict(X_test) Once you have made predictions using the trained model, you can evaluate the model's performance using the sklearn.metrics module, which provides a variety of metrics for evaluating machine learning models. For example, you could use the accuracy_score function to calculate the accuracy of the model on the test data, like this: from sklearn.metrics import accuracy_score # Calculate the accuracy of the model on the test data accuracy = accuracy_score(y_test, y_pred) print("Model accuracy: {:.2f}%".format(accuracy * 100))
Naive bayes with python but seperated two file as 'trainset.csv' and 'testset.csv'
I need to apply the naive Bayes algorithm with these files but I search for the algorithm and every example contains '1 CSV file and manually separated train and test set'. I already have 2 CSV file for the train and test set how can I apply a naive Bayes algorithm? I tried to use sklearn train_test_split without(test_size) command but I could not do anything
[ "It sounds like you want to use the Naive Bayes algorithm to train a model on one CSV file and then test that model using another CSV file. If that's the case, you can use the pandas library to load the two CSV files into separate dataframes, and then use the sklearn library to train a Naive Bayes model using the first dataframe and evaluate the model using the second dataframe.\nHere's an example of how you might do this:\n# Load the training and test data into separate dataframes using pandas\nimport pandas as pd\ntrain_df = pd.read_csv(\"trainset.csv\")\ntest_df = pd.read_csv(\"testset.csv\")\n\n# Extract the input features and target labels from the training data\nX_train = train_df.drop(\"target_label\", axis=1)\ny_train = train_df[\"target_label\"]\n\n# Extract the input features from the test data\nX_test = test_df.drop(\"target_label\", axis=1)\n\n# Import the GaussianNB classifier from sklearn\nfrom sklearn.naive_bayes import GaussianNB\n\n# Create a GaussianNB classifier instance\nnb = GaussianNB()\n\n# Train the classifier using the training data\nnb.fit(X_train, y_train)\n\n# Use the trained classifier to make predictions on the test data\ny_pred = nb.predict(X_test)\n\nOnce you have made predictions using the trained model, you can evaluate the model's performance using the sklearn.metrics module, which provides a variety of metrics for evaluating machine learning models. For example, you could use the accuracy_score function to calculate the accuracy of the model on the test data, like this:\nfrom sklearn.metrics import accuracy_score\n\n# Calculate the accuracy of the model on the test data\naccuracy = accuracy_score(y_test, y_pred)\nprint(\"Model accuracy: {:.2f}%\".format(accuracy * 100))\n\n" ]
[ 0 ]
[]
[]
[ "naivebayes", "python" ]
stackoverflow_0074674912_naivebayes_python.txt
Q: Filter Pyspark Dataframe column based on whether it contains or does not contain substring I have a pyspark dataframe message_df with millions of rows that looks like this id message ab123 Hello my name is Chris cd345 The room should be 2301 ef567 Welcome! What is your name? gh873 That way please kj893 The current year is 2022 and two lists wanted_words = ['name','room'] unwanted_words = ['welcome','year'] I only want to get rows where message contains any of the words in wanted_words and does not contain any of the words in unwanted_words, hence the result should be: id message ab123 Hello my name is Chris cd345 The room should be 2301 As of right now I am doing it word by word message_df.select(lower(F.col('message'))).filter( ( F.col('lower(message)').contains('name') | F.col('lower(message)').contains('room') ) & ( ~F.col('lower(message)').contains('welcome') & ~F.col('lower(message)').contains('year') ) ) Which is very tedious to code. However, when I instead use rlike: wanted_words ="(name|room)" unwanted_words ="(welcome|year)" message_df.select(lower(F.col('message'))).filter( ~F.col('lower(message)').rlike(not_contain) & F.col('lower(message)').rlike(contain) ) The process slows down immensely. Is the reason because rlike is significantly slower, and if so what is a better way of filtering when wanted_words and unwanted_words may contain hundreds of words? A: Split text into tokens/words and use arrays_overlap function to check if wanted or unwanted token is present: df = df.filter( ( F.arrays_overlap( F.split(F.regexp_replace(F.lower("message"), r"[^a-zA-Z0-9\s]+", ""), "\s+"), F.array([F.lit(c) for c in wanted_words]) ) ) & ( ~F.arrays_overlap( F.split(F.regexp_replace(F.lower("message"), r"[^a-zA-Z0-9\s]+", ""), "\s+"), F.array([F.lit(c) for c in unwanted_words]) ) ) ) Full example: columns = ["id","message"] data = [["ab123","Hello my name is Chris"],["cd345","The room should be 2301"],["ef567","Welcome! What is your name?"],["gh873","That way please"],["kj893","The current year is 2022"]] df = spark.createDataFrame(data).toDF(*columns) wanted_words = ['name','room'] unwanted_words = ['welcome','year'] df = df.filter( ( F.arrays_overlap( F.split(F.regexp_replace(F.lower("message"), r"[^a-zA-Z0-9\s]+", ""), "\s+"), F.array([F.lit(c) for c in wanted_words]) ) ) & ( ~F.arrays_overlap( F.split(F.regexp_replace(F.lower("message"), r"[^a-zA-Z0-9\s]+", ""), "\s+"), F.array([F.lit(c) for c in unwanted_words]) ) ) ) [Out]: +-----+------------------------+ |id |message | +-----+------------------------+ |ab123|Hello my name is Chris | |cd345|The room should be 2301 | +-----+------------------------+ You can also pre-compute the tokens at once for efficiency: df = df.withColumn("tokens", F.split(F.regexp_replace(F.lower("message"), r"[^a-zA-Z0-9\s]+", ""), "\s+")) and use in "arrays_overlap": F.arrays_overlap(F.col("tokens"), F.array([F.lit(c) for c in wanted_words]))
Filter Pyspark Dataframe column based on whether it contains or does not contain substring
I have a pyspark dataframe message_df with millions of rows that looks like this id message ab123 Hello my name is Chris cd345 The room should be 2301 ef567 Welcome! What is your name? gh873 That way please kj893 The current year is 2022 and two lists wanted_words = ['name','room'] unwanted_words = ['welcome','year'] I only want to get rows where message contains any of the words in wanted_words and does not contain any of the words in unwanted_words, hence the result should be: id message ab123 Hello my name is Chris cd345 The room should be 2301 As of right now I am doing it word by word message_df.select(lower(F.col('message'))).filter( ( F.col('lower(message)').contains('name') | F.col('lower(message)').contains('room') ) & ( ~F.col('lower(message)').contains('welcome') & ~F.col('lower(message)').contains('year') ) ) Which is very tedious to code. However, when I instead use rlike: wanted_words ="(name|room)" unwanted_words ="(welcome|year)" message_df.select(lower(F.col('message'))).filter( ~F.col('lower(message)').rlike(not_contain) & F.col('lower(message)').rlike(contain) ) The process slows down immensely. Is the reason because rlike is significantly slower, and if so what is a better way of filtering when wanted_words and unwanted_words may contain hundreds of words?
[ "Split text into tokens/words and use arrays_overlap function to check if wanted or unwanted token is present:\ndf = df.filter(\n (\n F.arrays_overlap(\n F.split(F.regexp_replace(F.lower(\"message\"), r\"[^a-zA-Z0-9\\s]+\", \"\"), \"\\s+\"),\n F.array([F.lit(c) for c in wanted_words])\n )\n )\n & \n (\n ~F.arrays_overlap(\n F.split(F.regexp_replace(F.lower(\"message\"), r\"[^a-zA-Z0-9\\s]+\", \"\"), \"\\s+\"),\n F.array([F.lit(c) for c in unwanted_words])\n )\n )\n)\n\nFull example:\ncolumns = [\"id\",\"message\"]\ndata = [[\"ab123\",\"Hello my name is Chris\"],[\"cd345\",\"The room should be 2301\"],[\"ef567\",\"Welcome! What is your name?\"],[\"gh873\",\"That way please\"],[\"kj893\",\"The current year is 2022\"]]\ndf = spark.createDataFrame(data).toDF(*columns)\n\nwanted_words = ['name','room']\nunwanted_words = ['welcome','year']\n\ndf = df.filter(\n (\n F.arrays_overlap(\n F.split(F.regexp_replace(F.lower(\"message\"), r\"[^a-zA-Z0-9\\s]+\", \"\"), \"\\s+\"),\n F.array([F.lit(c) for c in wanted_words])\n )\n )\n & \n (\n ~F.arrays_overlap(\n F.split(F.regexp_replace(F.lower(\"message\"), r\"[^a-zA-Z0-9\\s]+\", \"\"), \"\\s+\"),\n F.array([F.lit(c) for c in unwanted_words])\n )\n )\n)\n\n[Out]:\n+-----+------------------------+\n|id |message |\n+-----+------------------------+\n|ab123|Hello my name is Chris |\n|cd345|The room should be 2301 |\n+-----+------------------------+\n\nYou can also pre-compute the tokens at once for efficiency:\ndf = df.withColumn(\"tokens\", F.split(F.regexp_replace(F.lower(\"message\"), r\"[^a-zA-Z0-9\\s]+\", \"\"), \"\\s+\"))\n\nand use in \"arrays_overlap\":\nF.arrays_overlap(F.col(\"tokens\"), F.array([F.lit(c) for c in wanted_words]))\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pyspark", "python" ]
stackoverflow_0074668162_dataframe_pyspark_python.txt
Q: How To Send A Data Object With Fetch API I want to send a data object with fetch api with keepalive to the current page and get the data through php. how can I do it. Data To Send { name: 'blabla', age: 432, type: 'pig' } I want to recieve as a post variable $_POST['name']; I've tried this but it is not working fetch('', { method: 'POST', body: {name: 'blabla'}, keepalive: true }); Sorry for no code A: No idea what keepalive is, but if I want to send a fetch request to a php backend I would usually do something like this: fetch("backend.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", }, body: "data=" + data, }) .then((response) => response.json()) .then((response) => doWhatYouWant(response)) .catch((error) => alert("Error : " + error)); A: You could call fetch with json as content-type and use method POST as you allready tried, you also have to serialize the content on the body fetch("backend.php", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name: "blablabla" }), });
How To Send A Data Object With Fetch API
I want to send a data object with fetch api with keepalive to the current page and get the data through php. how can I do it. Data To Send { name: 'blabla', age: 432, type: 'pig' } I want to recieve as a post variable $_POST['name']; I've tried this but it is not working fetch('', { method: 'POST', body: {name: 'blabla'}, keepalive: true }); Sorry for no code
[ "No idea what keepalive is, but if I want to send a fetch request to a php backend I would usually do something like this:\n fetch(\"backend.php\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n },\n body: \"data=\" + data,\n })\n .then((response) => response.json())\n .then((response) => doWhatYouWant(response))\n .catch((error) => alert(\"Error : \" + error));\n\n", "You could call fetch with json as content-type and use method POST as you allready tried, you also have to serialize the content on the body\n fetch(\"backend.php\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ name: \"blablabla\" }),\n});\n\n" ]
[ 0, 0 ]
[]
[]
[ "fetch_api", "javascript", "php" ]
stackoverflow_0074674440_fetch_api_javascript_php.txt
Q: adding text above icon in jetpack compose Is there any way how I can show a little description above specific icon in Jetpack Compose like in this picture? A: It's called speech or tooltip bubble. You can create this or any shape using GenericShape or adding RoundedRect. Column( modifier = Modifier .fillMaxSize() .padding(10.dp) ) { var showToolTip by remember { mutableStateOf(false) } Spacer(modifier = Modifier.height(100.dp)) val triangleShape = remember { GenericShape { size: Size, layoutDirection: LayoutDirection -> val width = size.width val height = size.height lineTo(width / 2, height) lineTo(width, 0f) lineTo(0f, 0f) } } Box { if (showToolTip) { Column(modifier = Modifier.offset(y = (-48).dp)) { Box( modifier = Modifier .clip(RoundedCornerShape(10.dp)) .shadow(2.dp) .background(Color(0xff26A69A)) .padding(8.dp), ) { Text("Hello World", color = Color.White) } Box( modifier = Modifier .offset(x = 15.dp) .clip(triangleShape) .width(20.dp) .height(16.dp) .background(Color(0xff26A69A)) ) } } IconButton( onClick = { showToolTip = true } ) { Icon( imageVector = Icons.Default.Add, contentDescription = "null", Modifier .background(Color.Red, CircleShape) .padding(4.dp) ) } } } If you need shadow or border that must be a single shape you need to build it with GenericShape. You can check my answer out and library i built. The sample below is simplified version of library, with no Modifier.layout which is essential for setting space reserved for arrow and setting padding correctly instead of creating another Box with Padding Result fun getBubbleShape( density: Density, cornerRadius: Dp, arrowWidth: Dp, arrowHeight: Dp, arrowOffset: Dp ): GenericShape { val cornerRadiusPx: Float val arrowWidthPx: Float val arrowHeightPx: Float val arrowOffsetPx: Float with(density) { cornerRadiusPx = cornerRadius.toPx() arrowWidthPx = arrowWidth.toPx() arrowHeightPx = arrowHeight.toPx() arrowOffsetPx = arrowOffset.toPx() } return GenericShape { size: Size, layoutDirection: LayoutDirection -> val rectBottom = size.height - arrowHeightPx this.addRoundRect( RoundRect( rect = Rect( offset = Offset.Zero, size = Size(size.width, rectBottom) ), cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx) ) ) moveTo(arrowOffsetPx, rectBottom) lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height) lineTo(arrowOffsetPx + arrowWidthPx, rectBottom) } } Then create a Bubble Composable, i set static values but you can set these as parameters @Composable private fun Bubble( modifier: Modifier = Modifier, text: String ) { val density = LocalDensity.current val arrowHeight = 16.dp val bubbleShape = remember { getBubbleShape( density = density, cornerRadius = 12.dp, arrowWidth = 20.dp, arrowHeight = arrowHeight, arrowOffset = 30.dp ) } Box( modifier = modifier .clip(bubbleShape) .shadow(2.dp) .background(Color(0xff26A69A)) .padding(bottom = arrowHeight), contentAlignment = Alignment.Center ) { Box(modifier = Modifier.padding(8.dp)) { Text( text = text, color = Color.White, fontSize = 20.sp ) } } } You can use it as in this sample. You need to change offset of Bubble to match position of ImageButton Column( modifier = Modifier .fillMaxSize() .padding(10.dp) ) { var showToolTip by remember { mutableStateOf(false) } Spacer(modifier = Modifier.height(100.dp)) Box { if (showToolTip) { Bubble( modifier = Modifier.offset(x = (-15).dp, (-52).dp), text = "Hello World" ) } IconButton( onClick = { showToolTip = true } ) { Icon( imageVector = Icons.Default.Add, contentDescription = "null", Modifier .background(Color.Red, CircleShape) .padding(4.dp) ) } } } A: You can use a Box. The children of the Box layout will be stacked over each other. Box{ Text(text = "Text Above Icon", modifier = text alignment) Icon(... , modifier = icon alignment) }
adding text above icon in jetpack compose
Is there any way how I can show a little description above specific icon in Jetpack Compose like in this picture?
[ "It's called speech or tooltip bubble. You can create this or any shape using GenericShape or adding RoundedRect.\nColumn(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n val triangleShape = remember {\n GenericShape { size: Size, layoutDirection: LayoutDirection ->\n val width = size.width\n val height = size.height\n\n lineTo(width / 2, height)\n lineTo(width, 0f)\n lineTo(0f, 0f)\n }\n }\n\n Box {\n\n if (showToolTip) {\n Column(modifier = Modifier.offset(y = (-48).dp)) {\n\n\n Box(\n modifier = Modifier\n .clip(RoundedCornerShape(10.dp))\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(8.dp),\n ) {\n Text(\"Hello World\", color = Color.White)\n }\n\n\n Box(\n modifier = Modifier\n .offset(x = 15.dp)\n .clip(triangleShape)\n .width(20.dp)\n .height(16.dp)\n .background(Color(0xff26A69A))\n )\n }\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n\nIf you need shadow or border that must be a single shape you need to build it with GenericShape. You can check my answer out and library i built.\nThe sample below is simplified version of library, with no Modifier.layout which is essential for setting space reserved for arrow and setting padding correctly instead of creating another Box with Padding\nResult\n\nfun getBubbleShape(\n density: Density,\n cornerRadius: Dp,\n arrowWidth: Dp,\n arrowHeight: Dp,\n arrowOffset: Dp\n): GenericShape {\n\n val cornerRadiusPx: Float\n val arrowWidthPx: Float\n val arrowHeightPx: Float\n val arrowOffsetPx: Float\n\n with(density) {\n cornerRadiusPx = cornerRadius.toPx()\n arrowWidthPx = arrowWidth.toPx()\n arrowHeightPx = arrowHeight.toPx()\n arrowOffsetPx = arrowOffset.toPx()\n }\n\n return GenericShape { size: Size, layoutDirection: LayoutDirection ->\n\n val rectBottom = size.height - arrowHeightPx\n this.addRoundRect(\n RoundRect(\n rect = Rect(\n offset = Offset.Zero,\n size = Size(size.width, rectBottom)\n ),\n cornerRadius = CornerRadius(cornerRadiusPx, cornerRadiusPx)\n )\n )\n moveTo(arrowOffsetPx, rectBottom)\n lineTo(arrowOffsetPx + arrowWidthPx / 2, size.height)\n lineTo(arrowOffsetPx + arrowWidthPx, rectBottom)\n\n }\n}\n\nThen create a Bubble Composable, i set static values but you can set these as parameters\n@Composable\nprivate fun Bubble(\n modifier: Modifier = Modifier,\n text: String\n) {\n val density = LocalDensity.current\n val arrowHeight = 16.dp\n\n val bubbleShape = remember {\n getBubbleShape(\n density = density,\n cornerRadius = 12.dp,\n arrowWidth = 20.dp,\n arrowHeight = arrowHeight,\n arrowOffset = 30.dp\n )\n }\n\n Box(\n modifier = modifier\n .clip(bubbleShape)\n .shadow(2.dp)\n .background(Color(0xff26A69A))\n .padding(bottom = arrowHeight),\n contentAlignment = Alignment.Center\n ) {\n Box(modifier = Modifier.padding(8.dp)) {\n Text(\n text = text,\n color = Color.White,\n fontSize = 20.sp\n )\n }\n }\n}\n\nYou can use it as in this sample. You need to change offset of Bubble to match position of ImageButton\nColumn(\n modifier = Modifier\n .fillMaxSize()\n .padding(10.dp)\n) {\n\n var showToolTip by remember {\n mutableStateOf(false)\n }\n\n\n Spacer(modifier = Modifier.height(100.dp))\n\n Box {\n\n if (showToolTip) {\n Bubble(\n modifier = Modifier.offset(x = (-15).dp, (-52).dp),\n text = \"Hello World\"\n )\n }\n\n IconButton(\n onClick = { showToolTip = true }\n ) {\n Icon(\n imageVector = Icons.Default.Add,\n contentDescription = \"null\",\n Modifier\n .background(Color.Red, CircleShape)\n .padding(4.dp)\n )\n }\n }\n}\n\n", "You can use a Box. The children of the Box layout will be stacked over each other.\nBox{ \n Text(text = \"Text Above Icon\", modifier = text alignment)\n Icon(... , modifier = icon alignment) \n \n}\n\n" ]
[ 1, 0 ]
[ " /** Text can be added above an icon in Jetpack Compose by using a combination of the Row and Column composables. The Row composable lays out its children in a single row while the Column composable lays out its children in a single column. To add text above the icon, the Row composable should be used first, followed by the Column composable. This will allow the text to be placed on the top of the icon. For example, the following code will add text above an icon: ***/\n \n Row { \n Text(text = \"Text Above Icon\") \n Column { \n Icon(... ) \n } \n }\n\n" ]
[ -1 ]
[ "android", "android_jetpack", "android_jetpack_compose", "kotlin" ]
stackoverflow_0074670360_android_android_jetpack_android_jetpack_compose_kotlin.txt
Q: How to use react-big-calendar only for month view I'm trying to use react-big-calendar, only for viewing the month and allowing the user to press a certain date, which should trigger my own function. That is I'm not interested in (and want to remove) all the functionality related to week, day, agenda or displaying the time of a day. I simply want to show the month-view, allow the user to press a date which should trigger my function onSelectSlot. I haven't found much on how to do this, the little I did find said to use selectable={true} and onSelectSlot={onSelectSlot} to make a function to execute ones a date has been pressed. However, this did not work. And I still wonder how to remove all the added functionalities, which I want remove as I have no use of them. Is these things possible with react-big-calender, or should I move on to trying something else? I know there are other ones out there, but I really like the look and feel of this one and would prefer to stick with it if possible. Here is an image of how it looks, to give a better understanding of what I mean: (So it's the things in the top right corner that I want to remove, and when a pressing a certain date I want to trigger my own function and not switch to the day-view as it does by default) import format from "date-fns/format"; import getDay from "date-fns/getDay"; import parse from "date-fns/parse"; import startOfWeek from "date-fns/startOfWeek"; import React, { useState } from "react"; import { Calendar, dateFnsLocalizer } from "react-big-calendar"; import "react-big-calendar/lib/css/react-big-calendar.css"; import DatePicker from "react-datepicker"; import "react-datepicker/dist/react-datepicker.css"; import "./calendar.css"; const locales = { "en-US": require("date-fns/locale/en-US"), }; const localizer = dateFnsLocalizer({ format, parse, startOfWeek, getDay, locales, }); const onSelectSlot = (pressedDate) => { console.log("pressed Date: ", pressedDate) }; function MyCalendar() { return ( <div className="text-center"> <h1>Calendar</h1> <Calendar localizer={localizer} selectable={true} startAccessor="start" onSelectSlot={onSelectSlot} endAccessor="end" style={{ height: 500, margin: "50px" }} /> </div> ); } export default MyCalendar; Update and Solution To change the view to month and only show month-view, add the following to you calendar: view='month' views={['month']}. The function executes using the code displayed above, however it only works when you press inside of the cell and not the number in the cell which was what I was doing. Hence why it didn't trigger initially for me. To handle pressing the number in the cell use onNavigate={onSelectSlot} A: Add the following changes. const {views, ...otherProps} = useMemo(() => ({ views: { month: true } }), []) and then add to prop views={views}
How to use react-big-calendar only for month view
I'm trying to use react-big-calendar, only for viewing the month and allowing the user to press a certain date, which should trigger my own function. That is I'm not interested in (and want to remove) all the functionality related to week, day, agenda or displaying the time of a day. I simply want to show the month-view, allow the user to press a date which should trigger my function onSelectSlot. I haven't found much on how to do this, the little I did find said to use selectable={true} and onSelectSlot={onSelectSlot} to make a function to execute ones a date has been pressed. However, this did not work. And I still wonder how to remove all the added functionalities, which I want remove as I have no use of them. Is these things possible with react-big-calender, or should I move on to trying something else? I know there are other ones out there, but I really like the look and feel of this one and would prefer to stick with it if possible. Here is an image of how it looks, to give a better understanding of what I mean: (So it's the things in the top right corner that I want to remove, and when a pressing a certain date I want to trigger my own function and not switch to the day-view as it does by default) import format from "date-fns/format"; import getDay from "date-fns/getDay"; import parse from "date-fns/parse"; import startOfWeek from "date-fns/startOfWeek"; import React, { useState } from "react"; import { Calendar, dateFnsLocalizer } from "react-big-calendar"; import "react-big-calendar/lib/css/react-big-calendar.css"; import DatePicker from "react-datepicker"; import "react-datepicker/dist/react-datepicker.css"; import "./calendar.css"; const locales = { "en-US": require("date-fns/locale/en-US"), }; const localizer = dateFnsLocalizer({ format, parse, startOfWeek, getDay, locales, }); const onSelectSlot = (pressedDate) => { console.log("pressed Date: ", pressedDate) }; function MyCalendar() { return ( <div className="text-center"> <h1>Calendar</h1> <Calendar localizer={localizer} selectable={true} startAccessor="start" onSelectSlot={onSelectSlot} endAccessor="end" style={{ height: 500, margin: "50px" }} /> </div> ); } export default MyCalendar; Update and Solution To change the view to month and only show month-view, add the following to you calendar: view='month' views={['month']}. The function executes using the code displayed above, however it only works when you press inside of the cell and not the number in the cell which was what I was doing. Hence why it didn't trigger initially for me. To handle pressing the number in the cell use onNavigate={onSelectSlot}
[ "Add the following changes.\nconst {views, ...otherProps} = useMemo(() => ({\nviews: {\nmonth: true\n}\n}), [])\nand then add to prop\nviews={views}\n" ]
[ 0 ]
[ "as per documentation example you can pass defaultView=\"month\" in you calendar component\n" ]
[ -1 ]
[ "javascript", "react_big_calendar", "react_calendar", "reactjs" ]
stackoverflow_0072053885_javascript_react_big_calendar_react_calendar_reactjs.txt
Q: Master-detail navigation in Blazor I have a master-detail page in blazor wasm: a left panel with a list of items, and a right panel with the selected item. An example (ascii generated here), with item 2 selected: MASTER DETAIL +--------------------+----------------------------------------+ | item 1 | | | | | | | item 2 | +--------------------+ | |░░░░░░░░░░░░░░░░░░░░| | |░item 2░░░░░░░░░░░░░| | |░░░░░░░░░░░░░░░░░░░░| | |░░░░░░░░░░░░░░░░░░░░| | +--------------------+ | | item 3 | | | | | | | | +--------------------+ | | item 4 | | | | | | | | +--------------------+----------------------------------------+ https://www.example.com/items/2 URLs: /items for page showing items without a selection /items/2 for page showing items with item 2 selected I managed to do all that, using this approach: MyLayout.razor has a <Master /> component (left), and a <Detail Id=_selectedId /> component (right) When an item is clicked in the master component (left), it raises an event with the Id The layout handles that event, and passes the id to the detail component (right) The detail component (right) shows the new item I also want the browser's location updated from /items to /items/2, so I used: NavigationManager.NavigateTo("/items/" + id). But that reloads all components. Workarounds: I haven't found a way to update the browser location without reloading the page (though I could do that in javascript). Even if that were possible, I'm not sure that's a good way to do it. I could use a query string parameter instead, /items?id=10, then the NavigationManager would (I think) avoid the rerendering - but I can't use this approach, it must be part of the URI. What is the recommended way to handle master-detail navigation in blazor? A: Instead of using NavigationManager, you should use an event callback from Master Component (Master.razor) to tell its parent Component (Mainlayout.razor) that the Id selected has changed. Thus now Mainlayout can pass the new Id into its second child Detail Component. The Detail Component then will rerender accordingly. Further reference on event callback : https://www.pragimtech.com/blog/blazor/blazor-eventcallback/ To force the Detail component to be rerendered, you can also use OnParameterSet on the Detail component. Read more here : Executing method on Parameter change A: You don't need to use a Layout for this. There are many ways to solve the problem. the level of complexity in the solution depends on the functionality required. Here's a normal page version using weather forecasts that demonstrates one way. Create a blank Layout if you want a vanilla look. First my mods to the WeatherForecastService: public class WeatherForecastService { public IEnumerable<WeatherForecast>? Forecasts { get; private set; } public WeatherForecast? Forecast { get; private set; } public async Task<bool> GetForecastsAsync() { if (this.Forecasts is null) this.Forecasts = await _getForecastAsync(); return true; } public async Task GetForecastAsync(int id) { // mimic an async fetch await Task.Delay(100); this.Forecast = Forecasts?.FirstOrDefault(item => item.Id == id); } private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private async Task<IEnumerable<WeatherForecast>> _getForecastAsync() { // mimic an async fetch await Task.Delay(100); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Id = index, Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }); } } The Viewer component: @inject WeatherForecastService ForecastService @if (ForecastService.Forecast == null) { <p><em>No Record Selected</em></p> } else { <div class="container-fluid"> <div class="row"> <div class="col-6">Date</div> <div class="col-6">@ForecastService.Forecast.Date</div> </div> <div class="row"> <div class="col-6">Temperature &deg; C</div> <div class="col-6">@ForecastService.Forecast.TemperatureC</div> </div> <div class="row"> <div class="col-6">Temperature &deg; F</div> <div class="col-6">@ForecastService.Forecast.TemperatureF</div> </div> <div class="row"> <div class="col-6">Summary</div> <div class="col-6">@ForecastService.Forecast.Summary</div> </div> </div> } @code { [Parameter] public int? Id { get; set; } private int? currentId; protected async override Task OnParametersSetAsync() { if (this.currentId != Id) { await ForecastService.GetForecastAsync(this.Id ?? 0); this.currentId = this.Id; } } } And the list component: @inject WeatherForecastService ForecastService @if (ForecastService.Forecasts == null) { <p><em>Loading...</em></p> } else { <table class="table"> <tbody> @foreach (var forecast in this.ForecastService.Forecasts) { <tr> <td><a href="/fetchdata/@forecast.Id"> @forecast.Date.ToShortDateString()</a></td> </tr> } </tbody> </table> } @code { protected override async Task OnInitializedAsync() => await ForecastService.GetForecastsAsync(); } And then the new FetchData: @page "/fetchdata/{Id:int}" @page "/fetchdata" <div class="container-fluid"> <div class="row"> <div class="col-4"> <WeatherList /> </div> <div class="col-8"> <WeatherViewer Id=this.Id /> </div> </div> </div> @code { [Parameter] public int? Id { get; set; } } Note: All the data and data management resides in the service. There's no page reloading: just a parameter change. As the navigation is to the same page we use OnParametersSetAsync in the viewer to check if we need to refresh the selected item.
Master-detail navigation in Blazor
I have a master-detail page in blazor wasm: a left panel with a list of items, and a right panel with the selected item. An example (ascii generated here), with item 2 selected: MASTER DETAIL +--------------------+----------------------------------------+ | item 1 | | | | | | | item 2 | +--------------------+ | |░░░░░░░░░░░░░░░░░░░░| | |░item 2░░░░░░░░░░░░░| | |░░░░░░░░░░░░░░░░░░░░| | |░░░░░░░░░░░░░░░░░░░░| | +--------------------+ | | item 3 | | | | | | | | +--------------------+ | | item 4 | | | | | | | | +--------------------+----------------------------------------+ https://www.example.com/items/2 URLs: /items for page showing items without a selection /items/2 for page showing items with item 2 selected I managed to do all that, using this approach: MyLayout.razor has a <Master /> component (left), and a <Detail Id=_selectedId /> component (right) When an item is clicked in the master component (left), it raises an event with the Id The layout handles that event, and passes the id to the detail component (right) The detail component (right) shows the new item I also want the browser's location updated from /items to /items/2, so I used: NavigationManager.NavigateTo("/items/" + id). But that reloads all components. Workarounds: I haven't found a way to update the browser location without reloading the page (though I could do that in javascript). Even if that were possible, I'm not sure that's a good way to do it. I could use a query string parameter instead, /items?id=10, then the NavigationManager would (I think) avoid the rerendering - but I can't use this approach, it must be part of the URI. What is the recommended way to handle master-detail navigation in blazor?
[ "Instead of using NavigationManager, you should use an event callback from Master Component (Master.razor) to tell its parent Component (Mainlayout.razor) that the Id selected has changed. Thus now Mainlayout can pass the new Id into its second child Detail Component. The Detail Component then will rerender accordingly.\nFurther reference on event callback : https://www.pragimtech.com/blog/blazor/blazor-eventcallback/\nTo force the Detail component to be rerendered, you can also use\nOnParameterSet on the Detail component.\nRead more here :\nExecuting method on Parameter change\n", "You don't need to use a Layout for this.\nThere are many ways to solve the problem. the level of complexity in the solution depends on the functionality required.\nHere's a normal page version using weather forecasts that demonstrates one way. Create a blank Layout if you want a vanilla look.\nFirst my mods to the WeatherForecastService:\npublic class WeatherForecastService\n{\n public IEnumerable<WeatherForecast>? Forecasts { get; private set; }\n\n public WeatherForecast? Forecast { get; private set; }\n\n public async Task<bool> GetForecastsAsync()\n {\n if (this.Forecasts is null)\n this.Forecasts = await _getForecastAsync();\n\n return true;\n }\n\n public async Task GetForecastAsync(int id)\n {\n // mimic an async fetch\n await Task.Delay(100);\n this.Forecast = Forecasts?.FirstOrDefault(item => item.Id == id);\n }\n\n\n private static readonly string[] Summaries = new[]\n {\n \"Freezing\", \"Bracing\", \"Chilly\", \"Cool\", \"Mild\", \"Warm\", \"Balmy\", \"Hot\", \"Sweltering\", \"Scorching\"\n };\n\n private async Task<IEnumerable<WeatherForecast>> _getForecastAsync()\n {\n // mimic an async fetch\n await Task.Delay(100);\n return Enumerable.Range(1, 5).Select(index => new WeatherForecast\n {\n Id = index,\n Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),\n TemperatureC = Random.Shared.Next(-20, 55),\n Summary = Summaries[Random.Shared.Next(Summaries.Length)]\n });\n }\n}\n\nThe Viewer component:\n@inject WeatherForecastService ForecastService\n\n@if (ForecastService.Forecast == null)\n{\n <p><em>No Record Selected</em></p>\n}\nelse\n{\n <div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-6\">Date</div>\n <div class=\"col-6\">@ForecastService.Forecast.Date</div>\n </div>\n\n <div class=\"row\">\n <div class=\"col-6\">Temperature &deg; C</div>\n <div class=\"col-6\">@ForecastService.Forecast.TemperatureC</div>\n </div>\n\n <div class=\"row\">\n <div class=\"col-6\">Temperature &deg; F</div>\n <div class=\"col-6\">@ForecastService.Forecast.TemperatureF</div>\n </div>\n\n <div class=\"row\">\n <div class=\"col-6\">Summary</div>\n <div class=\"col-6\">@ForecastService.Forecast.Summary</div>\n </div>\n\n </div>\n}\n\n@code {\n [Parameter] public int? Id { get; set; }\n\n private int? currentId;\n\n protected async override Task OnParametersSetAsync()\n {\n if (this.currentId != Id)\n {\n await ForecastService.GetForecastAsync(this.Id ?? 0);\n this.currentId = this.Id;\n }\n }\n}\n\nAnd the list component:\n@inject WeatherForecastService ForecastService\n\n@if (ForecastService.Forecasts == null)\n{\n <p><em>Loading...</em></p>\n}\nelse\n{\n <table class=\"table\">\n <tbody>\n @foreach (var forecast in this.ForecastService.Forecasts)\n {\n <tr>\n <td><a href=\"/fetchdata/@forecast.Id\"> @forecast.Date.ToShortDateString()</a></td>\n </tr>\n }\n </tbody>\n </table>\n}\n\n@code {\n\n protected override async Task OnInitializedAsync()\n => await ForecastService.GetForecastsAsync();\n}\n\nAnd then the new FetchData:\n@page \"/fetchdata/{Id:int}\"\n@page \"/fetchdata\"\n\n<div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-4\">\n <WeatherList />\n </div>\n <div class=\"col-8\">\n <WeatherViewer Id=this.Id />\n </div>\n </div>\n\n</div>\n\n@code {\n [Parameter] public int? Id { get; set; }\n}\n\nNote:\n\nAll the data and data management resides in the service.\nThere's no page reloading: just a parameter change. As the navigation is to the same page we use OnParametersSetAsync in the viewer to check if we need to refresh the selected item.\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "asp.net_core", "asp.net_core_6.0", "blazor", "blazor_webassembly", "c#" ]
stackoverflow_0074673537_asp.net_core_asp.net_core_6.0_blazor_blazor_webassembly_c#.txt
Q: Python Write every Nth Filename from Folder to a Text File Hello I am trying to write every odd and then even filename from a Folder to a text file. import os TXT = "C:/Users/Admin/Documents/combine.txt" # Collects Files with open(TXT, "w") as a: for path, subdirs, files in os.walk(r'C:\Users\Admin\Desktop\combine'): for filename in files: f = os.path.join(path, filename) a.write("file '" + str(f) + "'" + '\n') example filenames: 01, 02, 03, 04, 05, 06, 07, 08, 09 .png wanted results: file 'C:\Users\Admin\Desktop\combine\01.png' file 'C:\Users\Admin\Desktop\combine\03.png' file 'C:\Users\Admin\Desktop\combine\05.png' file 'C:\Users\Admin\Desktop\combine\07.png' file 'C:\Users\Admin\Desktop\combine\09.png' file 'C:\Users\Admin\Desktop\combine\02.png' file 'C:\Users\Admin\Desktop\combine\04.png' file 'C:\Users\Admin\Desktop\combine\06.png' file 'C:\Users\Admin\Desktop\combine\08.png' A: As suggested by Mitchell van Zuylen, and Tomerikoo, you could use slicing and listdir to produce your desired output: Code: import os N = 2 # every 2nd filename combine_txt = "C:\Users\Admin\Documents\combine.txt" folder_of_interest = 'C:\Users\Admin\Desktop\combine' files = sorted(os.listdir(folder_of_interest)) files = [f for f in files if f.endswith('.png')] #only select .png files with open(combine_txt, "w") as a: for i in range(N): for f in files[i::N]: a.write(f"file '{folder_of_interest}\\{f}'\n") Output: combine.txt file 'C:\Users\Admin\Desktop\combine\01.png' file 'C:\Users\Admin\Desktop\combine\03.png' file 'C:\Users\Admin\Desktop\combine\05.png' file 'C:\Users\Admin\Desktop\combine\07.png' file 'C:\Users\Admin\Desktop\combine\09.png' file 'C:\Users\Admin\Desktop\combine\02.png' file 'C:\Users\Admin\Desktop\combine\04.png' file 'C:\Users\Admin\Desktop\combine\06.png' file 'C:\Users\Admin\Desktop\combine\08.png' Note: You can change N = 2 to N = 3 to list every 3rd filename in the same way.
Python Write every Nth Filename from Folder to a Text File
Hello I am trying to write every odd and then even filename from a Folder to a text file. import os TXT = "C:/Users/Admin/Documents/combine.txt" # Collects Files with open(TXT, "w") as a: for path, subdirs, files in os.walk(r'C:\Users\Admin\Desktop\combine'): for filename in files: f = os.path.join(path, filename) a.write("file '" + str(f) + "'" + '\n') example filenames: 01, 02, 03, 04, 05, 06, 07, 08, 09 .png wanted results: file 'C:\Users\Admin\Desktop\combine\01.png' file 'C:\Users\Admin\Desktop\combine\03.png' file 'C:\Users\Admin\Desktop\combine\05.png' file 'C:\Users\Admin\Desktop\combine\07.png' file 'C:\Users\Admin\Desktop\combine\09.png' file 'C:\Users\Admin\Desktop\combine\02.png' file 'C:\Users\Admin\Desktop\combine\04.png' file 'C:\Users\Admin\Desktop\combine\06.png' file 'C:\Users\Admin\Desktop\combine\08.png'
[ "As suggested by Mitchell van Zuylen, and Tomerikoo, you could use slicing and listdir to produce your desired output:\nCode:\nimport os\n\nN = 2 # every 2nd filename\n\ncombine_txt = \"C:\\Users\\Admin\\Documents\\combine.txt\"\nfolder_of_interest = 'C:\\Users\\Admin\\Desktop\\combine'\n\nfiles = sorted(os.listdir(folder_of_interest))\nfiles = [f for f in files if f.endswith('.png')] #only select .png files\n\nwith open(combine_txt, \"w\") as a:\n for i in range(N):\n for f in files[i::N]:\n a.write(f\"file '{folder_of_interest}\\\\{f}'\\n\")\n\nOutput:\ncombine.txt\nfile 'C:\\Users\\Admin\\Desktop\\combine\\01.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\03.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\05.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\07.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\09.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\02.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\04.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\06.png'\nfile 'C:\\Users\\Admin\\Desktop\\combine\\08.png'\n\nNote:\nYou can change N = 2 to N = 3 to list every 3rd filename in the same way.\n" ]
[ 0 ]
[]
[]
[ "filenames", "iteration", "python", "subdirectory" ]
stackoverflow_0074674464_filenames_iteration_python_subdirectory.txt
Q: how to resolve FATAL EXCEPTION: DefaultDispatcher-worker-4 I have written a new usecase to communicate to api which uses Flow, I am guessing I am not handing the threading properly in the Usecase between Main thread and IO thread, This is the error I get -01-18 02:20:40.555 26602-26870/com.xxx.xx.staging E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-4 Process: com.xxx.xx.staging, PID: 26602 java.lang.IllegalStateException: Event bus [Bus "fill_order"] accessed from non-main thread null at com.squareup.otto.ThreadEnforcer$2.enforce(ThreadEnforcer.java:47) at com.squareup.otto.Bus.post(Bus.java:317) at com.xxx.xx.fragments.filller.fillorder.BasefillOrderFragment.postFldeckStatusUpdateEvent(BasefillOrderFragment.java:117) at com.xxx.xx.fragments.filller.fillorder.fillOrderDataFragment.postFldeckStatusUpdateEvent(fillOrderDataFragment.java:1955) at com.xxx.xx.fragments.filller.fillorder.fillOrderDataFragment.updateView(fillOrderDataFragment.java:845) at com.xx.xx.fragments.filller.fillorder.fillOrderDataFragment.legacyUpdateView(fillOrderDataFragment.java:2317) at com.xxx.xx.clean.fillorder.presenter.BasefillDataPresenter.onStartfilllingSuccess(BasefillDataPresenter.kt:460) at com.xxx.xx.clean.fillorder.presenter.BasefillDataPresenter.handleStartfilllingClicked(BasefillDataPresenter.kt:315) at com.xxx.xx.clean.fillorder.presenter.BasefillDataPresenter.access$handleStartfilllingClicked(BasefillDataPresenter.kt:49) The error is at handleStartfilllingClicked(view, it) in . collect I am calling startfilllingUseCaseFlow usecase which might be the issue @FlowPreview fun initFlowSubscription(view: View) { launch { view.startfilllingObservableFlow .conflate() .catch { onStartfilllingError(view) } .flatMapMerge { if (!hasOpenInopIncidents()) { equipmentProvider.get()?.let { startfilllingUseCaseFlow(StartfilllingUseCaseFlow.Params(it)) }!! } else { val incidentOpenResponse = GenericResponse(false) incidentOpenResponse.error = OPEN_INCIDENTS flowOf(incidentOpenResponse) } } .collect { handleStartfilllingClicked(view, it) // ERROR IS HERE } } } private fun handleStartfilllingClicked(view: View, response: GenericResponse) { if (response.success == false && response.error == OPEN_INCIDENTS) { view.showCannotProceedInopIncidentDialog() view.hideLoader(false) return } onStartfilllingSuccess(view) // Error is here } StartfilllingUseCaseFlow class StartfilllingUseCaseFlow @Inject constructor( private val currentOrderStorage: CurrentOrderStorage, private val fillOrderRepository: fillOrderRepository, private val app: App ): FlowUseCase<StartfilllingUseCaseFlow.Params, GenericResponse>() { override suspend fun run(params: Params): Flow<GenericResponse> { val startTime = DateTime() val action = TimestampedAction( app.session.user.id, null, startTime ) return flowOf(fillOrderRepository.startfilllingSuspend( currentOrderStorage.fillOrder!!.id, action )).onEach { onSuccess(startTime, params.equipment) } .catch { e -> e.message?.let { onError(it) } } .flowOn(Dispatchers.IO) } private fun onSuccess(startTime: DateTime, equipment: Equipment) { if (currentOrderStorage.getfillOrder() == null) return currentOrderStorage.getfillOrder()!!.setStatus(fillOrderData.STATUS_fillLING) equipment.times.start = startTime app.saveState() } private fun onError(errorMessage: String) { Timber.e(errorMessage, "Error calling started fillling! %s", errorMessage) } data class Params(val equipment: Equipment) } I am guessing I am not handing IO and Main thread properly here abstract class FlowUseCase<in Params, out T>() { abstract suspend fun run(params: Params): Flow<T> suspend operator fun invoke(params: Params): Flow<T> = run(params).flowOn(Dispatchers.IO) } Could you suggest where I am gettig it wrong Thanks R A: You are trying to update the view in Coroutines default thread. All views updates must be in the MainThread. try: fun initFlowSubscription(view: View) { launch(Dispatchers.Main) { //enter code here } } This might give another error because you are doing too much process in the main thread. To avoid that you. could use "async" and update your view after: Exemple: fun initFlowSubscription(view: View) { launch(Dispatchers.Main) { val asyncValue = async(Dispatchers.IO) { //Do yours suspend fun } val value = asyncValue.await() } } This example should yours fine and avoid stopping the users UI A: Coroutines sometimes consume unhandled exceptions (this seems to be more prevalent when using async/await). Anyway, add a CoroutineExceptionHandler in these cases. CoroutineScope(IO + coroutineExceptionHandler).launch { //perform background task } val coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable -> Log.d("coroutineExceptionHandler", "yes this happened") throwable.printStackTrace() }
how to resolve FATAL EXCEPTION: DefaultDispatcher-worker-4
I have written a new usecase to communicate to api which uses Flow, I am guessing I am not handing the threading properly in the Usecase between Main thread and IO thread, This is the error I get -01-18 02:20:40.555 26602-26870/com.xxx.xx.staging E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-4 Process: com.xxx.xx.staging, PID: 26602 java.lang.IllegalStateException: Event bus [Bus "fill_order"] accessed from non-main thread null at com.squareup.otto.ThreadEnforcer$2.enforce(ThreadEnforcer.java:47) at com.squareup.otto.Bus.post(Bus.java:317) at com.xxx.xx.fragments.filller.fillorder.BasefillOrderFragment.postFldeckStatusUpdateEvent(BasefillOrderFragment.java:117) at com.xxx.xx.fragments.filller.fillorder.fillOrderDataFragment.postFldeckStatusUpdateEvent(fillOrderDataFragment.java:1955) at com.xxx.xx.fragments.filller.fillorder.fillOrderDataFragment.updateView(fillOrderDataFragment.java:845) at com.xx.xx.fragments.filller.fillorder.fillOrderDataFragment.legacyUpdateView(fillOrderDataFragment.java:2317) at com.xxx.xx.clean.fillorder.presenter.BasefillDataPresenter.onStartfilllingSuccess(BasefillDataPresenter.kt:460) at com.xxx.xx.clean.fillorder.presenter.BasefillDataPresenter.handleStartfilllingClicked(BasefillDataPresenter.kt:315) at com.xxx.xx.clean.fillorder.presenter.BasefillDataPresenter.access$handleStartfilllingClicked(BasefillDataPresenter.kt:49) The error is at handleStartfilllingClicked(view, it) in . collect I am calling startfilllingUseCaseFlow usecase which might be the issue @FlowPreview fun initFlowSubscription(view: View) { launch { view.startfilllingObservableFlow .conflate() .catch { onStartfilllingError(view) } .flatMapMerge { if (!hasOpenInopIncidents()) { equipmentProvider.get()?.let { startfilllingUseCaseFlow(StartfilllingUseCaseFlow.Params(it)) }!! } else { val incidentOpenResponse = GenericResponse(false) incidentOpenResponse.error = OPEN_INCIDENTS flowOf(incidentOpenResponse) } } .collect { handleStartfilllingClicked(view, it) // ERROR IS HERE } } } private fun handleStartfilllingClicked(view: View, response: GenericResponse) { if (response.success == false && response.error == OPEN_INCIDENTS) { view.showCannotProceedInopIncidentDialog() view.hideLoader(false) return } onStartfilllingSuccess(view) // Error is here } StartfilllingUseCaseFlow class StartfilllingUseCaseFlow @Inject constructor( private val currentOrderStorage: CurrentOrderStorage, private val fillOrderRepository: fillOrderRepository, private val app: App ): FlowUseCase<StartfilllingUseCaseFlow.Params, GenericResponse>() { override suspend fun run(params: Params): Flow<GenericResponse> { val startTime = DateTime() val action = TimestampedAction( app.session.user.id, null, startTime ) return flowOf(fillOrderRepository.startfilllingSuspend( currentOrderStorage.fillOrder!!.id, action )).onEach { onSuccess(startTime, params.equipment) } .catch { e -> e.message?.let { onError(it) } } .flowOn(Dispatchers.IO) } private fun onSuccess(startTime: DateTime, equipment: Equipment) { if (currentOrderStorage.getfillOrder() == null) return currentOrderStorage.getfillOrder()!!.setStatus(fillOrderData.STATUS_fillLING) equipment.times.start = startTime app.saveState() } private fun onError(errorMessage: String) { Timber.e(errorMessage, "Error calling started fillling! %s", errorMessage) } data class Params(val equipment: Equipment) } I am guessing I am not handing IO and Main thread properly here abstract class FlowUseCase<in Params, out T>() { abstract suspend fun run(params: Params): Flow<T> suspend operator fun invoke(params: Params): Flow<T> = run(params).flowOn(Dispatchers.IO) } Could you suggest where I am gettig it wrong Thanks R
[ "You are trying to update the view in Coroutines default thread. All views updates must be in the MainThread.\ntry:\n fun initFlowSubscription(view: View) {\n launch(Dispatchers.Main) {\n //enter code here\n }\n }\n\nThis might give another error because you are doing too much process in the main thread. To avoid that you. could use \"async\" and update your view after:\nExemple:\n fun initFlowSubscription(view: View) {\n launch(Dispatchers.Main) {\n val asyncValue = async(Dispatchers.IO) {\n //Do yours suspend fun\n }\n val value = asyncValue.await()\n }\n }\n\nThis example should yours fine and avoid stopping the users UI\n", "Coroutines sometimes consume unhandled exceptions (this seems to be more prevalent when using async/await). Anyway, add a CoroutineExceptionHandler in these cases.\nCoroutineScope(IO + coroutineExceptionHandler).launch {\n //perform background task\n}\n\nval coroutineExceptionHandler = CoroutineExceptionHandler{_, throwable ->\n Log.d(\"coroutineExceptionHandler\", \"yes this happened\")\n throwable.printStackTrace()\n}\n\n" ]
[ 0, 0 ]
[]
[]
[ "android", "android_threading", "kotlin", "kotlin_coroutines", "use_case" ]
stackoverflow_0065768099_android_android_threading_kotlin_kotlin_coroutines_use_case.txt
Q: Why return statement does not return anything? I wrote code to find subsequence string. If the character present in the given another string return true else return false, but it doesn't return anything. What is the problem in my code. import java.lang.String; public class Subsequence{ public static void main(String args[]){ String s=""; String t="ajhbuuhyc"; Solution obj=new Solution(); obj.find(s,t); } } class Solution{ public boolean find(String s,String t){ int S=s.length(); int T=t.length(); int i=0,j=0; if(S==0) return true; if(S>T || T==0) return false; while(i<S && j<T){ if(s.charAt(i)==t.charAt(j)) i++; j++; } return i==S; } A: every method in java has a return; value. if you write this code public void foo(){ return; } ide tell you that 'return' is unnecessary as the last statement in a 'void' method return has two options it stops the method it return some data public static int foo() { return 2 + 2; } public static void main(String[] args) { System.out.println(foo()); // 4 } In your case, you ignore data from method find. Write if (find("", "")) System.out.println("true"); // true System.out.println(find("", "")); // true
Why return statement does not return anything?
I wrote code to find subsequence string. If the character present in the given another string return true else return false, but it doesn't return anything. What is the problem in my code. import java.lang.String; public class Subsequence{ public static void main(String args[]){ String s=""; String t="ajhbuuhyc"; Solution obj=new Solution(); obj.find(s,t); } } class Solution{ public boolean find(String s,String t){ int S=s.length(); int T=t.length(); int i=0,j=0; if(S==0) return true; if(S>T || T==0) return false; while(i<S && j<T){ if(s.charAt(i)==t.charAt(j)) i++; j++; } return i==S; }
[ "every method in java has a return; value. if you write this code\npublic void foo(){\n return;\n}\n\nide tell you that 'return' is unnecessary as the last statement in a 'void' method\nreturn has two options\n\nit stops the method\n\nit return some data\n public static int foo() {\n return 2 + 2;\n }\n\n public static void main(String[] args) {\n System.out.println(foo()); // 4\n }\n\n\n\nIn your case, you ignore data from method find. Write\nif (find(\"\", \"\"))\n System.out.println(\"true\"); // true\n\nSystem.out.println(find(\"\", \"\")); // true\n\n" ]
[ 0 ]
[]
[]
[ "java", "return", "string", "subsequence" ]
stackoverflow_0074674524_java_return_string_subsequence.txt
Q: increment the name of the variable, ex: prdt1, prdt2, prdt3 ...etc I didn't try anything because I don't even know where to start... the program would associate every item of the list to the variables like (name)1, (name)2, (name)3, and so on to the number of items the list has. prdt = ["WD40", "001", "oleo de carro, 1L", "liquidos", "seccao 1", 5, 30] prdt1 ="WD40" prdt2 ="001" prdt3 ="oleo de carro, 1L" prdt4 ="liquidos" a program that creates a variable incremented by 1 in a for a loop. A: Basically with python version above 3.8 you can use eval and walrus operator in order to achieve this behaviour. You will get variables with names corresponding to your list items for idx, item in enumerate(prdt): eval(f"({item}{idx}:={item})") If you look at this weird syntax in eval it's walrus operator := combined with a parenthesis and all that in a f-string. Very unreadable and ugly solution imho, but eval only allows for expressions, NOT compound statements (so you cannot use the regular assignment with = ). And you have int values in your list, which will cause the above code to fail, since var name in python cannot be an int... 5=5 is not a legal code, neither are values with spaces...Overall sorry to say, but this question does not make too much sense to be honest. But in general it sounds like a terrible idea to be honest (whatever is your usecase). If you need to associate specific names with values you should use dict probably.
increment the name of the variable, ex: prdt1, prdt2, prdt3 ...etc
I didn't try anything because I don't even know where to start... the program would associate every item of the list to the variables like (name)1, (name)2, (name)3, and so on to the number of items the list has. prdt = ["WD40", "001", "oleo de carro, 1L", "liquidos", "seccao 1", 5, 30] prdt1 ="WD40" prdt2 ="001" prdt3 ="oleo de carro, 1L" prdt4 ="liquidos" a program that creates a variable incremented by 1 in a for a loop.
[ "Basically with python version above 3.8 you can use eval and walrus operator in order to achieve this behaviour. You will get variables with names corresponding to your list items\nfor idx, item in enumerate(prdt):\n eval(f\"({item}{idx}:={item})\")\n\nIf you look at this weird syntax in eval it's walrus operator := combined with a parenthesis and all that in a f-string. Very unreadable and ugly solution imho, but eval only allows for expressions, NOT compound statements (so you cannot use the regular assignment with = ).\nAnd you have int values in your list, which will cause the above code to fail, since var name in python cannot be an int... 5=5 is not a legal code, neither are values with spaces...Overall sorry to say, but this question does not make too much sense to be honest.\nBut in general it sounds like a terrible idea to be honest (whatever is your usecase). If you need to associate specific names with values you should use dict probably.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074674932_python.txt
Q: dotnet 6 google authentication is returning not succeeded =false This is asp.net core web api project and dotnet 6. This is the issue i am facing succeeded is returning false as specified above? Response is this This is the program.cs file using Microsoft.AspNetCore.Authentication.Cookies; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddAuthentication(o => { o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddGoogle(g => { g.ClientId = "167221756435"; g.ClientSecret = "GO"; g.SaveTokens = true; }); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
dotnet 6 google authentication is returning not succeeded =false
This is asp.net core web api project and dotnet 6. This is the issue i am facing succeeded is returning false as specified above? Response is this This is the program.cs file using Microsoft.AspNetCore.Authentication.Cookies; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddAuthentication(o => { o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie() .AddGoogle(g => { g.ClientId = "167221756435"; g.ClientSecret = "GO"; g.SaveTokens = true; }); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
[]
[]
[ "To connect to Google authentication with .NET 6, you need to first configure the authentication service by registering your app in the Google API Console. After this step, you can use the Google.Apis.Auth library to create a new ClientSecrets object containing your registered app credentials. Then you can use the GoogleWebAuthorizationBroker.AuthorizeAsync method to request authorization from the user and acquire access credentials. For an example of how this is done, you can refer to this documentation: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-3.1\n" ]
[ -1 ]
[ ".net_core", "asp.net_core", "asp.net_core_webapi", "asp.net_web_api", "c#" ]
stackoverflow_0074674612_.net_core_asp.net_core_asp.net_core_webapi_asp.net_web_api_c#.txt
Q: How do I add resources such as text files or exe files into my application? I tried this code static HOST_FILE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png"); fn main() { let host_str = std::str::from_utf8(HOST_FILE). unwrap(); println!("Hosts are:\n{}", &host_str[..42]); } But it shows me an error: thread 'main' panicked at 'called Result::unwrap() on an Err value: Utf8Error { valid_up_to: 66, error_len: Some(1) }', src\main.rs:48:51 stack backtrace A: static IMAGE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png"); fn main() { println!("Image: {:?}", IMAGE); } Although I recommend using a path relative to your source code, like static IMAGE: &'static [u8] = include_bytes!("../cbimage.png"); fn main() { println!("Image: {:?}", IMAGE); } And place cbimage.png next to your Cargo.toml.
How do I add resources such as text files or exe files into my application?
I tried this code static HOST_FILE: &'static [u8] = include_bytes!("C:\\Users\\Downloads\\cbimage.png"); fn main() { let host_str = std::str::from_utf8(HOST_FILE). unwrap(); println!("Hosts are:\n{}", &host_str[..42]); } But it shows me an error: thread 'main' panicked at 'called Result::unwrap() on an Err value: Utf8Error { valid_up_to: 66, error_len: Some(1) }', src\main.rs:48:51 stack backtrace
[ "static IMAGE: &'static [u8] = include_bytes!(\"C:\\\\Users\\\\Downloads\\\\cbimage.png\");\n\nfn main() {\n println!(\"Image: {:?}\", IMAGE);\n}\n\nAlthough I recommend using a path relative to your source code, like\nstatic IMAGE: &'static [u8] = include_bytes!(\"../cbimage.png\");\n\nfn main() {\n println!(\"Image: {:?}\", IMAGE);\n}\n\nAnd place cbimage.png next to your Cargo.toml.\n" ]
[ 0 ]
[]
[]
[ "resources", "rust" ]
stackoverflow_0074673817_resources_rust.txt
Q: Why do I get a null username when using Apple Sign In in my Flutter app? I am trying to implement the Apple social login within my Flutter IOS App. I succeed to successfully connect, but in the credential received it seems there Is no personal information in it such as: The username: which is null The email: I only get the iCloud address, even when I select a personal email when signing in. I am using firebase_auth: ^3.7.0 here is my code for connecting with apple: signInWithApple() async { final appleProvider = AppleAuthProvider() ..addScope("email") ..addScope("fullName"); try { await _auth.signInWithProvider(appleProvider).then((credential) async { print(credential.toString()); }); } on FirebaseAuthException catch (errorMessage) { print(errorMessage); } } I have also attached the credential I get from this code. [![received credentials][1]][1] [1]: https://i.stack.imgur.com/fBKXn.png Do you have any idea of what is going wrong ? A: Based on the code you've shared, it looks like you're using the firebase_auth package to implement the Apple social login within your Flutter app. It seems that you're able to successfully connect to Apple using the AppleAuthProvider, but the credential object that you receive does not contain the expected information (i.e., the username and email address). There are a few reasons why this might be happening. One possibility is that you have not properly configured your app to request the necessary permissions from the user when they sign in with Apple. In your code, you're using the addScope method to request the "email" and "fullName" scopes, but it's possible that these are not sufficient to access the user's personal information. Another possibility is that the user has not granted your app permission to access their personal information. When a user signs in with Apple, they will be prompted to review the permissions that your app is requesting and decide whether to grant or deny them. If the user denies your app access to their personal information, then the credential object that you receive will not contain that information. It's also worth noting that the credential object returned by signInWithProvider only contains the information that is provided by the underlying authentication provider (in this case, Apple). If the provider does not include certain information in the credential, then that information will not be available to your app. I would recommend checking the documentation for the signInWithProvider method to ensure that you're using it correctly, and verifying that your app is properly configured to request the necessary permissions from the user. You can also try prompting the user to grant your app access to their personal information if they have not already done so.
Why do I get a null username when using Apple Sign In in my Flutter app?
I am trying to implement the Apple social login within my Flutter IOS App. I succeed to successfully connect, but in the credential received it seems there Is no personal information in it such as: The username: which is null The email: I only get the iCloud address, even when I select a personal email when signing in. I am using firebase_auth: ^3.7.0 here is my code for connecting with apple: signInWithApple() async { final appleProvider = AppleAuthProvider() ..addScope("email") ..addScope("fullName"); try { await _auth.signInWithProvider(appleProvider).then((credential) async { print(credential.toString()); }); } on FirebaseAuthException catch (errorMessage) { print(errorMessage); } } I have also attached the credential I get from this code. [![received credentials][1]][1] [1]: https://i.stack.imgur.com/fBKXn.png Do you have any idea of what is going wrong ?
[ "Based on the code you've shared, it looks like you're using the firebase_auth package to implement the Apple social login within your Flutter app. It seems that you're able to successfully connect to Apple using the AppleAuthProvider, but the credential object that you receive does not contain the expected information (i.e., the username and email address).\nThere are a few reasons why this might be happening. One possibility is that you have not properly configured your app to request the necessary permissions from the user when they sign in with Apple. In your code, you're using the addScope method to request the \"email\" and \"fullName\" scopes, but it's possible that these are not sufficient to access the user's personal information.\nAnother possibility is that the user has not granted your app permission to access their personal information. When a user signs in with Apple, they will be prompted to review the permissions that your app is requesting and decide whether to grant or deny them. If the user denies your app access to their personal information, then the credential object that you receive will not contain that information.\nIt's also worth noting that the credential object returned by signInWithProvider only contains the information that is provided by the underlying authentication provider (in this case, Apple). If the provider does not include certain information in the credential, then that information will not be available to your app.\nI would recommend checking the documentation for the signInWithProvider method to ensure that you're using it correctly, and verifying that your app is properly configured to request the necessary permissions from the user. You can also try prompting the user to grant your app access to their personal information if they have not already done so.\n" ]
[ 0 ]
[]
[]
[ "apple_sign_in", "firebase_authentication", "flutter" ]
stackoverflow_0074674978_apple_sign_in_firebase_authentication_flutter.txt
Q: Formatting text in css Can you tell me how to make the text selection the same as in the picture below I have no idea how to make such an effect, can you help?
Formatting text in css
Can you tell me how to make the text selection the same as in the picture below I have no idea how to make such an effect, can you help?
[]
[]
[ "You can use a pseudo selector for this.\nIf your text is in a <p> tag, you could try styling it with something like this:\np::selection {\n background: #fff;\n color: #ff0000;\n}\n\nRead more about selecting text css: https://css-tricks.com/almanac/selectors/s/selection/\n" ]
[ -2 ]
[ "css", "html" ]
stackoverflow_0074674961_css_html.txt
Q: How to pass image from one activity to another activity I am getting picture from gallery using this code.i want to pass this image view to another activity and show it.In second activity i want to catch it.It is same as data passing through an activities but the images are not working in that method.Any suggetions? val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> imageView.setImageURI(uri) } val button = findViewById<Button>(R.id.button) button.setOnClickListener { getContent.launch("image/*") } val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> imageView.setImageURI(uri) } val button = findViewById<Button>(R.id.button) button.setOnClickListener { getContent.launch("image/*") } A: Convert the URI to string and add it to intent in your First activity intent.putExtra("img_uri", selectedImage.toString()); In your second activity get the string and parse the string to get uri Intent intent = getIntent(); String uriStr = intent.getStringExtra("img_uri"); Uri uri = Uri.parse(uriStr); imageview.setImageURI(uri) ; To Start Second Activity Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("img_uri", selectedImage.toString()); startActivity(intent); A: Instead of .getContent() use .getDocument() and take persistable uri permission in on activity result. The rest the same as proposed by Sidharth Mudgil.
How to pass image from one activity to another activity
I am getting picture from gallery using this code.i want to pass this image view to another activity and show it.In second activity i want to catch it.It is same as data passing through an activities but the images are not working in that method.Any suggetions? val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> imageView.setImageURI(uri) } val button = findViewById<Button>(R.id.button) button.setOnClickListener { getContent.launch("image/*") } val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> imageView.setImageURI(uri) } val button = findViewById<Button>(R.id.button) button.setOnClickListener { getContent.launch("image/*") }
[ "Convert the URI to string and add it to intent in your First activity\nintent.putExtra(\"img_uri\", selectedImage.toString());\n\nIn your second activity get the string and parse the string to get uri\nIntent intent = getIntent(); \nString uriStr = intent.getStringExtra(\"img_uri\"); \nUri uri = Uri.parse(uriStr);\nimageview.setImageURI(uri) ;\n\nTo Start Second Activity\nIntent intent = new Intent(FirstActivity.this, SecondActivity.class);\nintent.putExtra(\"img_uri\", selectedImage.toString());\nstartActivity(intent);\n\n", "Instead of .getContent() use .getDocument() and take persistable uri permission in on activity result.\nThe rest the same as proposed by Sidharth Mudgil.\n" ]
[ 0, 0 ]
[]
[]
[ "android", "kotlin" ]
stackoverflow_0074674832_android_kotlin.txt
Q: invert 2 items in a list Python I'm building a Formula1 race simulator in python and I'm trying to make a overtake function, basically, i've all the drivers stored in a list and once one of the drivers surpasses the other I need to invert their position in the list ['hamilton','vertsappen','perez','sainz'] ['hamilton','perez','verstappen','sainz'] is there any way to do so? since now I have tried to store the original positions in a temporary variable but I keep finding myself with duplicates in the list original temporary variables overtaken temp = Valteri Bottas overtaker temp = Nicholas Latifi after the inverting overtaken temp = Valteri Bottas overtaker temp = Valteri Bottas A: A simple overtake function: def overtake_driver(drivers, overtaker, overtaken): # Find the indices of the overtaker and the overtaken in the list of drivers overtaker_index = drivers.index(overtaker) overtaken_index = drivers.index(overtaken) # Swap the positions of the overtaker and the overtaken in the list of drivers drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index] # Return the updated list of drivers return drivers Basically, fetch the indices of the respective drivers and just swap them in a double assignment! A: A lazy way to do it. a = ['hamilton','vertsappen','perez','sainz'] a.remove('vertsappen') a.insert(2, 'vertsappen') print(a) #['hamilton','perez','verstappen','sainz'] A: i solved the problem, it was much easier then i thought: grid[0], grid[1] = grid[1] = grid[0]
invert 2 items in a list Python
I'm building a Formula1 race simulator in python and I'm trying to make a overtake function, basically, i've all the drivers stored in a list and once one of the drivers surpasses the other I need to invert their position in the list ['hamilton','vertsappen','perez','sainz'] ['hamilton','perez','verstappen','sainz'] is there any way to do so? since now I have tried to store the original positions in a temporary variable but I keep finding myself with duplicates in the list original temporary variables overtaken temp = Valteri Bottas overtaker temp = Nicholas Latifi after the inverting overtaken temp = Valteri Bottas overtaker temp = Valteri Bottas
[ "A simple overtake function:\ndef overtake_driver(drivers, overtaker, overtaken):\n # Find the indices of the overtaker and the overtaken in the list of drivers\n overtaker_index = drivers.index(overtaker)\n overtaken_index = drivers.index(overtaken)\n\n # Swap the positions of the overtaker and the overtaken in the list of drivers\n drivers[overtaker_index], drivers[overtaken_index] = drivers[overtaken_index], drivers[overtaker_index]\n\n # Return the updated list of drivers\n return drivers\n\nBasically, fetch the indices of the respective drivers and just swap them in a double assignment!\n", "A lazy way to do it.\na = ['hamilton','vertsappen','perez','sainz']\n\na.remove('vertsappen')\n\na.insert(2, 'vertsappen')\n\nprint(a)\n\n#['hamilton','perez','verstappen','sainz']\n\n", "i solved the problem, it was much easier then i thought:\ngrid[0], grid[1] = grid[1] = grid[0]\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074674950_python.txt
Q: Polygon from world file In order to get polygons with the boundary of raster images from .jpg + .jgw pairs, I'm doing this: library(terra) r <- rectify(rast("DJI_0371.jpg")) p <- as.polygons(is.na(r))[1,] But it is quite slow for a long list of jpg + .jgw pairs, I think because of rectify(). Is there a way to get the polygon directly from the imported .jpg + .jgw pairs, avoiding the rectify()? Would this be significantly faster? https://www.dropbox.com/s/0lvezqddapmv1g2/DJI_0371.zip?dl=0 Edit: Following robertdj: > t0 <- Sys.time() > r <- rast("DJI_0371.jpg") Warning message: [rast] the data in this file are rotated. Use 'rectify' to fix that > print(Sys.time()-t0) Time difference of 0.007530451 secs > > t0 <- Sys.time() > r2 <- rectify(r) > print(Sys.time()-t0) Time difference of 0.1370528 secs > > t0 <- Sys.time() > p <- as.polygons(is.na(r2))[1,] > print(Sys.time()-t0) Time difference of 0.02361417 secs > t0 <- Sys.time() > p <- as.polygons(is.na( rectify(rast("DJI_0371.jpg"))))[1,] Warning message: [rast] the data in this file are rotated. Use 'rectify' to fix that > print(Sys.time()-t0) Time difference of 0.1690121 secs So the 2nd question is answered: avoiding the rectify() would be significantly faster. The 1st question remains. A: Solved with gdalUtilitis::gdalinfo() > t0 <- Sys.time() > a <- gdalinfo("DJI_0371.jpg", json=TRUE, quiet=TRUE) > a <- jsonify::from_json(a) > a <- matrix(unlist(a$cornerCoordinates)[1:8], nrow=4, byrow=TRUE) > colnames(a) <- c("lon", "lat") > p <- vect(a,"polygons") > print(Sys.time()-t0) Time difference of 0.009047747 secs > plot(p)
Polygon from world file
In order to get polygons with the boundary of raster images from .jpg + .jgw pairs, I'm doing this: library(terra) r <- rectify(rast("DJI_0371.jpg")) p <- as.polygons(is.na(r))[1,] But it is quite slow for a long list of jpg + .jgw pairs, I think because of rectify(). Is there a way to get the polygon directly from the imported .jpg + .jgw pairs, avoiding the rectify()? Would this be significantly faster? https://www.dropbox.com/s/0lvezqddapmv1g2/DJI_0371.zip?dl=0 Edit: Following robertdj: > t0 <- Sys.time() > r <- rast("DJI_0371.jpg") Warning message: [rast] the data in this file are rotated. Use 'rectify' to fix that > print(Sys.time()-t0) Time difference of 0.007530451 secs > > t0 <- Sys.time() > r2 <- rectify(r) > print(Sys.time()-t0) Time difference of 0.1370528 secs > > t0 <- Sys.time() > p <- as.polygons(is.na(r2))[1,] > print(Sys.time()-t0) Time difference of 0.02361417 secs > t0 <- Sys.time() > p <- as.polygons(is.na( rectify(rast("DJI_0371.jpg"))))[1,] Warning message: [rast] the data in this file are rotated. Use 'rectify' to fix that > print(Sys.time()-t0) Time difference of 0.1690121 secs So the 2nd question is answered: avoiding the rectify() would be significantly faster. The 1st question remains.
[ "Solved with gdalUtilitis::gdalinfo()\n> t0 <- Sys.time()\n> a <- gdalinfo(\"DJI_0371.jpg\", json=TRUE, quiet=TRUE)\n> a <- jsonify::from_json(a)\n> a <- matrix(unlist(a$cornerCoordinates)[1:8], nrow=4, byrow=TRUE)\n> colnames(a) <- c(\"lon\", \"lat\") \n> p <- vect(a,\"polygons\")\n> print(Sys.time()-t0)\nTime difference of 0.009047747 secs\n> plot(p)\n\n" ]
[ 0 ]
[]
[]
[ "r", "terra" ]
stackoverflow_0074638626_r_terra.txt
Q: How to build Perfect Hash in C++? I'd like to know how to build a Perfect Hash in C++. Perfect Hash is such a hash that 1) Has no collisions at all, 2) Is built only for fixed set of values, 3) Maps set of N values to a range of numbers of 0 .. N * 1.23 - 1, i.e. it maps not to numbers till N, but till some bigger multiple of N, like N * 1.23. I've read this Wiki article about Perfect Hash. And decided to post this short question only to send my own Answer. So I don't provide any Minimal Reproducible Example, only because answer is fully contained. A: Suppose we have set S of N integer elements. We want to perfect-hash this set. There are different ways of building perfect hash. But one way, according to Wiki, is following way: First we choose some function g(x) = k * x mod p mod n, where P is some quite large prime. And K is some random constant. N is number of elements in a set. Then we map through g(x) all elements of a set, these elements map to some integers in a range 0..N-1 which may collide. Collided integers form separate buckets. We create infinite amount of Hash functions. For example in my below C++ code I use same as g(x) functions equal to Hash[i](x) = RandomConstant[i] * x mod Prime[i] mod M, where M = N * 1.23, here 1.23 is some small constant, it can be something like 1.2-1.5. Each bucket B_i is hashed separately in such a way that it forms set K_i = Hash[l](x) for x in B_i, so that l is minimal and |K_i| = |B_i|, and K_i doesn't intersect with previous K_i. Each minimal found l is stored as sigma(i) = l. sigma(i) is compressed into bit vector in such a way that we can get value l = sigma(i) in O(1) time. Finally, to get perfect hash of value x we do PerfectHash(x) = Hash[sigma(g(x))](x). Full code below. It generates N random numbers, then perfect hashes them and finally outputs amount of bits per number. Try it online! #include <cstdint> #include <bit> #include <vector> #include <random> #include <cstring> #include <stdexcept> #include <string> #include <iostream> #include <iomanip> #include <algorithm> #include <unordered_map> #include <array> #define ASSERT_MSG(cond, msg) { if (!(cond)) throw std::runtime_error("Assertion (" #cond ") failed at line " + std::to_string(__LINE__) + "! Msg: '" + std::string(msg) + "'."); } #define ASSERT(cond) ASSERT_MSG(cond, "") #define DASSERT_MSG(cond, msg) ASSERT_MSG(cond, msg) #define DASSERT(cond) DASSERT_MSG(cond, "") using u8 = uint8_t; using u32 = uint32_t; using u64 = uint64_t; template <typename T> bool IsPrime(T const & n) { if (n % 2 == 0) return false; for (size_t d = 3; d * d <= n; d += 2) if (n % d == 0) return false; return true; } template <typename T> T NextPrime(T const & i) { if (i <= 2) return 2; for (T j = i | 1;; j += 2) if (IsPrime(j)) return j; } class BitVector { static size_t constexpr index_block = 1 << 9; public: BitVector() {} BitVector(size_t size) : size_(size), bits_((size_ + 7) / 8) {} void Clear() { size_ = 0; bits_.clear(); index_.clear(); } size_t Size() const { return size_; } bool Get(size_t i) const { return (bits_[i / 8] >> (i % 8)) & u8(1); } void Set(size_t i, bool val = true) { if (val) bits_[i / 8] |= u8(1) << (i % 8); else bits_[i / 8] &= ~(u8(1) << (i % 8)); } void Push(bool val) { ++size_; if (size_ - 1 >= bits_.size() * 8) bits_.resize((size_ + 7) / 8); Set(size_ - 1, val); } void Index() { index_.clear(); for (size_t i = 0; i < size_; i += index_block) { size_t sum = 0; size_t const portion = std::min(index_block, size_ - i); for (size_t k = i; k < i + portion; k += 64) if (i + portion - k >= 64) sum += std::popcount(*(u64*)&bits_[k / 8]); else { u64 x = 0; std::memcpy(&x, &bits_[k / 8], bits_.size() - k / 8); sum += std::popcount(x); } index_.push_back(index_.empty() ? sum : (index_.back() + sum)); } } size_t Select1(size_t idx) const { size_t const d = std::distance(index_.data(), std::upper_bound(index_.data(), index_.data() + index_.size(), idx)); ASSERT_MSG(d < index_.size(), "idx " + std::to_string(idx)); size_t const prev_sum = d == 0 ? 0 : index_[d - 1], hi = std::min<size_t>(size_, index_block * (d + 1)); size_t csum = 0, i = 0; u64 word = 0; for (i = index_block * d; i < hi; i += 64) { size_t const portion = std::min<size_t>(hi - i, 64); size_t word_sum = 0; if (portion == 64) word = *(u64*)&bits_[i / 8]; else { word = 0; std::memcpy(&word, &bits_[i / 8], bits_.size() - i / 8); } word_sum = std::popcount(word); if (prev_sum + csum + word_sum > idx) break; csum += word_sum; } size_t sum0 = 0; while (true) { size_t const i1 = std::countr_zero(word); ASSERT(i1 < 64); if (prev_sum + csum + sum0 >= idx) { ASSERT(prev_sum + csum + sum0 == idx); ASSERT(Get(i + i1)); return i + i1; } word &= word - 1; ++sum0; } } std::string Dump() const { std::string r; for (size_t i = 0; i < size_; ++i) r.append(1, Get(i) ? '1' : '0'); return r; } u64 Word(size_t i) const { return (*(u64*)&bits_[i / 8]) >> (i % 8); } private: size_t size_ = 0; std::vector<u8> bits_; std::vector<size_t> index_; }; class GammaBitVector { static size_t constexpr index_block = 1 << 7; public: template <typename T> void GammaEncodeVec(std::vector<T> const & nums) { for (auto n: nums) { auto [x, b] = GammaEncode(std::max<size_t>(n, 1) - 1); //std::cout << n << ": " << b << " " << x << std::endl; for (size_t i = 0; i < b; ++i) { bv_.Push(bool(x & 1)); x >>= 1; } } //std::cout << "GammaEncodedVec " << bv_.Size() << std::endl; //std::cout << bv_.Dump() << std::endl << std::endl; } void Index() { size_t i = 0, cnt = 0; while (i < bv_.Size()) { auto const [n, ebits, dbits] = GammaDecode(bv_.Word(i)); ++cnt; i += ebits; if (cnt < index_block && i < bv_.Size()) continue; index_.push_back(i); cnt = 0; } } size_t Get(size_t i) const { size_t j = i / index_block * index_block, sum = i / index_block > 0 ? index_.at(i / index_block - 1) : 0; while (sum < bv_.Size()) { auto const [n, ebits, dbits] = GammaDecode(bv_.Word(sum)); if (j >= i) return n + 1; ++j; sum += ebits; } ASSERT(false); } size_t Size() const { return bv_.Size(); } size_t GetBitOffset(size_t i) const { size_t j = i / index_block * index_block, sum = i / index_block > 0 ? index_.at(i / index_block - 1) : 0; while (sum < bv_.Size()) { auto const [n, ebits, dbits] = GammaDecode(bv_.Word(sum)); if (j >= i) return sum; ++j; sum += ebits; } ASSERT(false); } private: static u64 Shl(u64 w, size_t cnt) { return cnt >= 64 ? u64(0) : (w << cnt); } static u64 Shr(u64 w, size_t cnt) { return cnt >= 64 ? u64(0) : (w >> cnt); } static u64 Mask(size_t n) { return n >= 64 ? ~u64(0) : (u64(1) << n) - 1; } static size_t NumBits(u64 n) { return 64 - std::countl_zero(n); } static std::tuple<u64, size_t> GammaEncode(u64 n) { ++n; DASSERT(n != 0); size_t const nbits = NumBits(n); static auto lo = []{ std::array<u32, 32> r{}; for (size_t i = 0; i < r.size(); ++i) r[i] = u32(1) << i; return r; }(); size_t const rnbits = nbits - 1; DASSERT(rnbits < lo.size()); return std::make_tuple((Shl(n & Mask(rnbits), nbits) | u64(lo[rnbits])), rnbits + nbits); } static std::tuple<u64, size_t, size_t> GammaDecode(u64 n) { static size_t constexpr c_tab_bits = 8; static auto tab = []{ std::array<u8, (1 << c_tab_bits)> r{}; for (size_t i = 0; i < r.size(); ++i) { size_t j = i, sr = 0; if (i == 0) sr = 0xFF; else while (!bool(j & 1)) { ++sr; j >>= 1; } r[i] = u8(sr); } return r; }(); size_t cnt = tab[n & Mask(c_tab_bits)]; if (cnt == 0xFF) { ASSERT(n != 0); cnt = 0; u64 m = n; while (!bool(m & 1)) { ++cnt; m >>= 1; } ASSERT(cnt <= 31); } return std::make_tuple(u64((((n >> (cnt + 1)) & Mask(cnt)) | (u64(1) << cnt)) - 1), size_t(2 * cnt + 1), size_t(cnt + 1)); } BitVector bv_; std::vector<size_t> index_; }; class PerfectHash { public: // https://en.wikipedia.org/wiki/Perfect_hash_function void Build(std::vector<u64> const & nums) { size_t const n = nums.size(); m_ = 1.5 * n; n_ = n; primes_.clear(); primes_.push_back({rng_(), NextPrime(n_)}); primes_.push_back({rng_(), NextPrime(m_)}); std::vector<std::vector<size_t>> Bs(n); for (size_t i = 0; i < n; ++i) { Bs[g(nums[i])].push_back(nums[i]); //std::cout << "i " << i << ": " << nums[i] << ": " << g(nums[i]) << ", "; } //std::cout << std::endl; std::vector<u64> K; BitVector Tb(m_); std::vector<u32> sigma_l(n); size_t max_bucket_size = 0; for (size_t i = 0; i < n; ++i) { auto const & B = Bs.at(i); max_bucket_size = std::max<size_t>(max_bucket_size, B.size()); if (B.empty()) continue; size_t l = 0; for (l = 1; l < 10'000; ++l) { bool exists = false; K.clear(); for (size_t iB = 0; iB < B.size(); ++iB) { auto const j = B[iB]; auto const h = HashFunc(l, j); if (Tb.Get(h)) { exists = true; break; } for (auto k: K) if (k == h) { exists = true; break; } if (exists) break; K.push_back(h); } if (!exists) break; } ASSERT(l < 10'000); sigma_l[i] = l; for (auto j: K) Tb.Set(j); } sigma_bv_.Clear(); //std::cout << "MaxBucket " << max_bucket_size << std::endl; //std::cout << "Sigma: "; for (size_t i = 0; i < sigma_l.size(); ++i) { auto const l = sigma_l[i]; //std::cout << l << ", "; sigma_bv_.Push(1); for (size_t i = 0; i + 1 < l; ++i) sigma_bv_.Push(0); } //std::cout << std::endl; sigma_gbv_.GammaEncodeVec(sigma_l); sigma_gbv_.Index(); //std::cout << "Sigma from GBV: "; for (size_t i = 0; i < sigma_l.size(); ++i) { //std::cout << sigma_gbv_.Get(i) << ", "; ASSERT_MSG(std::max<size_t>(1, sigma_l[i]) == sigma_gbv_.Get(i), "i " + std::to_string(i) + " sigma_l " + std::to_string(std::max<size_t>(1, sigma_l[i])) + " sigma_Get(i) " + std::to_string(sigma_gbv_.Get(i)) + " sigma_GetOff(i) " + std::to_string(sigma_gbv_.GetBitOffset(i)) + " sigma_GetOff(i - 1) " + std::to_string(sigma_gbv_.GetBitOffset(i - 1))); } //std::cout << std::endl; sigma_bv_.Index(); for (size_t i = 0; i < sigma_bv_.Size(); ++i) { //std::cout << (sigma_bv_.Get(i) ? "1" : "0"); } //std::cout << std::endl; } size_t Hash(u64 const & x) { return HashFunc(Sigma(g(x)), x); } size_t NumBits() const { return sigma_gbv_.Size(); } size_t HashFunc(size_t i, u64 const & x) { while (i >= primes_.size()) primes_.push_back({rng_(), NextPrime(primes_.back().second + 1)}); auto const [k, p] = primes_[i]; auto v = (k * x) % p; size_t const mod = i == 0 ? n_ : m_; while (v >= mod) v -= mod; return v; } size_t g(u64 const & x) { return HashFunc(0, x); } size_t Sigma(size_t i) { size_t const i1 = sigma_gbv_.Get(i); //std::cout << "Sigma: " << i << ": " << i1 << std::endl; return i1; /* size_t cnt = 0; for (size_t i = i1 + 1, size = sigma_bv_.Size(); i < size; ++i, ++cnt) { std::cout << i << " (" << std::boolalpha << sigma_bv_.Get(i) << "), "; if (sigma_bv_.Get(i)) break; } std::cout << std::endl << "Val: " << (cnt + 1) << std::endl; return cnt + 1; */ } size_t N() const { return n_; } size_t M() const { return m_; } private: std::mt19937_64 rng_{123}; size_t n_ = 0, m_ = 0; BitVector sigma_bv_; GammaBitVector sigma_gbv_; std::vector<std::pair<u64, u64>> primes_; }; int main() { try { std::mt19937_64 rng{123}; std::vector<u64> nums(1 << 17); for (size_t i = 0; i < nums.size(); ++i) nums[i] = rng(); PerfectHash ph; ph.Build(nums); std::cout << "Nums " << nums.size() << std::endl; std::cout << "PerfectHash Bits " << ph.NumBits() << ", " << std::setprecision(3) << (double(ph.NumBits()) / nums.size()) << " bits/num" << std::endl; std::unordered_map<u64, u64> hashes; for (size_t i = 0; i < nums.size(); ++i) { //std::cout << "i " << i << std::endl; auto const hash = ph.Hash(nums[i]); if (i < 16) { //std::cout << nums[i] << ": " << hash << std::endl; } ASSERT(hash < ph.M()); ASSERT_MSG(!hashes.count(hash), "i " + std::to_string(i) + " nums[i] " + std::to_string(nums[i]) + " hash " + std::to_string(hash) + " g(x) " + std::to_string(ph.g(nums[i])) + " sigma " + std::to_string(ph.Sigma(ph.g(nums[i]))) + " hash_func " + std::to_string(ph.HashFunc(ph.Sigma(ph.g(nums[i])), nums[i])) + " prev_i " + std::to_string(hashes.at(hash)) + " nums[hashes.at(hash)] " + std::to_string(nums[hashes.at(hash)]) + " prev_g(x) " + std::to_string(ph.g(nums[hashes.at(hash)])) + " prev_sigma " + std::to_string(ph.Sigma(ph.g(nums[hashes.at(hash)]))) + " prev_hash_func " + std::to_string(ph.HashFunc(ph.Sigma(ph.g(nums[hashes.at(hash)])), nums[hashes.at(hash)])) ); hashes[hash] = i; } ASSERT(hashes.size() == nums.size()); return 0; } catch (std::exception const & ex) { std::cout << "Exception: " << ex.what() << std::endl; return -1; } } Console Output: Nums 131072 PerfectHash Bits 244430, 1.86 bits/num
How to build Perfect Hash in C++?
I'd like to know how to build a Perfect Hash in C++. Perfect Hash is such a hash that 1) Has no collisions at all, 2) Is built only for fixed set of values, 3) Maps set of N values to a range of numbers of 0 .. N * 1.23 - 1, i.e. it maps not to numbers till N, but till some bigger multiple of N, like N * 1.23. I've read this Wiki article about Perfect Hash. And decided to post this short question only to send my own Answer. So I don't provide any Minimal Reproducible Example, only because answer is fully contained.
[ "Suppose we have set S of N integer elements. We want to perfect-hash this set.\nThere are different ways of building perfect hash. But one way, according to Wiki, is following way:\n\nFirst we choose some function g(x) = k * x mod p mod n, where P is some quite large prime. And K is some random constant. N is number of elements in a set.\n\nThen we map through g(x) all elements of a set, these elements map to some integers in a range 0..N-1 which may collide. Collided integers form separate buckets.\n\nWe create infinite amount of Hash functions. For example in my below C++ code I use same as g(x) functions equal to Hash[i](x) = RandomConstant[i] * x mod Prime[i] mod M, where M = N * 1.23, here 1.23 is some small constant, it can be something like 1.2-1.5.\n\nEach bucket B_i is hashed separately in such a way that it forms set K_i = Hash[l](x) for x in B_i, so that l is minimal and |K_i| = |B_i|, and K_i doesn't intersect with previous K_i. Each minimal found l is stored as sigma(i) = l.\n\nsigma(i) is compressed into bit vector in such a way that we can get value l = sigma(i) in O(1) time.\n\nFinally, to get perfect hash of value x we do PerfectHash(x) = Hash[sigma(g(x))](x).\n\n\nFull code below. It generates N random numbers, then perfect hashes them and finally outputs amount of bits per number.\nTry it online!\n#include <cstdint>\n#include <bit>\n#include <vector>\n#include <random>\n#include <cstring>\n#include <stdexcept>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <unordered_map>\n#include <array>\n\n#define ASSERT_MSG(cond, msg) { if (!(cond)) throw std::runtime_error(\"Assertion (\" #cond \") failed at line \" + std::to_string(__LINE__) + \"! Msg: '\" + std::string(msg) + \"'.\"); }\n#define ASSERT(cond) ASSERT_MSG(cond, \"\")\n#define DASSERT_MSG(cond, msg) ASSERT_MSG(cond, msg)\n#define DASSERT(cond) DASSERT_MSG(cond, \"\")\n\nusing u8 = uint8_t;\nusing u32 = uint32_t;\nusing u64 = uint64_t;\n\ntemplate <typename T>\nbool IsPrime(T const & n) {\n if (n % 2 == 0)\n return false;\n for (size_t d = 3; d * d <= n; d += 2)\n if (n % d == 0)\n return false;\n return true;\n}\n\ntemplate <typename T>\nT NextPrime(T const & i) {\n if (i <= 2) return 2;\n for (T j = i | 1;; j += 2)\n if (IsPrime(j))\n return j;\n}\n\nclass BitVector {\n static size_t constexpr index_block = 1 << 9;\n \npublic:\n BitVector() {}\n BitVector(size_t size) : size_(size), bits_((size_ + 7) / 8) {}\n void Clear() {\n size_ = 0;\n bits_.clear();\n index_.clear();\n }\n size_t Size() const { return size_; }\n bool Get(size_t i) const {\n return (bits_[i / 8] >> (i % 8)) & u8(1);\n }\n void Set(size_t i, bool val = true) {\n if (val)\n bits_[i / 8] |= u8(1) << (i % 8);\n else\n bits_[i / 8] &= ~(u8(1) << (i % 8));\n }\n void Push(bool val) {\n ++size_;\n if (size_ - 1 >= bits_.size() * 8)\n bits_.resize((size_ + 7) / 8);\n Set(size_ - 1, val);\n }\n void Index() {\n index_.clear();\n for (size_t i = 0; i < size_; i += index_block) {\n size_t sum = 0;\n size_t const portion = std::min(index_block, size_ - i);\n for (size_t k = i; k < i + portion; k += 64)\n if (i + portion - k >= 64)\n sum += std::popcount(*(u64*)&bits_[k / 8]);\n else {\n u64 x = 0;\n std::memcpy(&x, &bits_[k / 8], bits_.size() - k / 8);\n sum += std::popcount(x);\n }\n index_.push_back(index_.empty() ? sum : (index_.back() + sum));\n }\n }\n size_t Select1(size_t idx) const {\n size_t const d = std::distance(index_.data(), std::upper_bound(index_.data(), index_.data() + index_.size(), idx));\n ASSERT_MSG(d < index_.size(), \"idx \" + std::to_string(idx));\n size_t const prev_sum = d == 0 ? 0 : index_[d - 1], hi = std::min<size_t>(size_, index_block * (d + 1));\n size_t csum = 0, i = 0;\n u64 word = 0;\n for (i = index_block * d; i < hi; i += 64) {\n size_t const portion = std::min<size_t>(hi - i, 64);\n size_t word_sum = 0;\n if (portion == 64)\n word = *(u64*)&bits_[i / 8];\n else {\n word = 0;\n std::memcpy(&word, &bits_[i / 8], bits_.size() - i / 8);\n }\n word_sum = std::popcount(word);\n if (prev_sum + csum + word_sum > idx)\n break;\n csum += word_sum;\n }\n size_t sum0 = 0;\n while (true) {\n size_t const i1 = std::countr_zero(word);\n ASSERT(i1 < 64);\n if (prev_sum + csum + sum0 >= idx) {\n ASSERT(prev_sum + csum + sum0 == idx);\n ASSERT(Get(i + i1));\n return i + i1;\n }\n word &= word - 1;\n ++sum0;\n }\n }\n std::string Dump() const {\n std::string r;\n for (size_t i = 0; i < size_; ++i)\n r.append(1, Get(i) ? '1' : '0');\n return r;\n }\n u64 Word(size_t i) const {\n return (*(u64*)&bits_[i / 8]) >> (i % 8);\n }\n \nprivate:\n size_t size_ = 0;\n std::vector<u8> bits_;\n std::vector<size_t> index_;\n};\n\nclass GammaBitVector {\n static size_t constexpr index_block = 1 << 7;\n \npublic:\n template <typename T>\n void GammaEncodeVec(std::vector<T> const & nums) {\n for (auto n: nums) {\n auto [x, b] = GammaEncode(std::max<size_t>(n, 1) - 1);\n //std::cout << n << \": \" << b << \" \" << x << std::endl;\n for (size_t i = 0; i < b; ++i) {\n bv_.Push(bool(x & 1));\n x >>= 1;\n }\n }\n //std::cout << \"GammaEncodedVec \" << bv_.Size() << std::endl;\n //std::cout << bv_.Dump() << std::endl << std::endl;\n }\n void Index() {\n size_t i = 0, cnt = 0;\n while (i < bv_.Size()) {\n auto const [n, ebits, dbits] = GammaDecode(bv_.Word(i));\n ++cnt;\n i += ebits;\n if (cnt < index_block && i < bv_.Size())\n continue;\n index_.push_back(i);\n cnt = 0;\n }\n }\n size_t Get(size_t i) const {\n size_t j = i / index_block * index_block, sum = i / index_block > 0 ? index_.at(i / index_block - 1) : 0;\n while (sum < bv_.Size()) {\n auto const [n, ebits, dbits] = GammaDecode(bv_.Word(sum));\n if (j >= i)\n return n + 1;\n ++j;\n sum += ebits;\n }\n ASSERT(false);\n }\n size_t Size() const { return bv_.Size(); }\n size_t GetBitOffset(size_t i) const {\n size_t j = i / index_block * index_block, sum = i / index_block > 0 ? index_.at(i / index_block - 1) : 0;\n while (sum < bv_.Size()) {\n auto const [n, ebits, dbits] = GammaDecode(bv_.Word(sum));\n if (j >= i)\n return sum;\n ++j;\n sum += ebits;\n }\n ASSERT(false);\n }\n \nprivate:\n static u64 Shl(u64 w, size_t cnt) {\n return cnt >= 64 ? u64(0) : (w << cnt);\n }\n static u64 Shr(u64 w, size_t cnt) {\n return cnt >= 64 ? u64(0) : (w >> cnt);\n }\n static u64 Mask(size_t n) {\n return n >= 64 ? ~u64(0) : (u64(1) << n) - 1;\n }\n static size_t NumBits(u64 n) {\n return 64 - std::countl_zero(n);\n }\n static std::tuple<u64, size_t> GammaEncode(u64 n) {\n ++n;\n DASSERT(n != 0);\n size_t const nbits = NumBits(n);\n static auto lo = []{\n std::array<u32, 32> r{};\n for (size_t i = 0; i < r.size(); ++i)\n r[i] = u32(1) << i;\n return r;\n }();\n size_t const rnbits = nbits - 1;\n DASSERT(rnbits < lo.size());\n return std::make_tuple((Shl(n & Mask(rnbits), nbits) | u64(lo[rnbits])), rnbits + nbits);\n }\n static std::tuple<u64, size_t, size_t> GammaDecode(u64 n) {\n static size_t constexpr c_tab_bits = 8;\n static auto tab = []{\n std::array<u8, (1 << c_tab_bits)> r{};\n for (size_t i = 0; i < r.size(); ++i) {\n size_t j = i, sr = 0;\n if (i == 0)\n sr = 0xFF;\n else\n while (!bool(j & 1)) {\n ++sr;\n j >>= 1;\n }\n r[i] = u8(sr);\n }\n return r;\n }();\n size_t cnt = tab[n & Mask(c_tab_bits)];\n if (cnt == 0xFF) {\n ASSERT(n != 0);\n cnt = 0;\n u64 m = n;\n while (!bool(m & 1)) {\n ++cnt;\n m >>= 1;\n }\n ASSERT(cnt <= 31);\n }\n return std::make_tuple(u64((((n >> (cnt + 1)) & Mask(cnt)) | (u64(1) << cnt)) - 1), size_t(2 * cnt + 1), size_t(cnt + 1));\n }\n \n BitVector bv_;\n std::vector<size_t> index_;\n};\n\nclass PerfectHash {\npublic:\n // https://en.wikipedia.org/wiki/Perfect_hash_function\n \n void Build(std::vector<u64> const & nums) {\n size_t const n = nums.size();\n m_ = 1.5 * n;\n n_ = n;\n primes_.clear();\n primes_.push_back({rng_(), NextPrime(n_)});\n primes_.push_back({rng_(), NextPrime(m_)});\n std::vector<std::vector<size_t>> Bs(n);\n for (size_t i = 0; i < n; ++i) {\n Bs[g(nums[i])].push_back(nums[i]);\n //std::cout << \"i \" << i << \": \" << nums[i] << \": \" << g(nums[i]) << \", \";\n }\n //std::cout << std::endl;\n std::vector<u64> K;\n BitVector Tb(m_);\n std::vector<u32> sigma_l(n);\n size_t max_bucket_size = 0;\n for (size_t i = 0; i < n; ++i) {\n auto const & B = Bs.at(i);\n max_bucket_size = std::max<size_t>(max_bucket_size, B.size());\n if (B.empty())\n continue;\n size_t l = 0;\n for (l = 1; l < 10'000; ++l) {\n bool exists = false;\n K.clear();\n for (size_t iB = 0; iB < B.size(); ++iB) {\n auto const j = B[iB];\n auto const h = HashFunc(l, j);\n if (Tb.Get(h)) {\n exists = true;\n break;\n }\n for (auto k: K)\n if (k == h) {\n exists = true;\n break;\n }\n if (exists)\n break;\n K.push_back(h);\n }\n if (!exists)\n break;\n }\n ASSERT(l < 10'000);\n sigma_l[i] = l;\n for (auto j: K)\n Tb.Set(j);\n }\n sigma_bv_.Clear();\n //std::cout << \"MaxBucket \" << max_bucket_size << std::endl;\n //std::cout << \"Sigma: \";\n for (size_t i = 0; i < sigma_l.size(); ++i) {\n auto const l = sigma_l[i];\n //std::cout << l << \", \";\n sigma_bv_.Push(1);\n for (size_t i = 0; i + 1 < l; ++i)\n sigma_bv_.Push(0);\n }\n //std::cout << std::endl;\n sigma_gbv_.GammaEncodeVec(sigma_l);\n sigma_gbv_.Index();\n //std::cout << \"Sigma from GBV: \";\n for (size_t i = 0; i < sigma_l.size(); ++i) {\n //std::cout << sigma_gbv_.Get(i) << \", \";\n ASSERT_MSG(std::max<size_t>(1, sigma_l[i]) == sigma_gbv_.Get(i), \"i \" + std::to_string(i) + \" sigma_l \" + std::to_string(std::max<size_t>(1, sigma_l[i])) + \" sigma_Get(i) \" + std::to_string(sigma_gbv_.Get(i)) + \" sigma_GetOff(i) \" + std::to_string(sigma_gbv_.GetBitOffset(i)) + \" sigma_GetOff(i - 1) \" + std::to_string(sigma_gbv_.GetBitOffset(i - 1)));\n }\n //std::cout << std::endl;\n sigma_bv_.Index();\n for (size_t i = 0; i < sigma_bv_.Size(); ++i) {\n //std::cout << (sigma_bv_.Get(i) ? \"1\" : \"0\");\n }\n //std::cout << std::endl;\n }\n size_t Hash(u64 const & x) {\n return HashFunc(Sigma(g(x)), x);\n }\n size_t NumBits() const {\n return sigma_gbv_.Size();\n }\n size_t HashFunc(size_t i, u64 const & x) {\n while (i >= primes_.size())\n primes_.push_back({rng_(), NextPrime(primes_.back().second + 1)});\n auto const [k, p] = primes_[i];\n auto v = (k * x) % p;\n size_t const mod = i == 0 ? n_ : m_;\n while (v >= mod)\n v -= mod;\n return v;\n }\n size_t g(u64 const & x) {\n return HashFunc(0, x);\n }\n size_t Sigma(size_t i) {\n size_t const i1 = sigma_gbv_.Get(i);\n //std::cout << \"Sigma: \" << i << \": \" << i1 << std::endl;\n return i1;\n \n /*\n size_t cnt = 0;\n for (size_t i = i1 + 1, size = sigma_bv_.Size(); i < size; ++i, ++cnt) {\n std::cout << i << \" (\" << std::boolalpha << sigma_bv_.Get(i) << \"), \";\n if (sigma_bv_.Get(i))\n break;\n }\n std::cout << std::endl << \"Val: \" << (cnt + 1) << std::endl;\n return cnt + 1;\n */\n }\n size_t N() const { return n_; }\n size_t M() const { return m_; }\n \nprivate:\n std::mt19937_64 rng_{123};\n size_t n_ = 0, m_ = 0;\n BitVector sigma_bv_;\n GammaBitVector sigma_gbv_;\n std::vector<std::pair<u64, u64>> primes_;\n};\n\nint main() {\n try {\n std::mt19937_64 rng{123};\n std::vector<u64> nums(1 << 17);\n for (size_t i = 0; i < nums.size(); ++i)\n nums[i] = rng();\n PerfectHash ph;\n ph.Build(nums);\n std::cout << \"Nums \" << nums.size() << std::endl;\n std::cout << \"PerfectHash Bits \" << ph.NumBits() << \", \" << std::setprecision(3)\n << (double(ph.NumBits()) / nums.size()) << \" bits/num\" << std::endl;\n std::unordered_map<u64, u64> hashes;\n for (size_t i = 0; i < nums.size(); ++i) {\n //std::cout << \"i \" << i << std::endl;\n auto const hash = ph.Hash(nums[i]);\n if (i < 16) {\n //std::cout << nums[i] << \": \" << hash << std::endl;\n }\n ASSERT(hash < ph.M());\n ASSERT_MSG(!hashes.count(hash),\n \"i \" + std::to_string(i) + \" nums[i] \" + std::to_string(nums[i]) +\n \" hash \" + std::to_string(hash) + \" g(x) \" + std::to_string(ph.g(nums[i])) +\n \" sigma \" + std::to_string(ph.Sigma(ph.g(nums[i]))) +\n \" hash_func \" + std::to_string(ph.HashFunc(ph.Sigma(ph.g(nums[i])), nums[i])) +\n \" prev_i \" + std::to_string(hashes.at(hash)) + \" nums[hashes.at(hash)] \" +\n std::to_string(nums[hashes.at(hash)]) + \" prev_g(x) \" +\n std::to_string(ph.g(nums[hashes.at(hash)])) + \" prev_sigma \" +\n std::to_string(ph.Sigma(ph.g(nums[hashes.at(hash)]))) + \" prev_hash_func \" +\n std::to_string(ph.HashFunc(ph.Sigma(ph.g(nums[hashes.at(hash)])), nums[hashes.at(hash)]))\n );\n hashes[hash] = i;\n }\n ASSERT(hashes.size() == nums.size());\n return 0;\n } catch (std::exception const & ex) {\n std::cout << \"Exception: \" << ex.what() << std::endl;\n return -1;\n }\n}\n\nConsole Output:\nNums 131072\nPerfectHash Bits 244430, 1.86 bits/num\n\n" ]
[ 1 ]
[]
[]
[ "c++", "hash" ]
stackoverflow_0074675043_c++_hash.txt
Q: Laravel cache a query the includes Auth::id() I have a Laravel application where all users credentials are stored in users table. And I have multiple user roles, for each role there is a table in DB (admins, customers, ...) each one has different data. I'm using Auth::user() multiple times in my application, and the query is executed only once on DB (as expected). Example: $user1 = Auth::user(); $user2 = Auth::user(); $user3 = Auth::user(); $user4 = Auth::user(); // The query is executed only once in DB. When I'm trying to access admin data using Admin::where('user_id', Auth::id())->first() multiple queries are executed. Example: $user1 = Admin::where('user_id', Auth::id())->first(); $user2 = Admin::where('user_id', Auth::id())->first(); $user3 = Admin::where('user_id', Auth::id())->first(); $user4 = Admin::where('user_id', Auth::id())->first(); // 4 queries are executed. I have tried to add a relationship to user model as follows: // App\Models\User class User extends Authenticatable { ... public function admin() { return $this->belongsTo(Admin::class, 'id', 'user_id'); } } When executing Auth::user()->admin() also 4 queries are executed. I'm facing this problem in the model. I have this example model, where I need the agent to add an attribute: // App\Models\Card ... public function getCurrencyAttribute() { $user = Auth::user() // This query is executed only once for all rows. $admin = Admin::where('user_id', Auth::id()); // This query is executed for each row (if I have 100 rows, it's executed 100 times). ... } ... Is there a way to cache the query as Auth::user() is cached? A: first of all, Auth::user() is not cached, it's just stored in memory, and whenever you say Model::where('condition')->first(), you are telling the application to execute a query, so it will be executed, also when you say Auth::user()->admin(), you are calling it as a method, so it will return a query builder, you should call it as a property Auth::user()->admin, like this try using load method, Auth::user()->load(['admin']), it should append admin object to the user object. good luck ✌
Laravel cache a query the includes Auth::id()
I have a Laravel application where all users credentials are stored in users table. And I have multiple user roles, for each role there is a table in DB (admins, customers, ...) each one has different data. I'm using Auth::user() multiple times in my application, and the query is executed only once on DB (as expected). Example: $user1 = Auth::user(); $user2 = Auth::user(); $user3 = Auth::user(); $user4 = Auth::user(); // The query is executed only once in DB. When I'm trying to access admin data using Admin::where('user_id', Auth::id())->first() multiple queries are executed. Example: $user1 = Admin::where('user_id', Auth::id())->first(); $user2 = Admin::where('user_id', Auth::id())->first(); $user3 = Admin::where('user_id', Auth::id())->first(); $user4 = Admin::where('user_id', Auth::id())->first(); // 4 queries are executed. I have tried to add a relationship to user model as follows: // App\Models\User class User extends Authenticatable { ... public function admin() { return $this->belongsTo(Admin::class, 'id', 'user_id'); } } When executing Auth::user()->admin() also 4 queries are executed. I'm facing this problem in the model. I have this example model, where I need the agent to add an attribute: // App\Models\Card ... public function getCurrencyAttribute() { $user = Auth::user() // This query is executed only once for all rows. $admin = Admin::where('user_id', Auth::id()); // This query is executed for each row (if I have 100 rows, it's executed 100 times). ... } ... Is there a way to cache the query as Auth::user() is cached?
[ "first of all, Auth::user() is not cached, it's just stored in memory,\nand whenever you say Model::where('condition')->first(), you are telling the application to execute a query, so it will be executed, also when you say Auth::user()->admin(), you are calling it as a method, so it will return a query builder, you should call it as a property Auth::user()->admin, like this\ntry using load method, Auth::user()->load(['admin']), it should append admin object to the user object.\ngood luck ✌\n" ]
[ 1 ]
[]
[]
[ "caching", "laravel", "php", "relationship" ]
stackoverflow_0074674358_caching_laravel_php_relationship.txt
Q: Get Country using ip address and output New Year Countdown according to that Here I am trying to retrieve the IP address of the user, and with the timezone that I got from the IP address, I want to check if the date is 1/01/2023 for that country and then if it is, I want to redirect the user to another subdomain which has a Happy New Year Page: <?php $ip = $_SERVER['REMOTE_ADDR']; $ipInfo = file_get_contents('http://ip-api.com/json/' . $ip); $ipInfo = json_decode($ipInfo); $timezone = $ipInfo->timezone; if (date('d') == '01' && date('m') == '01' && date('Y') == '2023') { header('Location: https://2023.blogsaffair.com/'); } if (date('d') == '1' && date('m') == '11') { header('Location: https://blogsaffair.com'); }*/ ?> My scripts.js code for countdown const secondsText = document.getElementById('seconds'); const minutesText = document.getElementById('minutes'); const hoursText = document.getElementById('hours'); const daysText = document.getElementById('days'); function countDown () { var deadlineDate = new Date("Jan 1, 2023 00:00:00").getTime(); var presentDate= new Date().getTime(); var timeLeft = deadlineDate - presentDate; var daysValue = Math.floor(timeLeft / (1000 * 60 * 60 * 24)); var hoursValue = Math.floor(timeLeft % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)); var minutesValue = Math.floor(timeLeft % (1000 * 60 * 60) / (1000 * 60)); var secondsValue = Math.floor(timeLeft % (1000 * 60) / (1000)); secondsText.textContent = secondsValue; minutesText.textContent = minutesValue; hoursText.textContent = hoursValue; daysText.textContent = daysValue; if(timeLeft < 0){ clearInterval(); } } setInterval(countDown, 1000); I am trying to achieve what timeanddate.com shows on this link https://www.timeanddate.com/countdown/newyear How can I display the countdown for that country using IP. I couldn't find this anywhere on the internet so please help if you can? Thanks! A: <?php $ip = $_SERVER['REMOTE_ADDR']; $ipInfo = file_get_contents('http://ip-api.com/json/' . $ip); $ipInfo = json_decode($ipInfo); $timezone = $ipInfo->timezone; // Get the current date and time in the timezone of the user's IP address $date = new DateTime('now', new DateTimeZone($timezone)); // Check if the date is 1/01/2023 in the timezone of the user's IP address if ($date->format('d') == '01' && $date->format('m') == '01' && $date->format('Y') == '2023') { header('Location: https://2023.blogsaffair.com/'); } // If not, check if it's 11/01 in the user's timezone if ($date->format('d') == '1' && $date->format('m') == '11') { header('Location: https://blogsaffair.com'); } ?> the date and time in the timezone of the user's IP address is retrieved using the DateTime class and the DateTimeZone class. Then, the date is checked to see if it is 1/01/2023 in that timezone. the code checks if it is 11/01 in the user's timezone and redirects the user accordingly. A: To display a countdown to New Year's Day 2023 for a user based on their time zone, you will need to do the following: Retrieve the user's IP address using $_SERVER['REMOTE_ADDR']. Use a service like http://ip-api.com to determine the user's time zone based on their IP address. You can do this by making an HTTP GET request to the following URL: http://ip-api.com/json/{IP_ADDRESS}, where {IP_ADDRESS} is the user's IP address. This will return a JSON object containing information about the user's location, including their time zone. Use the time zone information to create a new Date object representing New Year's Day 2023 in the user's time zone. You can do this by using the Date constructor and passing in a string in the format "Jan 1, 2023 00:00:00", followed by the getTime() method to get the timestamp for that date in the user's time zone. Calculate the time remaining until New Year's Day 2023 by subtracting the current timestamp from the timestamp for New Year's Day 2023 in the user's time zone. Divide the time remaining by the number of milliseconds in a day, hour, minute, and second to determine the number of days, hours, minutes, and seconds remaining until New Year's Day 2023. Use this information to update the text content of the appropriate HTML elements on your page to display the countdown. I would recommend checking the documentation for the Date constructor and the getTime() method to ensure that you're using them correctly. You should also make sure that your PHP and JavaScript code is properly formatted and free of syntax errors. It's worth noting that the approach you've described (i.e., redirecting the user to a different subdomain based on the current date and time) may not be the most user-friendly way of displaying a countdown. A better approach might be to use JavaScript to update the countdown on the same page, without requiring the user to navigate to a different URL. This would allow the user to see the countdown without having to refresh the page or navigate away from the content they're currently viewing. Here is an example of how you might implement a countdown to New Year's Day 2023 for a user based on their time zone using PHP and JavaScript: <?php // Get the user's IP address $ip = $_SERVER['REMOTE_ADDR']; // Use a service like http://ip-api.com to determine the user's time zone // based on their IP address $ipInfo = file_get_contents('http://ip-api.com/json/' . $ip); $ipInfo = json_decode($ipInfo); $timezone = $ipInfo->timezone; // Use the time zone information to create a new Date object representing // New Year's Day 2023 in the user's time zone $deadlineDate = new Date("Jan 1, 2023 00:00:00", $timezone); $deadlineTimestamp = $deadlineDate->getTime(); // Calculate the time remaining until New Year's Day 2023 $presentDate = new Date(); $presentTimestamp = $presentDate->getTime(); $timeLeft = $deadlineTimestamp - $presentTimestamp; // Divide the time remaining by the number of milliseconds in a day, hour, // minute, and second to determine the number of days, hours, minutes, and // seconds remaining until New Year's Day 2023 $days = floor($timeLeft / (1000 * 60 * 60 * 24)); $hours = floor(($timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); $minutes = floor(($timeLeft % (1000 * 60 * 60)) / (1000 * 60)); $seconds = floor(($timeLeft % (1000 * 60)) / 1000); // Use this information to update the text content of the appropriate HTML // elements on your page to display the countdown echo "<div id='countdown'>"; echo "<span id='days'>$days</span> days, "; echo "<span id='hours'>$hours</span> hours, "; echo "<span id='minutes'>$minutes</span> minutes, and "; echo "<span id='seconds'>$seconds</span> seconds"; echo "</div>"; // If the current date and time are New Year's Day 2023 in the user's time zone, // redirect the user to a different URL if ($presentTimestamp >= $deadlineTimestamp) { header('Location: https://2023.blogsaffair.com/'); } ?> This code uses PHP to retrieve the user's IP address, determine their time zone, and calculate the time remaining until New Year's Day 2023. It then uses this information to update the text content of the appropriate HTML elements on the page, which can be styled using CSS to display the countdown. You can then use JavaScript to update the countdown every second, using the setInterval method: <script> // Get references to the HTML elements that will display the countdown const days = document.getElementById('days'); const hours = document.getElementById('hours'); const minutes = document.getElementById('minutes'); const seconds = document.getElementById('seconds'); // Define a function that calculates the time remaining until New Year's Day 2023 // in the user's time zone and updates the text content of the
Get Country using ip address and output New Year Countdown according to that
Here I am trying to retrieve the IP address of the user, and with the timezone that I got from the IP address, I want to check if the date is 1/01/2023 for that country and then if it is, I want to redirect the user to another subdomain which has a Happy New Year Page: <?php $ip = $_SERVER['REMOTE_ADDR']; $ipInfo = file_get_contents('http://ip-api.com/json/' . $ip); $ipInfo = json_decode($ipInfo); $timezone = $ipInfo->timezone; if (date('d') == '01' && date('m') == '01' && date('Y') == '2023') { header('Location: https://2023.blogsaffair.com/'); } if (date('d') == '1' && date('m') == '11') { header('Location: https://blogsaffair.com'); }*/ ?> My scripts.js code for countdown const secondsText = document.getElementById('seconds'); const minutesText = document.getElementById('minutes'); const hoursText = document.getElementById('hours'); const daysText = document.getElementById('days'); function countDown () { var deadlineDate = new Date("Jan 1, 2023 00:00:00").getTime(); var presentDate= new Date().getTime(); var timeLeft = deadlineDate - presentDate; var daysValue = Math.floor(timeLeft / (1000 * 60 * 60 * 24)); var hoursValue = Math.floor(timeLeft % (1000 * 60 * 60 * 24) / (1000 * 60 * 60)); var minutesValue = Math.floor(timeLeft % (1000 * 60 * 60) / (1000 * 60)); var secondsValue = Math.floor(timeLeft % (1000 * 60) / (1000)); secondsText.textContent = secondsValue; minutesText.textContent = minutesValue; hoursText.textContent = hoursValue; daysText.textContent = daysValue; if(timeLeft < 0){ clearInterval(); } } setInterval(countDown, 1000); I am trying to achieve what timeanddate.com shows on this link https://www.timeanddate.com/countdown/newyear How can I display the countdown for that country using IP. I couldn't find this anywhere on the internet so please help if you can? Thanks!
[ "<?php\n$ip = $_SERVER['REMOTE_ADDR'];\n$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);\n$ipInfo = json_decode($ipInfo);\n$timezone = $ipInfo->timezone;\n\n// Get the current date and time in the timezone of the user's IP address\n$date = new DateTime('now', new DateTimeZone($timezone));\n\n// Check if the date is 1/01/2023 in the timezone of the user's IP address\nif ($date->format('d') == '01' && $date->format('m') == '01' && $date->format('Y') == '2023') {\n header('Location: https://2023.blogsaffair.com/');\n}\n\n// If not, check if it's 11/01 in the user's timezone\nif ($date->format('d') == '1' && $date->format('m') == '11') {\n header('Location: https://blogsaffair.com');\n}\n?>\n\nthe date and time in the timezone of the user's IP address is retrieved using the DateTime class and the DateTimeZone class. Then, the date is checked to see if it is 1/01/2023 in that timezone. the code checks if it is 11/01 in the user's timezone and redirects the user accordingly.\n", "To display a countdown to New Year's Day 2023 for a user based on their time zone, you will need to do the following:\n\nRetrieve the user's IP address using $_SERVER['REMOTE_ADDR'].\nUse a service like http://ip-api.com to determine the user's time zone based on their IP address. You can do this by making an HTTP GET request to the following URL: http://ip-api.com/json/{IP_ADDRESS}, where {IP_ADDRESS} is the user's IP address. This will return a JSON object containing information about the user's location, including their time zone.\nUse the time zone information to create a new Date object representing New Year's Day 2023 in the user's time zone. You can do this by using the Date constructor and passing in a string in the format \"Jan 1, 2023 00:00:00\", followed by the getTime() method to get the timestamp for that date in the user's time zone.\nCalculate the time remaining until New Year's Day 2023 by subtracting the current timestamp from the timestamp for New Year's Day 2023 in the user's time zone.\nDivide the time remaining by the number of milliseconds in a day, hour, minute, and second to determine the number of days, hours, minutes, and seconds remaining until New Year's Day 2023.\nUse this information to update the text content of the appropriate HTML elements on your page to display the countdown.\nI would recommend checking the documentation for the Date constructor and the getTime() method to ensure that you're using them correctly. You should also make sure that your PHP and JavaScript code is properly formatted and free of syntax errors.\n\nIt's worth noting that the approach you've described (i.e., redirecting the user to a different subdomain based on the current date and time) may not be the most user-friendly way of displaying a countdown. A better approach might be to use JavaScript to update the countdown on the same page, without requiring the user to navigate to a different URL. This would allow the user to see the countdown without having to refresh the page or navigate away from the content they're currently viewing.\nHere is an example of how you might implement a countdown to New Year's Day 2023 for a user based on their time zone using PHP and JavaScript:\n <?php\n// Get the user's IP address\n$ip = $_SERVER['REMOTE_ADDR'];\n\n// Use a service like http://ip-api.com to determine the user's time zone\n// based on their IP address\n$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);\n$ipInfo = json_decode($ipInfo);\n$timezone = $ipInfo->timezone;\n\n// Use the time zone information to create a new Date object representing\n// New Year's Day 2023 in the user's time zone\n$deadlineDate = new Date(\"Jan 1, 2023 00:00:00\", $timezone);\n$deadlineTimestamp = $deadlineDate->getTime();\n\n// Calculate the time remaining until New Year's Day 2023\n$presentDate = new Date();\n$presentTimestamp = $presentDate->getTime();\n$timeLeft = $deadlineTimestamp - $presentTimestamp;\n\n// Divide the time remaining by the number of milliseconds in a day, hour,\n// minute, and second to determine the number of days, hours, minutes, and\n// seconds remaining until New Year's Day 2023\n$days = floor($timeLeft / (1000 * 60 * 60 * 24));\n$hours = floor(($timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));\n$minutes = floor(($timeLeft % (1000 * 60 * 60)) / (1000 * 60));\n$seconds = floor(($timeLeft % (1000 * 60)) / 1000);\n\n// Use this information to update the text content of the appropriate HTML\n// elements on your page to display the countdown\necho \"<div id='countdown'>\";\necho \"<span id='days'>$days</span> days, \";\necho \"<span id='hours'>$hours</span> hours, \";\necho \"<span id='minutes'>$minutes</span> minutes, and \";\necho \"<span id='seconds'>$seconds</span> seconds\";\necho \"</div>\";\n\n// If the current date and time are New Year's Day 2023 in the user's time zone,\n// redirect the user to a different URL\nif ($presentTimestamp >= $deadlineTimestamp) {\n header('Location: https://2023.blogsaffair.com/');\n}\n?>\n\nThis code uses PHP to retrieve the user's IP address, determine their time zone, and calculate the time remaining until New Year's Day 2023. It then uses this information to update the text content of the appropriate HTML elements on the page, which can be styled using CSS to display the countdown.\nYou can then use JavaScript to update the countdown every second, using the setInterval method:\n <script>\n// Get references to the HTML elements that will display the countdown\nconst days = document.getElementById('days');\nconst hours = document.getElementById('hours');\nconst minutes = document.getElementById('minutes');\nconst seconds = document.getElementById('seconds');\n\n// Define a function that calculates the time remaining until New Year's Day 2023\n// in the user's time zone and updates the text content of the\n\n" ]
[ 0, 0 ]
[]
[]
[ "javascript", "php" ]
stackoverflow_0074675009_javascript_php.txt
Q: Why I get an error Java unclosed string literal? I have a java class, but when I'm trying to build a project I get an error error: unclosed string literal return load().query(""" ^ (the third quote) Can you please explain to me why it is an error? My code @Component(ThreatImplMethodRepository.NAME) public class ThreatImplMethodRepository extends DefaultRepository<ThreatImplMethod> { public static final String NAME = "gwf_ThreatImplMethodRepository"; @Override protected Class<ThreatImplMethod> entityClass() { return ThreatImplMethod.class; } public List<ThreatImplMethod> getBySourcesAndTargets(List<ImpactSource> sources, List<ImpactTarget> targets, FetchPlan fetchPlan) { return load().query(""" select distinct im from gwf_ThreatImplMethodLink imLink join imLink.implMethods im where imLink.source in :sources and imLink.targets in :targets """) .parameter("sources", sources) .parameter("targets", targets) .fetchPlan(fetchPlan) .list(); } } A: Well, Zac Anger and user16320675 already mentioned this in the comments: you are using the Text Blocks feature1, which is probably not supported by your compiler. The compiler parses "" as an empty string literal and then reads the third one as an opening delimiter of another string literal, which is, according to the compiler, unclosed. You are using the Text Blocks syntactical device, which is a feature since Java 15 (or since Java 13 as a preview feature). Your code is working fine, but you'll need to use a Java ≥ 15 compiler. 1 See Java Language Specification § 3.10.6.
Why I get an error Java unclosed string literal?
I have a java class, but when I'm trying to build a project I get an error error: unclosed string literal return load().query(""" ^ (the third quote) Can you please explain to me why it is an error? My code @Component(ThreatImplMethodRepository.NAME) public class ThreatImplMethodRepository extends DefaultRepository<ThreatImplMethod> { public static final String NAME = "gwf_ThreatImplMethodRepository"; @Override protected Class<ThreatImplMethod> entityClass() { return ThreatImplMethod.class; } public List<ThreatImplMethod> getBySourcesAndTargets(List<ImpactSource> sources, List<ImpactTarget> targets, FetchPlan fetchPlan) { return load().query(""" select distinct im from gwf_ThreatImplMethodLink imLink join imLink.implMethods im where imLink.source in :sources and imLink.targets in :targets """) .parameter("sources", sources) .parameter("targets", targets) .fetchPlan(fetchPlan) .list(); } }
[ "Well, Zac Anger and user16320675 already mentioned this in the comments: you are using the Text Blocks feature1, which is probably not supported by your compiler.\nThe compiler parses \"\" as an empty string literal and then reads the third one as an opening delimiter of another string literal, which is, according to the compiler, unclosed.\nYou are using the Text Blocks syntactical device, which is a feature since Java 15 (or since Java 13 as a preview feature).\nYour code is working fine, but you'll need to use a Java ≥ 15 compiler.\n\n1 See Java Language Specification § 3.10.6.\n" ]
[ 3 ]
[ "The error error: unclosed string literal return load().query(\"\"\" ^ (the third quote) is caused by a syntax error in the Java code. In Java, a string literal is defined using double quotes (\"). However, in the code you provided, the string literal in the query() method is defined using triple quotes (\"\"\"), which is not valid syntax in Java.\nTo fix this error, you can remove the extra quotes from the string literal in the query() method. Here is an example of how the code could be updated to fix the error:\n@Component(ThreatImplMethodRepository.NAME)\npublic class ThreatImplMethodRepository extends \nDefaultRepository<ThreatImplMethod> {\npublic static final String NAME = \"gwf_ThreatImplMethodRepository\";\n\n@Override\nprotected Class<ThreatImplMethod> entityClass() {\n return ThreatImplMethod.class;\n}\n\npublic List<ThreatImplMethod> getBySourcesAndTargets(List<ImpactSource> sources, List<ImpactTarget> targets, FetchPlan fetchPlan) {\n return load().query(\"\"\"\n select distinct im\n from gwf_ThreatImplMethodLink imLink\n join imLink.implMethods im\n where imLink.source in :sources\n and imLink.targets in :targets\n \"\"\")\n .parameter(\"sources\", sources)\n .parameter(\"targets\", targets)\n .fetchPlan(fetchPlan)\n .list();\n }\n}\n\nIn this updated code, the string literal in the query() method is defined using double quotes, which is the correct syntax in Java. This will fix the unclosed string literal error and allow the code to be compiled and built successfully.\n" ]
[ -3 ]
[ "java" ]
stackoverflow_0074673724_java.txt
Q: copy button for input field and add URL automatic when its coped i have input field and copy button, visitors can write their phone number inside the input (ex: +123456789) and then click copy button to copy the numbers. i want the visitor when click copy and past it anywhere it should be with URL example.com/123456789 so the URL add automatically and without (+) mark. i have this code but it does not work as i expect and i tried to modified still not work. <input type="text" id="phonenumber"> <div class="tooltip"> <button type="button" onclick="myFunction()" onmouseout="outFunc()"> <span class="tooltiptext" id="myTooltip">Copy to clipboard</span> Copy text </button> </div> <script> function myFunction() { var copyText = document.getElementById("phonenumber"); copyText.select(); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); var tooltip = document.getElementById("myTooltip"); tooltip.innerHTML = "Copied"; } function outFunc() { var tooltip = document.getElementById("myTooltip"); tooltip.innerHTML = "Copy to clipboard"; } </script> i've tried to do it like this var copyText = document.getElementById("example.com/","phonenumber"); But its not working, i add extra var but still not working A: Here's the working example of the code: Codepen link (click to view live example) Used string.substring(1) to remove the first character from the input text. Then simply added it to clipboard by appending example.com to it while writing it to clipboard
copy button for input field and add URL automatic when its coped
i have input field and copy button, visitors can write their phone number inside the input (ex: +123456789) and then click copy button to copy the numbers. i want the visitor when click copy and past it anywhere it should be with URL example.com/123456789 so the URL add automatically and without (+) mark. i have this code but it does not work as i expect and i tried to modified still not work. <input type="text" id="phonenumber"> <div class="tooltip"> <button type="button" onclick="myFunction()" onmouseout="outFunc()"> <span class="tooltiptext" id="myTooltip">Copy to clipboard</span> Copy text </button> </div> <script> function myFunction() { var copyText = document.getElementById("phonenumber"); copyText.select(); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); var tooltip = document.getElementById("myTooltip"); tooltip.innerHTML = "Copied"; } function outFunc() { var tooltip = document.getElementById("myTooltip"); tooltip.innerHTML = "Copy to clipboard"; } </script> i've tried to do it like this var copyText = document.getElementById("example.com/","phonenumber"); But its not working, i add extra var but still not working
[ "Here's the working example of the code:\nCodepen link (click to view live example)\nUsed string.substring(1) to remove the first character from the input text. Then simply added it to clipboard by appending example.com to it while writing it to clipboard\n" ]
[ 1 ]
[]
[]
[ "html", "javascript" ]
stackoverflow_0074674806_html_javascript.txt
Q: Box-box collision detection with PyOpenGL and Pygame at 3d I'm writing a player class that, among other things, has mesh attributes (I use the py3d library and the mesh class from it) and collider (a class that I need to implement myself). The collider is a simple cube and should have a method to determine whether it collided with another collider-cube or not. I have a class that allows you to rotate and move 3d objects, I inherit the collider from it. The main problem is precisely to write a collision check function I tried to use the methods built into Pygame to detect collisions, but it didn't work, because when the camera is removed, the collider remains the same size, and it can't be rotated. I'm bad at math, and all the guides I found were in C.game example A: One way to detect box-box collisions in 3D using PyOpenGL and Pygame is to use the Bullet physics engine. Bullet is a 3D physics engine that can be used to detect collisions, apply forces, and simulate the motion of rigid bodies. To use Bullet, you would need to implement the collider class as a Bullet body, and then use the Bullet functions to detect collisions between the collider objects. You can also use the Bullet functions to rotate and move the colliders, which will allow you to keep the same size collider regardless of the camera position. Here's a link to a tutorial on how to integrate bullet http://www.opengl-tutorial.org/miscellaneous/clicking-on-objects/picking-with-a-physics-library/
Box-box collision detection with PyOpenGL and Pygame at 3d
I'm writing a player class that, among other things, has mesh attributes (I use the py3d library and the mesh class from it) and collider (a class that I need to implement myself). The collider is a simple cube and should have a method to determine whether it collided with another collider-cube or not. I have a class that allows you to rotate and move 3d objects, I inherit the collider from it. The main problem is precisely to write a collision check function I tried to use the methods built into Pygame to detect collisions, but it didn't work, because when the camera is removed, the collider remains the same size, and it can't be rotated. I'm bad at math, and all the guides I found were in C.game example
[ "One way to detect box-box collisions in 3D using PyOpenGL and Pygame is to use the Bullet physics engine. Bullet is a 3D physics engine that can be used to detect collisions, apply forces, and simulate the motion of rigid bodies. To use Bullet, you would need to implement the collider class as a Bullet body, and then use the Bullet functions to detect collisions between the collider objects. You can also use the Bullet functions to rotate and move the colliders, which will allow you to keep the same size collider regardless of the camera position.\nHere's a link to a tutorial on how to integrate bullet\nhttp://www.opengl-tutorial.org/miscellaneous/clicking-on-objects/picking-with-a-physics-library/\n" ]
[ 0 ]
[]
[]
[ "collision_detection", "pyopengl", "python" ]
stackoverflow_0074674884_collision_detection_pyopengl_python.txt
Q: why psudeo after element's width is not relative to its parents width? I am trying to add a underline like symbol below the active link for that purpose i am used ::after element and set it's width to 100% to get its parent element's width but the psudo element is way much bigger when width is 100%; my html code is <header class="main-header"> <a class="category-name"> <span> Sneakers </span> </a> <nav class="main-nav"> <ul class="main-nav-list"> <li class="m"> <a class="main-nav-link" href="#how">Collections</a> </li> <li><a class="main-nav-link" href="#meals">Men</a></li> <li> <a class="main-nav-link" href="#testimonials">Women</a> </li> <li><a class="main-nav-link" href="#pricing">About</a></li> <li><a class="main-nav-link nav-cta" href="#cta">Contact</a></li> </ul> </nav> <ul class="my__ac-list"> <li class="nav--cart_icon" id="cartBtn"> <a href="#" class="cart-icon" ><img src="./images/icon-cart.svg" alt="cart icon" srcset="" /></a> <p class="cart--strip">3</p> </li> <li> <a href="#"> <img class="profile-thumbnail" src="./images/image-avatar.png" alt="image-avatar" srcset="" /> </a> </li> </ul> </header> my css code is bit lengthier i couldnot format correctly so i have created code containg my html and css codepen link = https://codepen.io/sinan-m/pen/abKQaxp i want to add a underline below the active navigation link like in design my design image https://github.com/front-end-mentor-works/e-com-product-page/blob/main/design/active-states-basket-filled.jpg A: .main-nav-list li.m for this selector you need to add position: relative. Beacause right now the after pseudoelement is not positioned relative to the li element. position: absolute; An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling. Because you didn't set position:relative on the li, he after element takes the width of the window browser. That's why when set to 100%, it's so wide. A: Result Solution .main-nav-list li.m { border-bottom: 5px solid tomato; } I edited the rule for the .main-nav-list li.m selector in the code pen. To get it more spaced out, then add some padding. e.g. .main-nav-list li.m { border-bottom: 5px solid tomato; padding-bottom: 1ex; } You also need to change .main-nav-list { … align-items: top; … } To keep the alignment good. And remove the yellow.
why psudeo after element's width is not relative to its parents width?
I am trying to add a underline like symbol below the active link for that purpose i am used ::after element and set it's width to 100% to get its parent element's width but the psudo element is way much bigger when width is 100%; my html code is <header class="main-header"> <a class="category-name"> <span> Sneakers </span> </a> <nav class="main-nav"> <ul class="main-nav-list"> <li class="m"> <a class="main-nav-link" href="#how">Collections</a> </li> <li><a class="main-nav-link" href="#meals">Men</a></li> <li> <a class="main-nav-link" href="#testimonials">Women</a> </li> <li><a class="main-nav-link" href="#pricing">About</a></li> <li><a class="main-nav-link nav-cta" href="#cta">Contact</a></li> </ul> </nav> <ul class="my__ac-list"> <li class="nav--cart_icon" id="cartBtn"> <a href="#" class="cart-icon" ><img src="./images/icon-cart.svg" alt="cart icon" srcset="" /></a> <p class="cart--strip">3</p> </li> <li> <a href="#"> <img class="profile-thumbnail" src="./images/image-avatar.png" alt="image-avatar" srcset="" /> </a> </li> </ul> </header> my css code is bit lengthier i couldnot format correctly so i have created code containg my html and css codepen link = https://codepen.io/sinan-m/pen/abKQaxp i want to add a underline below the active navigation link like in design my design image https://github.com/front-end-mentor-works/e-com-product-page/blob/main/design/active-states-basket-filled.jpg
[ ".main-nav-list li.m for this selector you need to add position: relative. Beacause right now the after pseudoelement is not positioned relative to the li element.\n\nposition: absolute;\n\nAn element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).\nHowever; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.\nBecause you didn't set position:relative on the li, he after element takes the width of the window browser. That's why when set to 100%, it's so wide.\n", "Result\n\nSolution\n.main-nav-list li.m {\n border-bottom: 5px solid tomato;\n}\n\nI edited the rule for the .main-nav-list li.m selector in the code pen.\nTo get it more spaced out, then add some padding. e.g.\n.main-nav-list li.m {\n border-bottom: 5px solid tomato;\n padding-bottom: 1ex;\n}\n\nYou also need to change\n.main-nav-list {\n …\n align-items: top;\n …\n}\n\nTo keep the alignment good. And remove the yellow.\n" ]
[ 1, 0 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074674908_css_html.txt
Q: I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found" I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found" here my code music.py import discord from discord.ext import commands import youtube_dl class music(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def join(self, ctx): if ctx.author.voice is None: await ctx.send("Et ole puhelussa vitun apina!") voice_channel = ctx.author.voice.channel if ctx.voice_client is None: await voice_channel.connect() else: await ctx.voice_client.move_to(voice_channel) @commands.command() async def disconnect(self,ctx): await ctx.voice_client.disconnect() @commands.command() async def play(self,ctx,url): ctx.voice_client.stop() FNPEG_OPTIONS = {'before_optopms': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay max 5', 'options': '-vn'} YDL_OPTIONS = {'format': "bestaudio"} vc = ctx.voice_client with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) url2 = info['formats'][0]['url'] source = await discord.FFmpegOpusAudio.from_probe(url2,**FNPEG_OPTIONS) vc.play(source) @commands.command() async def pause(self, ctx): await ctx.voice_client.pause() await ctx.send("MUSIIKKI PYSÄYTETTY") @commands.command() async def resume(self, ctx): await ctx.voice_client.resume() await ctx.send("MUSIIKKI JATKUU") def setup(client): client.add_cog(music(client)) run.py import discord from discord.ext import commands import music cogs = [music] client = commands.Bot(command_prefix="?", intents = discord.Intents.all()) for i in range(len(cogs)): cogs[i].setup(client) client.run("MTA0ODUzNjcyMjY3NTMzNTE3OA.G4CK62.BwAK0qKYvuOYU_tm7-cVNCctL4RnnSDtIHmfyc") i tried commads but they are not working it only says "discord.ext.commands.errors.CommandNotFound: Command "commad i was trying" is not found" A: As of discord.py 2, the add_cog method has become an async function, so you need to await it. And if you're using a cog from a other file, it is suggested to use load_extension to load it. For example: cogs/music.py class Music(commands.Cog): ... # as of discord.py 2, this function needs to be an async function async def setup(bot): await bot.add_cog(Music(bot)) main.py # subclass the bot to override the "setup_hook" method class MyBot(commands.Bot): async def setup_hook(self): cogs_to_load = ("cogs.music",) # tuple of paths to the cogs you wanted to load # use "load_extension" to load all the cogs for cog in cogs_to_load: await self.load_extension(cog) bot = MyBot() ... Here is an example of extensions, and here is an example of cogs.
I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found"
I'm creating discord bot that plays audio but i got this eror "discord.ext.commands.errors.CommandNotFound: Command "join" is not found" here my code music.py import discord from discord.ext import commands import youtube_dl class music(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def join(self, ctx): if ctx.author.voice is None: await ctx.send("Et ole puhelussa vitun apina!") voice_channel = ctx.author.voice.channel if ctx.voice_client is None: await voice_channel.connect() else: await ctx.voice_client.move_to(voice_channel) @commands.command() async def disconnect(self,ctx): await ctx.voice_client.disconnect() @commands.command() async def play(self,ctx,url): ctx.voice_client.stop() FNPEG_OPTIONS = {'before_optopms': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay max 5', 'options': '-vn'} YDL_OPTIONS = {'format': "bestaudio"} vc = ctx.voice_client with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) url2 = info['formats'][0]['url'] source = await discord.FFmpegOpusAudio.from_probe(url2,**FNPEG_OPTIONS) vc.play(source) @commands.command() async def pause(self, ctx): await ctx.voice_client.pause() await ctx.send("MUSIIKKI PYSÄYTETTY") @commands.command() async def resume(self, ctx): await ctx.voice_client.resume() await ctx.send("MUSIIKKI JATKUU") def setup(client): client.add_cog(music(client)) run.py import discord from discord.ext import commands import music cogs = [music] client = commands.Bot(command_prefix="?", intents = discord.Intents.all()) for i in range(len(cogs)): cogs[i].setup(client) client.run("MTA0ODUzNjcyMjY3NTMzNTE3OA.G4CK62.BwAK0qKYvuOYU_tm7-cVNCctL4RnnSDtIHmfyc") i tried commads but they are not working it only says "discord.ext.commands.errors.CommandNotFound: Command "commad i was trying" is not found"
[ "As of discord.py 2, the add_cog method has become an async function, so you need to await it. And if you're using a cog from a other file, it is suggested to use load_extension to load it. For example:\ncogs/music.py\nclass Music(commands.Cog):\n ...\n\n# as of discord.py 2, this function needs to be an async function\nasync def setup(bot): \n await bot.add_cog(Music(bot))\n\nmain.py\n# subclass the bot to override the \"setup_hook\" method\nclass MyBot(commands.Bot):\n async def setup_hook(self):\n cogs_to_load = (\"cogs.music\",) # tuple of paths to the cogs you wanted to load\n\n # use \"load_extension\" to load all the cogs\n for cog in cogs_to_load:\n await self.load_extension(cog)\n\nbot = MyBot()\n\n...\n\nHere is an example of extensions, and here is an example of cogs.\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074674862_discord_discord.py_python.txt
Q: Syntax error or access violation: 1103 Incorrect table name I am trying to migrate the table but it throws an error saying the table name is not valid, Idk why, I check my database there is not even any similar name table, I follow the tutorial and this is working for video guy and not for me. Is there any way to fix it? I'm using laravel version 9 <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('slug'); $table->longText('description'); $table->tinyInteger('status')->default('0'); $table->tinyInteger('popular')->default('0'); $table->string('.meta_title'); $table->string('.meta_description'); $table->string('.meta_keyword'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('categories'); } }; Error php artisan migrate INFO Running migrations. 2022_12_04_110615_create_categories_table ............................................................................................... 5ms FAIL Illuminate\Database\QueryException SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name '' (SQL: create table `categories` (`id` bigint unsigned not null auto_increment primary key, `name` varchar(191) not null, `slug` varchar(191) not null, `description` longtext not null, `status` tinyint not null default '0', `popular` tinyint not null default '0', ``.`meta_title` varchar(191) not null, ``.`meta_description` varchar(191) not null, ``.`meta_keyword` varchar(191) not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci') A: because there is a dot before these columns $table->string('.meta_title'); $table->string('.meta_description'); $table->string('.meta_keyword'); the compiler will expect the table name before the dot, when there is nothing before the dot it will throw this exception
Syntax error or access violation: 1103 Incorrect table name
I am trying to migrate the table but it throws an error saying the table name is not valid, Idk why, I check my database there is not even any similar name table, I follow the tutorial and this is working for video guy and not for me. Is there any way to fix it? I'm using laravel version 9 <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('slug'); $table->longText('description'); $table->tinyInteger('status')->default('0'); $table->tinyInteger('popular')->default('0'); $table->string('.meta_title'); $table->string('.meta_description'); $table->string('.meta_keyword'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('categories'); } }; Error php artisan migrate INFO Running migrations. 2022_12_04_110615_create_categories_table ............................................................................................... 5ms FAIL Illuminate\Database\QueryException SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name '' (SQL: create table `categories` (`id` bigint unsigned not null auto_increment primary key, `name` varchar(191) not null, `slug` varchar(191) not null, `description` longtext not null, `status` tinyint not null default '0', `popular` tinyint not null default '0', ``.`meta_title` varchar(191) not null, ``.`meta_description` varchar(191) not null, ``.`meta_keyword` varchar(191) not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate 'utf8mb4_unicode_ci')
[ "because there is a dot before these columns\n$table->string('.meta_title');\n$table->string('.meta_description');\n$table->string('.meta_keyword');\n\nthe compiler will expect the table name before the dot, when there is nothing before the dot it will throw this exception\n" ]
[ 0 ]
[]
[]
[ "database", "laravel", "php", "sql_server" ]
stackoverflow_0074675034_database_laravel_php_sql_server.txt
Q: How can I test a react component depending on an external legacy JS library I have in a component this piece of code TagCanvas is defined in the _app.tsx file within a legacy JS script. I need to do like that because if I include it in the component using it doesn't work when the component is rendered again. I want to test this component, so I have started rendering the component like this: import {render, screen} from '@testing-library/react'; import {MusasCloud} from '../../../components/MusasCloud.tsx'; const TagCanvas = jest.fn(); describe('MusasCloud component', () => { test('Should render the MusasCloud component', () => { render(<MusasCloud musas={[]} />); screen.debug(); }); }); I get the html rendered as I expect but I am getting the Canvas error which I would like to avoid. As you can see I have tried to mock the TagCanvas function using jest.fn() but this is not ding the job I'd expect. Question: How can I avoid this exception when running the test? A: Try to add the mock to your global in your setupTest.js file: global.TagCanvas = { Start: () => "this is the mocked implementation" } A: Thanks to Marek response I have it now working. It also worked if I do this global definition inside the beforeAll process. I haven't jest configured to read the setupTest.js file. Since I am working in next in this project here is how I added it: //jest.config.js const nextJest = require('next/jest'); const createJestConfig = nextJest({ dir: './', }); // Add any custom config to be passed to Jest const customJestConfig = { moduleDirectories: ['node_modules', '<rootDir>/'], testEnvironment: 'jest-environment-jsdom', // Define setupTest file here setupFiles: ['<rootDir>/setupTest.js'], }; module.exports = createJestConfig(customJestConfig);
How can I test a react component depending on an external legacy JS library
I have in a component this piece of code TagCanvas is defined in the _app.tsx file within a legacy JS script. I need to do like that because if I include it in the component using it doesn't work when the component is rendered again. I want to test this component, so I have started rendering the component like this: import {render, screen} from '@testing-library/react'; import {MusasCloud} from '../../../components/MusasCloud.tsx'; const TagCanvas = jest.fn(); describe('MusasCloud component', () => { test('Should render the MusasCloud component', () => { render(<MusasCloud musas={[]} />); screen.debug(); }); }); I get the html rendered as I expect but I am getting the Canvas error which I would like to avoid. As you can see I have tried to mock the TagCanvas function using jest.fn() but this is not ding the job I'd expect. Question: How can I avoid this exception when running the test?
[ "Try to add the mock to your global in your setupTest.js file:\nglobal.TagCanvas = {\n Start: () => \"this is the mocked implementation\"\n}\n\n", "Thanks to Marek response I have it now working.\nIt also worked if I do this global definition inside the beforeAll process.\n\nI haven't jest configured to read the setupTest.js file. Since I am working in next in this project here is how I added it:\n//jest.config.js\nconst nextJest = require('next/jest');\n\nconst createJestConfig = nextJest({\n dir: './',\n});\n\n// Add any custom config to be passed to Jest\nconst customJestConfig = {\n moduleDirectories: ['node_modules', '<rootDir>/'],\n testEnvironment: 'jest-environment-jsdom',\n // Define setupTest file here\n setupFiles: ['<rootDir>/setupTest.js'],\n};\n\nmodule.exports = createJestConfig(customJestConfig);\n\n" ]
[ 1, 0 ]
[]
[]
[ "jestjs", "mocking", "react_testing_library", "reactjs" ]
stackoverflow_0074666329_jestjs_mocking_react_testing_library_reactjs.txt
Q: Can't get html element using js file in SPFX I am trying to build dynamic content from a SharePoint list using SPFX. I'd like to use jQuery to build an accordion view of the data. The issue is that I can't even seem to get the element once the page is rendered. In my code I am requiring a file called ota.js with the following code: console.log('Start'); function otaExpand(){ console.log('otaExpand Function Called'); let spListContainer = document.getElementById('spListContainer'); console.log(spListContainer); } window.addEventListener("load", otaExpand()); In my ts file this is my render method: public render(): void { this.domElement.innerHTML = ` <div> <div id="spListContainer">TEST</div> </div> `; //this._renderListAsync(); //($('.accordion', this.domElement) as any).accordion(); } When I review the console, I get my messages, but the element itself comes back as null. console.log I am using SharePoint 2019 on premise with the following configuration. +-- @microsoft/[email protected] +-- [email protected] `-- [email protected] node --version v8.17.0 I should also mention I am using TypeScript with no JavaScript framework. Does anyone know why I can't access this element from my js file? Thanks! My overall goal is to call list data and apply an accordion style to it (https://jqueryui.com/accordion), but I can't even get passed capturing the element to change it. I've tried calling my code from a js file as well as trying to put the code directly in the html. Neither worked. A: Your code from the "ota.js" file is probably called before your HTML is initialized (i.e. before the "render()" function is executed). To make sure this is the case, you could add log to the "render()" function to see when it's called. In other words, "window.load" event happens long before "render()" function is called. This is how web parts are loaded - dynamically after full load of the page. Or "window.load" does not happen at all - web parts may be loaded by the user when using the page designer, i.e. without page reload. To fix the issue, you should get the element after it's created, i.e. after the "render()" function creates the element you are trying to get.
Can't get html element using js file in SPFX
I am trying to build dynamic content from a SharePoint list using SPFX. I'd like to use jQuery to build an accordion view of the data. The issue is that I can't even seem to get the element once the page is rendered. In my code I am requiring a file called ota.js with the following code: console.log('Start'); function otaExpand(){ console.log('otaExpand Function Called'); let spListContainer = document.getElementById('spListContainer'); console.log(spListContainer); } window.addEventListener("load", otaExpand()); In my ts file this is my render method: public render(): void { this.domElement.innerHTML = ` <div> <div id="spListContainer">TEST</div> </div> `; //this._renderListAsync(); //($('.accordion', this.domElement) as any).accordion(); } When I review the console, I get my messages, but the element itself comes back as null. console.log I am using SharePoint 2019 on premise with the following configuration. +-- @microsoft/[email protected] +-- [email protected] `-- [email protected] node --version v8.17.0 I should also mention I am using TypeScript with no JavaScript framework. Does anyone know why I can't access this element from my js file? Thanks! My overall goal is to call list data and apply an accordion style to it (https://jqueryui.com/accordion), but I can't even get passed capturing the element to change it. I've tried calling my code from a js file as well as trying to put the code directly in the html. Neither worked.
[ "Your code from the \"ota.js\" file is probably called before your HTML is initialized (i.e. before the \"render()\" function is executed). To make sure this is the case, you could add log to the \"render()\" function to see when it's called.\nIn other words, \"window.load\" event happens long before \"render()\" function is called. This is how web parts are loaded - dynamically after full load of the page. Or \"window.load\" does not happen at all - web parts may be loaded by the user when using the page designer, i.e. without page reload.\nTo fix the issue, you should get the element after it's created, i.e. after the \"render()\" function creates the element you are trying to get.\n" ]
[ 0 ]
[]
[]
[ "sharepoint", "spfx" ]
stackoverflow_0074658103_sharepoint_spfx.txt
Q: Is there any way to add the header and trailer values in row in SQL/talend Required to append the header and trailer record to row values Select name from tableA Current output: Prsad Lokesh Chandra Ravi Rajendra Expected output like : cas Prasad Lokesh Chandra Ravi Rajendra cas A: You can use the UNION operator in SQL Server to combine the header and trailer values with the existing rows in your table. Here is an example of how you could do this: SELECT 'cas' AS header UNION ALL SELECT * FROM your_table UNION ALL SELECT 'cas' AS trailer This query will select the string cas as the header value, and then combine it with the rows in your table using the UNION ALL operator. Finally, it will select the string cas again as the trailer value and combine it with the other rows using UNION ALL again. This will result in a new table with the header and trailer values appended to the existing rows in your table. The final table will look like this: header ------ cas Prasad Lokesh Chandra Ravi Rajendra cas You can then use this table in your application as needed. In Talend, you can use the tUnion component to combine the header and trailer values with the rows in your table. Here is an example of how you could do this: Create a new Talend job and drag a tFileInputDelimited component onto the design workspace. Configure the component to read the input data from your table. Drag a tMap component onto the design Add more examples: To preserve the original order of the rows in your table when combining the header and trailer values, you can use the UNION operator with the ORDER BY clause in your SQL query. Here is an example of how you could do this: SELECT 'cas' AS header UNION SELECT * FROM your_table UNION SELECT 'cas' AS trailer ORDER BY (SELECT NULL) This query will select the string cas as the header value and then combine it with the rows in your table using the UNION operator. The UNION operator, unlike UNION ALL, eliminates duplicate rows from the results. However, it does not preserve the original order of the rows in the combined table. To preserve the original order of the rows, we can use the ORDER BY clause with the SELECT NULL subquery. This will ensure that the resulting table is ordered by the NULL value, which will preserve the original order of the rows. Finally, the query will select the string cas again as the trailer value and combine it with the other rows using UNION again. The ORDER BY clause will then be applied to the resulting table to preserve the original order of the rows. This will result in a new table with the header and trailer values appended to the existing rows in your table, and the original order of the rows will be preserved. The final table will look like this: header ------ cas Prasad Lokesh Chandra Ravi Rajendra cas You can then use this table in your application as needed.
Is there any way to add the header and trailer values in row in SQL/talend
Required to append the header and trailer record to row values Select name from tableA Current output: Prsad Lokesh Chandra Ravi Rajendra Expected output like : cas Prasad Lokesh Chandra Ravi Rajendra cas
[ "You can use the UNION operator in SQL Server to combine the header and trailer values with the existing rows in your table. Here is an example of how you could do this:\nSELECT 'cas' AS header\nUNION ALL\nSELECT * FROM your_table\nUNION ALL\nSELECT 'cas' AS trailer\n\nThis query will select the string cas as the header value, and then combine it with the rows in your table using the UNION ALL operator. Finally, it will select the string cas again as the trailer value and combine it with the other rows using UNION ALL again.\nThis will result in a new table with the header and trailer values appended to the existing rows in your table. The final table will look like this:\nheader\n------\ncas\nPrasad\nLokesh\nChandra\nRavi\nRajendra\ncas\n\nYou can then use this table in your application as needed.\nIn Talend, you can use the tUnion component to combine the header and trailer values with the rows in your table. Here is an example of how you could do this:\nCreate a new Talend job and drag a tFileInputDelimited component onto the design workspace. Configure the component to read the input data from your table.\nDrag a tMap component onto the design\nAdd more examples:\nTo preserve the original order of the rows in your table when combining the header and trailer values, you can use the UNION operator with the ORDER BY clause in your SQL query. Here is an example of how you could do this:\nSELECT 'cas' AS header\nUNION\nSELECT * FROM your_table\nUNION\nSELECT 'cas' AS trailer\nORDER BY (SELECT NULL)\n\nThis query will select the string cas as the header value and then combine it with the rows in your table using the UNION operator. The UNION operator, unlike UNION ALL, eliminates duplicate rows from the results. However, it does not preserve the original order of the rows in the combined table.\nTo preserve the original order of the rows, we can use the ORDER BY clause with the SELECT NULL subquery. This will ensure that the resulting table is ordered by the NULL value, which will preserve the original order of the rows.\nFinally, the query will select the string cas again as the trailer value and combine it with the other rows using UNION again. The ORDER BY clause will then be applied to the resulting table to preserve the original order of the rows.\nThis will result in a new table with the header and trailer values appended to the existing rows in your table, and the original order of the rows will be preserved. The final table will look like this:\nheader\n------\ncas\nPrasad\nLokesh\nChandra\nRavi\nRajendra\ncas\n\nYou can then use this table in your application as needed.\n" ]
[ 0 ]
[]
[]
[ "etl", "sql", "sql_server", "talend" ]
stackoverflow_0074674999_etl_sql_sql_server_talend.txt
Q: How to find the closest point on a polyhedron (Wedge) How could I get the closest point inside a polyhedron to a point in 3d space using 4 vertices on the wedge (p0,p1,p2,p3) I have a set of points labelled here: 3d representation And a random point in 3d space (q) I've managed to get rectangular prisms to work but I'm not sure about this. Any help is appreciated! A: One way to find the closest point on a polyhedron (Wedge) is to use a convex hull algorithm. This algorithm will take the four vertices of the Wedge (p0,p1,p2,p3) as input and will output the closest point of the Wedge to a given point in 3D space. The convex hull algorithm is available in many libraries, such as CGAL and OpenMesh, and can be implemented in C#. Once you have the closest point, you can then use a distance metric to determine the distance between the two points.
How to find the closest point on a polyhedron (Wedge)
How could I get the closest point inside a polyhedron to a point in 3d space using 4 vertices on the wedge (p0,p1,p2,p3) I have a set of points labelled here: 3d representation And a random point in 3d space (q) I've managed to get rectangular prisms to work but I'm not sure about this. Any help is appreciated!
[ "One way to find the closest point on a polyhedron (Wedge) is to use a convex hull algorithm. This algorithm will take the four vertices of the Wedge (p0,p1,p2,p3) as input and will output the closest point of the Wedge to a given point in 3D space. The convex hull algorithm is available in many libraries, such as CGAL and OpenMesh, and can be implemented in C#. Once you have the closest point, you can then use a distance metric to determine the distance between the two points.\n" ]
[ 0 ]
[]
[]
[ "algorithm", "c#", "geometry" ]
stackoverflow_0074669089_algorithm_c#_geometry.txt
Q: Load specific DIV with a react component without reloading the whole page I have a menu where every menu item is a button and I want to load a specific reactjs component into a specific div without reloading the whole page. This is the current code, clearly is bad but I don't know where to start fixing it... ... <Button onClick={this.loadTarget}> {menuItem.name} </Button> ... loadTarget(event) { document.getElementById("datapanel").innerHTML="abc<TranslationsList />"; } When I click a menu Item I want to load my div with the value "abc<TranslationsList />". "abc" is displayed but the custom component "TranslationsList" is not and I guess this is normal as the TranslationsList tag is not a HTML tag. But how could I load my component? I could use links instead of buttons but in this case the question is how could I update the div content with a specific link? A: Answered by OpenAI ChatGPT: To load a React component into a specific div without reloading the whole page, you can use React's render() method. This method allows you to render a React component to a specific DOM element. Here's an example of how you can use render() to accomplish what you're trying to do: import React from 'react'; import { render } from 'react-dom'; import TranslationsList from './TranslationsList'; // This is the component that will be rendered in the "datapanel" div const MyComponent = () => ( <div> abc<TranslationsList /> </div> ); // This function will be called when the button is clicked const loadTarget = () => { render(<MyComponent />, document.getElementById('datapanel')); }; ... <Button onClick={loadTarget}> {menuItem.name} </Button> In this example, when the button is clicked, the loadTarget() function will be called, which uses React's render() method to render the MyComponent component inside the div with the ID datapanel. This will replace the existing content of the div with the content of the MyComponent component, which in this case is the string "abc" and the TranslationsList component. Added by me, Latest react-dom render method is slightly different from the above code example provided by the ChatGPT, You can change loadTarget slightly if you are using latest react v18 const loadTarget = () => { const root = ReactDOM.createRoot( document.getElementById('datapanel'); ); root.render(<MyComponent />); };
Load specific DIV with a react component without reloading the whole page
I have a menu where every menu item is a button and I want to load a specific reactjs component into a specific div without reloading the whole page. This is the current code, clearly is bad but I don't know where to start fixing it... ... <Button onClick={this.loadTarget}> {menuItem.name} </Button> ... loadTarget(event) { document.getElementById("datapanel").innerHTML="abc<TranslationsList />"; } When I click a menu Item I want to load my div with the value "abc<TranslationsList />". "abc" is displayed but the custom component "TranslationsList" is not and I guess this is normal as the TranslationsList tag is not a HTML tag. But how could I load my component? I could use links instead of buttons but in this case the question is how could I update the div content with a specific link?
[ "Answered by OpenAI ChatGPT:\nTo load a React component into a specific div without reloading the whole page, you can use React's render() method. This method allows you to render a React component to a specific DOM element.\nHere's an example of how you can use render() to accomplish what you're trying to do:\nimport React from 'react';\nimport { render } from 'react-dom';\nimport TranslationsList from './TranslationsList';\n\n// This is the component that will be rendered in the \"datapanel\" div\nconst MyComponent = () => (\n <div>\n abc<TranslationsList />\n </div>\n);\n\n// This function will be called when the button is clicked\nconst loadTarget = () => {\n render(<MyComponent />, document.getElementById('datapanel'));\n};\n\n...\n\n<Button onClick={loadTarget}>\n {menuItem.name}\n</Button>\n\nIn this example, when the button is clicked, the loadTarget() function will be called, which uses React's render() method to render the MyComponent component inside the div with the ID datapanel. This will replace the existing content of the div with the content of the MyComponent component, which in this case is the string \"abc\" and the TranslationsList component.\n\nAdded by me,\nLatest react-dom render method is slightly different from the above code example provided by the ChatGPT,\nYou can change loadTarget slightly if you are using latest react v18\n\nconst loadTarget = () => {\n const root = ReactDOM.createRoot(\n document.getElementById('datapanel');\n );\n root.render(<MyComponent />);\n};\n\n" ]
[ 1 ]
[]
[]
[ "node.js", "reactjs" ]
stackoverflow_0074654088_node.js_reactjs.txt
Q: Sum an array in an array of objects I have an array of objects with some car data inside : const cars = [ { "id": 1, "car_make": "Lincoln", "car_model": "Navigator", "car_year": 2009, "data": { "rating": 4.9, "engines": [3, 4, 5, 6] } }, { "id": 2, "car_make": "Mazda", "car_model": "Miata MX-5", "car_year": 2001, "data": { "rating": 4.1, "engines": [1, 2] } },] Next I need to sum all the engines numbers inside the data object in car: So I made the next function but everytime I try to console the array it remains unchanged. cars.forEach(car => { car.data.engines.reduce((a,b) => a+b,0) }) console.log(cars); A: You need to assign the reduce value to engines again so change car.data.engines.reduce((a,b) => a+b,0) to car.data.engines = car.data.engines.reduce((a,b) => a+b,0) const cars = [ { "id": 1, "car_make": "Lincoln", "car_model": "Navigator", "car_year": 2009, "data": { "rating": 4.9, "engines": [3, 4, 5, 6] } }, { "id": 2, "car_make": "Mazda", "car_model": "Miata MX-5", "car_year": 2001, "data": { "rating": 4.1, "engines": [1, 2] } }] cars.forEach(car => { car.data.engines = car.data.engines.reduce((a,b) => a+b,0) }) console.log(cars); A: Basically the answer to the question should have been an map and create a new array from that old with the data changed. const newCars = data.map(car => ({ id: car.id, brand : car.car_make, engineSum : car.data.engines.reduce((a,b) => a+b,0), })).sort((a,b) => a.engineSum - b.engineSum); console.log(newCars);
Sum an array in an array of objects
I have an array of objects with some car data inside : const cars = [ { "id": 1, "car_make": "Lincoln", "car_model": "Navigator", "car_year": 2009, "data": { "rating": 4.9, "engines": [3, 4, 5, 6] } }, { "id": 2, "car_make": "Mazda", "car_model": "Miata MX-5", "car_year": 2001, "data": { "rating": 4.1, "engines": [1, 2] } },] Next I need to sum all the engines numbers inside the data object in car: So I made the next function but everytime I try to console the array it remains unchanged. cars.forEach(car => { car.data.engines.reduce((a,b) => a+b,0) }) console.log(cars);
[ "You need to assign the reduce value to engines again\nso change\ncar.data.engines.reduce((a,b) => a+b,0)\n\nto\ncar.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n\n\n\nconst cars = [\n{\n\"id\": 1,\n\"car_make\": \"Lincoln\",\n\"car_model\": \"Navigator\",\n\"car_year\": 2009,\n\"data\": {\n \"rating\": 4.9,\n \"engines\": [3, 4, 5, 6]\n}\n},\n{\n\"id\": 2,\n\"car_make\": \"Mazda\",\n\"car_model\": \"Miata MX-5\",\n\"car_year\": 2001,\n\"data\": {\n \"rating\": 4.1,\n \"engines\": [1, 2]\n}\n}]\n\ncars.forEach(car => {\n car.data.engines = car.data.engines.reduce((a,b) => a+b,0)\n})\n\nconsole.log(cars);\n\n\n\n", "Basically the answer to the question should have been an map and create a new array from that old with the data changed.\nconst newCars = data.map(car => ({\nid: car.id,\nbrand : car.car_make,\nengineSum : car.data.engines.reduce((a,b) => a+b,0),\n})).sort((a,b) => a.engineSum - b.engineSum);\n\nconsole.log(newCars);\n\n" ]
[ 2, 0 ]
[]
[]
[ "arrays", "javascript", "object", "reduce", "sum" ]
stackoverflow_0074675002_arrays_javascript_object_reduce_sum.txt
Q: How to recreate manually deleted resources from the CDK/CloudFormation I have two CDK/Cfn stacks which instantiate application load balancers with SSL certificates. I'm using DNS validation which the CDK manages by creating a Lambda function which requests and validates the certificates. Unfortunately, those Lambda functions were manually deleted and now when I try to update my CDK resources, CloudFormation attempts to replace these Lambdas but fails because they no longer exist. I wish that CloudFormation would behave like Terraform and just say "oh that thing I need to replace isn't there, nbd I needed to replace it anyway, so let's carry on" but it does not. Not sure how to get out of this jam. Any help is appreciated. A: You have to import them back to CloudFormation. In TF it is same, and you also import resources into TF. A: The easiest fix to this drift is redeploying your CDK app with the deleted resource temporarily removed (e.g. commented out). CloudFormation will "delete" the already deleted resource, bringing the template back into sync with the deployed configuration. Then add back the resource to your app and deploy again. Problem solved. There's a complication in your case. The missing Lambda function is being constructed indirectly by a higher-level CDK construct. Removing the L2/L3 parent will destroy more resources than just the Lambda. If you want to avoid this collateral damage, you can use escape hatch syntax and the node.tryRemoveChild method to surgically remove the missing Lambda only.
How to recreate manually deleted resources from the CDK/CloudFormation
I have two CDK/Cfn stacks which instantiate application load balancers with SSL certificates. I'm using DNS validation which the CDK manages by creating a Lambda function which requests and validates the certificates. Unfortunately, those Lambda functions were manually deleted and now when I try to update my CDK resources, CloudFormation attempts to replace these Lambdas but fails because they no longer exist. I wish that CloudFormation would behave like Terraform and just say "oh that thing I need to replace isn't there, nbd I needed to replace it anyway, so let's carry on" but it does not. Not sure how to get out of this jam. Any help is appreciated.
[ "You have to import them back to CloudFormation. In TF it is same, and you also import resources into TF.\n", "The easiest fix to this drift is redeploying your CDK app with the deleted resource temporarily removed (e.g. commented out). CloudFormation will \"delete\" the already deleted resource, bringing the template back into sync with the deployed configuration. Then add back the resource to your app and deploy again. Problem solved.\nThere's a complication in your case. The missing Lambda function is being constructed indirectly by a higher-level CDK construct. Removing the L2/L3 parent will destroy more resources than just the Lambda. If you want to avoid this collateral damage, you can use escape hatch syntax and the node.tryRemoveChild method to surgically remove the missing Lambda only.\n" ]
[ 0, 0 ]
[]
[]
[ "amazon_cloudformation", "amazon_web_services", "aws_cdk" ]
stackoverflow_0074672849_amazon_cloudformation_amazon_web_services_aws_cdk.txt
Q: How can I remove the debug banner in Flutter? I'm using flutter screenshot and I expected the screenshot to not have a banner, but it has. Note that I get a not supported for emulator message for profile and release mode. A: On your MaterialApp set debugShowCheckedModeBanner to false. MaterialApp( debugShowCheckedModeBanner: false, ) The debug banner will also automatically be removed on the release build. A: Outdated If you are using Android Studio, you can find the option in the Flutter Inspector tab → More Actions. Or if you're using Dart DevTools, you can find the same button in the top right corner as well. A: Well, this is the simple answer you want. MaterialApp( debugShowCheckedModeBanner: false ) CupertinoApp( debugShowCheckedModeBanner: false ) But if you want to go deep with the app (want a release APK file (which doesn't have a debug banner) and if you are using Android Studio then go to Run → Flutter → Run 'main.dart' in Release mode. A: If you are using IntelliJ IDEA, there is an option in the Flutter Inspector to disable it. Run the project: When you are in the Flutter Inspector, click or choose "More Actions." When the menu appears, choose "Hide Debug Mode Banner": A: There is also another way for removing the "debug" banner from the Flutter app. Now after a new release there is no "debugShowCheckedModeBanner: false," code line in the main .dart file. So I think these methods are effective: If you are using Visual Studio Code, then install `"Dart DevTools" from extensions. After installation, you can easily find the "Dart DevTools" text icon at the bottom of Visual Studio Code. When you click on that text icon, a link will be opened in Google Chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot. NOTE: Dart DevTools is a Dart language debugger extension in Visual Studio Code If Dart DevTools is already installed in your Visual Studio Code, then you can directly open Google Chrome and open the URL "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX" Note: In this link, replace "XXXXX" by 5 digit port-id (on which your Flutter app is running) which will vary whenever you use the flutter run command and replace "ZZZZZ" by your global (unchangeable) 5 digit debugger-id Note: These Dart developer tools are only for the Google Chrome browser A: The debug banner appears only while in development and is automatically removed in the release build. To hide this there is a need to set debugShowCheckedModeBanner to false MaterialApp( debugShowCheckedModeBanner: false, ) A: Three ways to remove flutter debug banner: 1. In the MaterialApp/ScaffoldApp Snippet MaterialApp( debugShowCheckedModeBanner: false, ) OR ScaffoldApp( debugShowCheckedModeBanner: false, ); 2.By making release version of your app For running release version of your app, use this command flutter run --release Or if using real devices rather than emulators or simulators. make a build version of the app. flutter build apk 3.BY using dart dev tool to remove debug banner IN vs code type ctr+shift+pin windows and for mac cmd+shift+p and use this command to open dart dev tool Dart: Open DevTools A: On your MaterialApp set debugShowCheckedModeBanner to false. MaterialApp( debugShowCheckedModeBanner: false, ) The debug banner will also automatically be removed on release build. If you are using emulator or real device and you want to check it on release mode then => flutter run release --apk run this command on terminal Android Studio / Vs Code A: To remove the Flutter debug banner, there are several possibilities: The first one is to use the debugShowCheckModeBanner property in your MaterialApp widget. Code: MaterialApp( debugShowCheckedModeBanner: false, ) And then do a hot reload. The second possibility is to hide debug mode banner in Flutter Inspector if you use Android Studio or IntelliJ IDEA. The third possibility is to use Dart DevTools. A: Use: MaterialApp( debugShowCheckedModeBanner: false, ) This is the code for removing this banner. The debug banner is due to MaterialApp, e.g., you can see this banner on all that pages that use MaterialApp. There should be at least one MaterialApp in your app on main root. A: All other answers are great for Android Studio, but if using Visual Studio Code there is a command you can use to toggle this easily. Open the command palette (Mac: Cmd + Shift + P or Windows: Ctrl + Shift + P). Then type toggle debug-mode banner as shown below: A: In a Material app set debugShowCheckedModeBanner to false. A: official example MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Home'), ), ), debugShowCheckedModeBanner: false, //setup this property ) for more information, view the official documentation. A: Just do this in your MaterialApp or GetMaterialApp add this line debugShowCheckedModeBanner to false. like this MaterialApp( debugShowCheckedModeBanner: false, ) A: If you are still in debug mode, you can switch to release mode and the banner will be gone. You can also open the same Run/Debug Configurations window via shortcuts: ALT+SHIFT+F10, then Press 0 and Press ALT+a. Now enter --release. A: It's the app.dart class property. It displays a banner, saying "DEBUG" when running in checked mode. MaterialApp builds one of these by default. For disabling this banner in debug mode also, you can set a Boolean false. return MaterialApp( theme:.... debugShowCheckedModeBanner: false, home: SplashScreen(), ); In release mode this has no effect. A: set debugShowCheckedModeBanner to false in MaterialApp Widget and you are good to go. See the below example for a better understanding. MaterialApp( debugShowCheckedModeBanner: false, ) A: To hide the debug banner: For android: In MaterialApp widget select false, by default debugShowCheckedModeBanner. is true. MaterialApp( debugShowCheckedModeBanner: false, ) For IOS CupertinoApp: CupertinoApp( debugShowCheckedModeBanner: false ) A: If you use Scaffold in Return Section so add on Top MaterialApp and Restart void main() => runApp( const MaterialApp( debugShowCheckedModeBanner: false, home: Home()), ); A: You can use debugShowCheckedModeBanner inside MaterialApp: return MaterialApp( debugShowCheckedModeBanner: false, ... ); A: It can be done as MaterialApp( debugShowCheckedModeBanner: false, ) A: To remove the debug banner in Flutter, you can use the debugShowCheckedModeBanner property in your MaterialApp widget. You can set this property to false to hide the debug banner. Here is an example of how you can do this: MaterialApp( debugShowCheckedModeBanner: false, )
How can I remove the debug banner in Flutter?
I'm using flutter screenshot and I expected the screenshot to not have a banner, but it has. Note that I get a not supported for emulator message for profile and release mode.
[ "On your MaterialApp set debugShowCheckedModeBanner to false.\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\nThe debug banner will also automatically be removed on the release build.\n", "Outdated\n\nIf you are using Android Studio, you can find the option in the Flutter Inspector tab → More Actions.\n\n\nOr if you're using Dart DevTools, you can find the same button in the top right corner as well.\n\n\n\n", "Well, this is the simple answer you want.\nMaterialApp(\n debugShowCheckedModeBanner: false\n)\n\nCupertinoApp(\n debugShowCheckedModeBanner: false\n)\n\nBut if you want to go deep with the app (want a release APK file (which doesn't have a debug banner) and if you are using Android Studio then go to Run → Flutter → Run 'main.dart' in Release mode.\n", "If you are using IntelliJ IDEA, there is an option in the Flutter Inspector to disable it.\nRun the project:\n\n\nWhen you are in the Flutter Inspector, click or choose \"More Actions.\"\n\nWhen the menu appears, choose \"Hide Debug Mode Banner\":\n\n", "There is also another way for removing the \"debug\" banner from the Flutter app. Now after a new release there is no \"debugShowCheckedModeBanner: false,\" code line in the main .dart file. So I think these methods are effective:\n\nIf you are using Visual Studio Code, then install `\"Dart DevTools\" from extensions. After installation, you can easily find the \"Dart DevTools\" text icon at the bottom of Visual Studio Code. When you click on that text icon, a link will be opened in Google Chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.\n\nNOTE: Dart DevTools is a Dart language debugger extension in Visual Studio Code\n\nIf Dart DevTools is already installed in your Visual Studio Code, then you can directly open Google Chrome and open\nthe URL \"127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX\"\n\nNote: In this link, replace \"XXXXX\" by 5 digit port-id (on which your Flutter app is running) which will vary whenever you use the flutter run command and replace \"ZZZZZ\" by your global (unchangeable) 5 digit debugger-id\nNote: These Dart developer tools are only for the Google Chrome browser\n", "The debug banner appears only while in development and is automatically removed in the release build.\nTo hide this there is a need to set debugShowCheckedModeBanner to false\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\n\n", "Three ways to remove flutter debug banner:\n1. In the MaterialApp/ScaffoldApp\nSnippet\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\nOR\nScaffoldApp(\n debugShowCheckedModeBanner: false,\n );\n\n2.By making release version of your app\n\nFor running release version of your app, use this command\n\nflutter run --release\n\n\nOr if using real devices rather than emulators or simulators.\nmake a build version of the app.\n\nflutter build apk\n\n3.BY using dart dev tool to remove debug banner\nIN vs code type ctr+shift+pin windows and for mac cmd+shift+p and use this command to open dart dev tool\nDart: Open DevTools\n\n\n", "On your MaterialApp set debugShowCheckedModeBanner to false.\n MaterialApp(\n debugShowCheckedModeBanner: false,\n )\n\nThe debug banner will also automatically be removed on release build.\nIf you are using emulator or real device and you want to check it on release\nmode then =>\n flutter run release --apk \n\nrun this command on terminal Android Studio / Vs Code\n", "To remove the Flutter debug banner, there are several possibilities:\n\nThe first one is to use the debugShowCheckModeBanner property in your MaterialApp widget.\nCode:\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\nAnd then do a hot reload.\n\nThe second possibility is to hide debug mode banner in Flutter Inspector if you use Android Studio or IntelliJ IDEA.\n\n\nThe third possibility is to use Dart DevTools.\n\n\n", "Use:\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\nThis is the code for removing this banner.\nThe debug banner is due to MaterialApp, e.g., you can see this banner on all that pages that use MaterialApp.\nThere should be at least one MaterialApp in your app on main root.\n", "All other answers are great for Android Studio, but if using Visual Studio Code there is a command you can use to toggle this easily. Open the command palette (Mac: Cmd + Shift + P or Windows: Ctrl + Shift + P). Then type toggle debug-mode banner as shown below:\n\n", "In a Material app set debugShowCheckedModeBanner to false.\n", "official example\nMaterialApp(\n home: Scaffold(\n appBar: AppBar(\n title: const Text('Home'),\n ),\n ),\n debugShowCheckedModeBanner: false, //setup this property\n)\n\nfor more information, view the official documentation.\n", "Just do this in your MaterialApp or GetMaterialApp \nadd this line\n debugShowCheckedModeBanner to false.\nlike this\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\n", "If you are still in debug mode, you can switch to release mode and the banner will be gone.\n\n\nYou can also open the same Run/Debug Configurations window via shortcuts:\nALT+SHIFT+F10, then Press 0 and Press ALT+a.\nNow enter --release.\n", "It's the app.dart class property.\nIt displays a banner, saying \"DEBUG\" when running in checked mode. MaterialApp builds one of these by default.\nFor disabling this banner in debug mode also, you can set a Boolean false.\nreturn MaterialApp(\n theme:....\n debugShowCheckedModeBanner: false,\n home: SplashScreen(),\n);\n\nIn release mode this has no effect.\n", "set debugShowCheckedModeBanner to false in MaterialApp Widget and you are good to go. See the below example for a better understanding.\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\n", "To hide the debug banner:\nFor android: In MaterialApp widget select false, by default debugShowCheckedModeBanner.\nis true.\n MaterialApp(\n debugShowCheckedModeBanner: false,\n )\n\nFor IOS CupertinoApp:\nCupertinoApp(\n debugShowCheckedModeBanner: false\n)\n\n", "If you use Scaffold in Return Section so add on Top MaterialApp and Restart\nvoid main() => runApp(\n const MaterialApp(\n debugShowCheckedModeBanner: false, \n home: Home()),\n );\n\n", "You can use debugShowCheckedModeBanner inside MaterialApp:\nreturn MaterialApp(\n debugShowCheckedModeBanner: false,\n ...\n);\n\n", "It can be done as\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\n", "To remove the debug banner in Flutter, you can use the debugShowCheckedModeBanner property in your MaterialApp widget. You can set this property to false to hide the debug banner.\nHere is an example of how you can do this:\nMaterialApp(\n debugShowCheckedModeBanner: false,\n)\n\n" ]
[ 1314, 117, 64, 44, 26, 21, 17, 15, 11, 10, 10, 7, 6, 5, 4, 3, 3, 2, 1, 0, 0, 0 ]
[ "use this\nclass MyApp extends StatelessWidget {\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n debugShowCheckedModeBanner: false,\n theme: AppTheme.appTheme,\n home: HomePage(),\n );\n }\n}\n\n", "This is the simplest way.\nFor : MaterialApp(\ndebugShowCheckedModeBanner: false\n)\nFor : CupertinoApp(\ndebugShowCheckedModeBanner: false\n)\nIf you are logically handle another flutter components\nthem you use a bool variable & handle it.\nFor Example\nbool isDebug === false ;\nif(isDebug == true)\n{\ndebugShowCheckedModeBanner: true\n}\nelse\n{\ndebugShowCheckedModeBanner: false\n}\nThanks & Enjoy)):\n", "Go to main in the Lib folder widget Build find MaterialApp insert the debugShowCheckedModeBanner and add False\n MaterialApp(\n debugShowCheckedModeBanner: false`\n )\n\n" ]
[ -1, -1, -2 ]
[ "android_emulator", "flutter", "flutter_layout" ]
stackoverflow_0048893935_android_emulator_flutter_flutter_layout.txt
Q: Sorting Nested Lists with Various Elements I have a nested list like: [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]] I need to have this sorted by x (from least to most) as (other strings should stay where they are): [["bla","x=13","z=13","blabla"],["bla","blabla","x=17"],["x=27","blabla","bla","y=24"]] and also from most to least: [["x=27","blabla","bla","y=24"],["bla","blabla","x=17"],["bla","x=13","z=13","blabla"]] I think I have to use key=lambda but I just couldn't figure out how to do it. Searched through the web and this website but I just can't do it. A: Given your list: sort_this_list = [ ["bla","blabla","x=17"], ["bla","x=13","z=13","blabla"], ["x=27","blabla","bla","y=24"] ] First, extract the x element from the respective list! def get_x(list): # Iterate over the items in the given list for item in list: # Check if the item starts with "x=" if item.startswith("x="): # Extract the value of x and return it as an integer return int(item.split("=")[1]) Now you can sort it via sorted_ascending = sorted(sort_this_list, key=get_x) (Look up the sorted(..) function: This will return it ascending as you requested it.)! A: Just for the sake of it, here's one with a lambda function: mylist = [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]] mylist.sort(key = lambda l:int([item for item in l if 'x=' in item][0].split('=')[1]), reverse = True) # [['x=27', 'blabla', 'bla', 'y=24'], # ['bla', 'blabla', 'x=17'], # ['bla', 'x=13', 'z=13', 'blabla']]
Sorting Nested Lists with Various Elements
I have a nested list like: [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]] I need to have this sorted by x (from least to most) as (other strings should stay where they are): [["bla","x=13","z=13","blabla"],["bla","blabla","x=17"],["x=27","blabla","bla","y=24"]] and also from most to least: [["x=27","blabla","bla","y=24"],["bla","blabla","x=17"],["bla","x=13","z=13","blabla"]] I think I have to use key=lambda but I just couldn't figure out how to do it. Searched through the web and this website but I just can't do it.
[ "Given your list:\nsort_this_list = [\n [\"bla\",\"blabla\",\"x=17\"],\n [\"bla\",\"x=13\",\"z=13\",\"blabla\"],\n [\"x=27\",\"blabla\",\"bla\",\"y=24\"]\n]\n\nFirst, extract the x element from the respective list!\ndef get_x(list):\n # Iterate over the items in the given list\n for item in list:\n # Check if the item starts with \"x=\"\n if item.startswith(\"x=\"):\n # Extract the value of x and return it as an integer\n return int(item.split(\"=\")[1])\n\nNow you can sort it via sorted_ascending = sorted(sort_this_list, key=get_x) (Look up the sorted(..) function: This will return it ascending as you requested it.)!\n", "Just for the sake of it, here's one with a lambda function:\nmylist = [[\"bla\",\"blabla\",\"x=17\"],[\"bla\",\"x=13\",\"z=13\",\"blabla\"],[\"x=27\",\"blabla\",\"bla\",\"y=24\"]]\n\nmylist.sort(key = lambda l:int([item for item in l if 'x=' in item][0].split('=')[1]), reverse = True)\n\n# [['x=27', 'blabla', 'bla', 'y=24'],\n# ['bla', 'blabla', 'x=17'],\n# ['bla', 'x=13', 'z=13', 'blabla']]\n\n" ]
[ 1, 0 ]
[]
[]
[ "list", "nested_lists", "python", "python_3.x", "sorting" ]
stackoverflow_0074674996_list_nested_lists_python_python_3.x_sorting.txt
Q: How to start my progress bar counting after navigating the container section of my web page How to start my progressbar counting when i will go to container section of my webpage.I think i have to change my javascript code a bit please help me. HTML CODE <div class="container"> <div class="circular-progress"> <span class="progress-value">100%</span> </div> <span class="text">HTML & CSS</span> </div> <!-- JavaScript --> <script src="js/script.js"></script> CSS CODE /* Google Fonts - Poppins */ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap'); *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ height: 100vh; display: flex; align-items: center; justify-content: center; background: #7d2ae8; } .container{ display: flex; width: 420px; padding: 50px 0; border-radius: 8px; background: #fff; row-gap: 30px; flex-direction: column; align-items: center; } .circular-progress{ position: relative; height: 250px; width: 250px; border-radius: 50%; background: conic-gradient(#7d2ae8 3.6deg, #ededed 0deg); display: flex; align-items: center; justify-content: center; } .circular-progress::before{ content: ""; position: absolute; height: 210px; width: 210px; border-radius: 50%; background-color: #fff; } .progress-value{ position: relative; font-size: 40px; font-weight: 600; color: #7d2ae8; } .text{ font-size: 30px; font-weight: 500; color: #606060; } Javascriptcode let circularProgress = document.querySelector(".circular-progress"), progressValue = document.querySelector(".progress-value"); let progressStartValue = 0, progressEndValue = 90, speed = 100; let progress = setInterval(() => { progressStartValue++; progressValue.textContent = `${progressStartValue}%` circularProgress.style.background = `conic-gradient(#7d2ae8 ${progressStartValue * 3.6}deg, #ededed 0deg)` if(progressStartValue == progressEndValue){ clearInterval(progress); } }, speed); When i load my page at first then progressbar is count value But i want to start the counting after i go to that section of that webpage. A: You could use Intersection Observer. You choose an HTML element to observe and once this element is in view, that will trigger the start of the progress bar.
How to start my progress bar counting after navigating the container section of my web page
How to start my progressbar counting when i will go to container section of my webpage.I think i have to change my javascript code a bit please help me. HTML CODE <div class="container"> <div class="circular-progress"> <span class="progress-value">100%</span> </div> <span class="text">HTML & CSS</span> </div> <!-- JavaScript --> <script src="js/script.js"></script> CSS CODE /* Google Fonts - Poppins */ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap'); *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ height: 100vh; display: flex; align-items: center; justify-content: center; background: #7d2ae8; } .container{ display: flex; width: 420px; padding: 50px 0; border-radius: 8px; background: #fff; row-gap: 30px; flex-direction: column; align-items: center; } .circular-progress{ position: relative; height: 250px; width: 250px; border-radius: 50%; background: conic-gradient(#7d2ae8 3.6deg, #ededed 0deg); display: flex; align-items: center; justify-content: center; } .circular-progress::before{ content: ""; position: absolute; height: 210px; width: 210px; border-radius: 50%; background-color: #fff; } .progress-value{ position: relative; font-size: 40px; font-weight: 600; color: #7d2ae8; } .text{ font-size: 30px; font-weight: 500; color: #606060; } Javascriptcode let circularProgress = document.querySelector(".circular-progress"), progressValue = document.querySelector(".progress-value"); let progressStartValue = 0, progressEndValue = 90, speed = 100; let progress = setInterval(() => { progressStartValue++; progressValue.textContent = `${progressStartValue}%` circularProgress.style.background = `conic-gradient(#7d2ae8 ${progressStartValue * 3.6}deg, #ededed 0deg)` if(progressStartValue == progressEndValue){ clearInterval(progress); } }, speed); When i load my page at first then progressbar is count value But i want to start the counting after i go to that section of that webpage.
[ "You could use Intersection Observer. You choose an HTML element to observe and once this element is in view, that will trigger the start of the progress bar.\n" ]
[ 0 ]
[]
[]
[ "css", "html", "javascript", "progress_bar" ]
stackoverflow_0074673118_css_html_javascript_progress_bar.txt
Q: Kotlin access activity on recyclerView Adapter I have recyclerView and after click of card I would like to replace fragments in activity. The problem is I have no access to activity. Here is my code in adapter: override fun onBindViewHolder(holder: ViewHolder, position: Int) { val itemsViewModel = mList[position] holder.tagImage.setImageResource(itemsViewModel.tagImage) holder.tagName.text = itemsViewModel.tagName holder.tagDescription.text = itemsViewModel.tagDescription holder.itemView.setOnClickListener { Log.d(InTorry.TAG, itemsViewModel.tagName) val fragment = ProductsFragment() val transaction = activity?.supportFragmentManager?.beginTransaction() transaction?.replace(R.id.homeFragmentsContainer, fragment) //transaction?.disallowAddToBackStack() transaction?.commit() } } The above replace code works in fragment but in adapter there is "activity?" error. Kind Regards Jack A: There are multiple ways to solve this problem. Using Context You can use the context from holder.itemView and cast it into an Activity. This is probably the simplest way, however this can be problematic since a Context may represent an Activity, a Service, an Application, etc. in which case it may lead to a ClassCastException when used simply. Using Callback You can set up a callback from your Adapter to your Activity or Fragment and then replace your Fragment. Use JetPack Navigation This is my personal favorite as the latest versions allow you to access NavController from Activity, Fragment or any View in the hierarchy to navigate. This is just one of many benefits of using this library. Here is a link to Jetpack Navigation. A: To fix the error pass a reference of the activity to the adapter's constructor and save it as a member variable. Then use that variable to access the activity and perform the fragment transaction. class MyAdapter( private val activity: Activity, private val mList: List<ItemsViewModel> ) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { // Your existing code here holder.itemView.setOnClickListener { // Use the activity variable to access the activity and perform the fragment transaction val fragment = ProductsFragment() val transaction = activity.supportFragmentManager.beginTransaction() transaction.replace(R.id.homeFragmentsContainer, fragment) transaction.commit() } } // Other adapter methods here } When instantiating adapter, pass a reference to the activity to its constructor: val adapter = MyAdapter(this, mList) Alternatively, instead of passing the activity to the adapter, it is possible to pass a FragmentManager to the adapter, which can be used to perform the fragment transaction. class MyAdapter( private val fragmentManager: FragmentManager, private val mList: List<ItemsViewModel> ) : RecyclerView.Adapter<MyAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { // Your existing code here holder.itemView.setOnClickListener { // Use the fragmentManager variable to perform the fragment transaction val fragment = ProductsFragment() val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.homeFragmentsContainer, fragment) transaction.commit() } } // Other adapter methods here } Pass a reference to the FragmentManager to adapter constructor. This way lets avoid passing an activity reference to the adapter, which makes code more modular and reusable. val adapter = MyAdapter(supportFragmentManager, mList) A: The Simplest and Safer way to solve this is my using Callback from your holder to activity. Below is the step by step process : Decalare an Interface interface OnItemClick { fun onClick() } Implement that interface in you Activity and put the desired code class MainActivity : OnItemClick { ... override onClick() { // Do whatever you want val fragment = ProductsFragment() val transaction = fragmentManager.beginTransaction() transaction.replace(R.id.homeFragmentsContainer, fragment) transaction.commit() } } Create a variable of that Interface type in you Adapter and in your onBindViewHolder method invoke that interface class MyAdapter(val listener : OnItemClick) { ... override fun onBindViewHolder(holder: ViewHolder, position: Int) { ... listener.onClick() } Finally pass that interface to your Adapter from you Activity class MainActivity : OnItemClick { val adapter = MyAdapter(this) ... } NOTE : Please don't pass activity to context here and there you will get unexpected result and most probably a crash. A: After watching this video https://www.youtube.com/watch?v=WqrpcWXBz14 I managed to do it this way In Adapter class TagsAdapter(var mList: List<TagsViewModel>) : RecyclerView.Adapter<TagsAdapter.ViewHolder>() { var onItemClick: ((TagsViewModel) -> Unit)? = null//click listener STEP 1!!! override fun onBindViewHolder(holder: TagsAdapter.ViewHolder, position: Int) { holder.itemView.setOnClickListener { onItemClick?.invoke(itemsViewModel)//click listener STEP 2!!! } } } And in Fragment class TagsFragment : Fragment() { private lateinit var tagsRecyclerView: RecyclerView private var tagsArray = ArrayList<TagsViewModel>() private lateinit var adapter: TagsAdapter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adapter = TagsAdapter(tagsArray) tagsRecyclerView.adapter = adapter adapter.onItemClick = {//click listener STEP 3!!! val fragment = ProductsFragment() val transaction = activity?.supportFragmentManager?.beginTransaction() transaction?.replace(R.id.homeFragmentsContainer, fragment) //transaction?.disallowAddToBackStack() transaction?.commit() } } } It looks very clean and easy. I don't know is a correct way but it works
Kotlin access activity on recyclerView Adapter
I have recyclerView and after click of card I would like to replace fragments in activity. The problem is I have no access to activity. Here is my code in adapter: override fun onBindViewHolder(holder: ViewHolder, position: Int) { val itemsViewModel = mList[position] holder.tagImage.setImageResource(itemsViewModel.tagImage) holder.tagName.text = itemsViewModel.tagName holder.tagDescription.text = itemsViewModel.tagDescription holder.itemView.setOnClickListener { Log.d(InTorry.TAG, itemsViewModel.tagName) val fragment = ProductsFragment() val transaction = activity?.supportFragmentManager?.beginTransaction() transaction?.replace(R.id.homeFragmentsContainer, fragment) //transaction?.disallowAddToBackStack() transaction?.commit() } } The above replace code works in fragment but in adapter there is "activity?" error. Kind Regards Jack
[ "There are multiple ways to solve this problem.\n\nUsing Context\n\nYou can use the context from holder.itemView and cast it into an Activity.\nThis is probably the simplest way, however this can be problematic since a Context may represent an Activity, a Service, an Application, etc. in which case it may lead to a ClassCastException when used simply.\n\nUsing Callback\n\nYou can set up a callback from your Adapter to your Activity or Fragment and then replace your Fragment.\n\nUse JetPack Navigation\n\nThis is my personal favorite as the latest versions allow you to access NavController from Activity, Fragment or any View in the hierarchy to navigate. This is just one of many benefits of using this library.\nHere is a link to Jetpack Navigation.\n", "To fix the error pass a reference of the activity to the adapter's constructor and save it as a member variable. Then use that variable to access the activity and perform the fragment transaction.\nclass MyAdapter(\n private val activity: Activity, \n private val mList: List<ItemsViewModel>\n) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {\n\n override fun onBindViewHolder(holder: ViewHolder, position: Int) {\n // Your existing code here\n \n holder.itemView.setOnClickListener {\n // Use the activity variable to access the activity and perform the fragment transaction\n val fragment = ProductsFragment()\n val transaction = activity.supportFragmentManager.beginTransaction()\n transaction.replace(R.id.homeFragmentsContainer, fragment)\n transaction.commit()\n }\n }\n\n // Other adapter methods here\n}\n\nWhen instantiating adapter, pass a reference to the activity to its constructor:\nval adapter = MyAdapter(this, mList)\n\nAlternatively, instead of passing the activity to the adapter, it is possible to pass a FragmentManager to the adapter, which can be used to perform the fragment transaction.\nclass MyAdapter(\n private val fragmentManager: FragmentManager,\n private val mList: List<ItemsViewModel>\n) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {\n\n override fun onBindViewHolder(holder: ViewHolder, position: Int) {\n // Your existing code here\n \n holder.itemView.setOnClickListener {\n // Use the fragmentManager variable to perform the fragment transaction\n val fragment = ProductsFragment()\n val transaction = fragmentManager.beginTransaction()\n transaction.replace(R.id.homeFragmentsContainer, fragment)\n transaction.commit()\n }\n }\n\n // Other adapter methods here\n}\n\nPass a reference to the FragmentManager to adapter constructor. This way lets avoid passing an activity reference to the adapter, which makes code more modular and reusable.\nval adapter = MyAdapter(supportFragmentManager, mList)\n\n", "The Simplest and Safer way to solve this is my using Callback from your holder to activity. Below is the step by step process :\n\nDecalare an Interface\ninterface OnItemClick {\n fun onClick()\n}\n\n\nImplement that interface in you Activity and put the desired code\nclass MainActivity : OnItemClick {\n...\n\n override onClick() {\n // Do whatever you want\n val fragment = ProductsFragment()\n val transaction = fragmentManager.beginTransaction()\n transaction.replace(R.id.homeFragmentsContainer, fragment)\n transaction.commit()\n\n }\n}\n\n\nCreate a variable of that Interface type in you Adapter and in your onBindViewHolder method invoke that interface\nclass MyAdapter(val listener : OnItemClick) {\n... \n\n\noverride fun onBindViewHolder(holder: ViewHolder, position: Int) {\n ...\n listener.onClick()\n\n}\n\n\nFinally pass that interface to your Adapter from you Activity\nclass MainActivity : OnItemClick {\n val adapter = MyAdapter(this)\n...\n}\n\n\n\nNOTE : Please don't pass activity to context here and there you will get unexpected result and most probably a crash.\n", "After watching this video https://www.youtube.com/watch?v=WqrpcWXBz14\nI managed to do it this way\nIn Adapter\nclass TagsAdapter(var mList: List<TagsViewModel>) :\n RecyclerView.Adapter<TagsAdapter.ViewHolder>() {\n\n var onItemClick: ((TagsViewModel) -> Unit)? = null//click listener STEP 1!!!\n\n override fun onBindViewHolder(holder: TagsAdapter.ViewHolder, position: Int) {\n\n holder.itemView.setOnClickListener {\n\n onItemClick?.invoke(itemsViewModel)//click listener STEP 2!!!\n\n }\n }\n}\n\nAnd in Fragment\nclass TagsFragment : Fragment() {\n \n private lateinit var tagsRecyclerView: RecyclerView\n private var tagsArray = ArrayList<TagsViewModel>()\n private lateinit var adapter: TagsAdapter\n \n override fun onViewCreated(view: View, savedInstanceState: Bundle?) {\n super.onViewCreated(view, savedInstanceState)\n \n adapter = TagsAdapter(tagsArray)\n tagsRecyclerView.adapter = adapter\n \n adapter.onItemClick = {//click listener STEP 3!!!\n \n val fragment = ProductsFragment()\n\n val transaction = activity?.supportFragmentManager?.beginTransaction()\n transaction?.replace(R.id.homeFragmentsContainer, fragment)\n //transaction?.disallowAddToBackStack()\n transaction?.commit()\n }\n\n\n }\n}\n\nIt looks very clean and easy. I don't know is a correct way but it works\n" ]
[ 0, 0, 0, 0 ]
[]
[]
[ "android", "android_recyclerview", "kotlin" ]
stackoverflow_0074670400_android_android_recyclerview_kotlin.txt
Q: What does the variable do to this function in C? I recently asked for help on a code. However, I am confused of what does it do to my code. Anyways, this is already correct. I just want to know how does the parameters on this one work and their purpose, specifically af, bf, v and v2. void validateMoveHelper(int x1, int y1, int af, int bf, int v, int v2) { for(int a = 1, b = 1; board[x1 + af * a][y1 + bf * b] == ' '; a++, b++) { if((x1 + af * a) == v || (y1 + bf * b) == v2) return; printf("%d%d , ", x1 + af * a , y1 + bf * b); } } void validateMove(int x1, int y1) { printf( "Available coordinates to send the piece are: \n" ) ; validateMoveHelper(x1, y1, -1, -1, 1, 8); validateMoveHelper(x1, y1, 8, 1, -1, -1); validateMoveHelper(x1, y1, 8, 1, 1, 8); validateMoveHelper(x1, y1, -1, -1, -1, -1); } A: The validateMoveHelper function is a helper function that is used by the validateMove function to determine the available coordinates to which a piece can be moved on a chessboard. The validateMoveHelper function takes the following parameters: x1: The starting x-coordinate of the piece that is being moved. y1: The starting y-coordinate of the piece that is being moved. af: The amount to add to the x-coordinate for each step in the iteration. This parameter determines the direction in which the function will iterate over the chessboard. bf: The amount to add to the y-coordinate for each step in the iteration. This parameter determines the direction in which the function will iterate over the chessboard. v: The maximum or minimum value that the x-coordinate can have. This parameter determines when the iteration should stop. v2: The maximum or minimum value that the y-coordinate can have. This parameter determines when the iteration should stop. The validateMoveHelper function uses a for loop to iterate over the chessboard in the direction specified by the af and bf parameters. For each step in the iteration, the function checks if the current position on the chessboard is empty (i.e., if it contains a space character) and if the x-coordinate or y-coordinate has reached the maximum or minimum value specified by the v and v2 parameters. If either of these conditions is true, the function returns without printing any coordinates. Otherwise, it prints the current x-coordinate and y-coordinate. The validateMove function uses the validateMoveHelper function to iterate over the chessboard in four different directions (top-left, top-right, bottom-left, bottom-right) to determine the available coordinates to which a piece can be moved. It does this by calling validateMoveHelper four times, passing in different values for the af, bf, v, and v2 parameters to specify the direction and boundaries of the iteration. Overall, the validateMoveHelper and validateMove functions are used to determine the possible moves for a piece on a chessboard. The af and bf parameters determine the direction of the iteration, while the v and v2 parameters determine the boundaries of the iteration. These parameters enable the functions to handle a variety of different scenarios and move patterns on the chessboard.
What does the variable do to this function in C?
I recently asked for help on a code. However, I am confused of what does it do to my code. Anyways, this is already correct. I just want to know how does the parameters on this one work and their purpose, specifically af, bf, v and v2. void validateMoveHelper(int x1, int y1, int af, int bf, int v, int v2) { for(int a = 1, b = 1; board[x1 + af * a][y1 + bf * b] == ' '; a++, b++) { if((x1 + af * a) == v || (y1 + bf * b) == v2) return; printf("%d%d , ", x1 + af * a , y1 + bf * b); } } void validateMove(int x1, int y1) { printf( "Available coordinates to send the piece are: \n" ) ; validateMoveHelper(x1, y1, -1, -1, 1, 8); validateMoveHelper(x1, y1, 8, 1, -1, -1); validateMoveHelper(x1, y1, 8, 1, 1, 8); validateMoveHelper(x1, y1, -1, -1, -1, -1); }
[ "The validateMoveHelper function is a helper function that is used by the validateMove function to determine the available coordinates to which a piece can be moved on a chessboard. The validateMoveHelper function takes the following parameters:\n\nx1: The starting x-coordinate of the piece that is being moved.\n\ny1: The starting y-coordinate of the piece that is being moved.\n\naf: The amount to add to the x-coordinate for each step in the\niteration. This parameter determines the direction in which the\nfunction will iterate over the chessboard.\n\nbf: The amount to add to the y-coordinate for each step in the\niteration. This parameter determines the direction in which the\nfunction will iterate over the chessboard.\n\nv: The maximum or minimum value that the x-coordinate can have. This\nparameter determines when the iteration should stop.\n\nv2: The maximum or minimum value that the y-coordinate can have. This\nparameter determines when the iteration should stop.\n\n\nThe validateMoveHelper function uses a for loop to iterate over the chessboard in the direction specified by the af and bf parameters. For each step in the iteration, the function checks if the current position on the chessboard is empty (i.e., if it contains a space character) and if the x-coordinate or y-coordinate has reached the maximum or minimum value specified by the v and v2 parameters. If either of these conditions is true, the function returns without printing any coordinates. Otherwise, it prints the current x-coordinate and y-coordinate.\nThe validateMove function uses the validateMoveHelper function to iterate over the chessboard in four different directions (top-left, top-right, bottom-left, bottom-right) to determine the available coordinates to which a piece can be moved. It does this by calling validateMoveHelper four times, passing in different values for the af, bf, v, and v2 parameters to specify the direction and boundaries of the iteration.\nOverall, the validateMoveHelper and validateMove functions are used to determine the possible moves for a piece on a chessboard. The af and bf parameters determine the direction of the iteration, while the v and v2 parameters determine the boundaries of the iteration. These parameters enable the functions to handle a variety of different scenarios and move patterns on the chessboard.\n" ]
[ 0 ]
[]
[]
[ "c", "void" ]
stackoverflow_0074675047_c_void.txt
Q: How do i upload a vuejs project but i need to link it on a href I have a portfolio and we can find all my project. I need to open a vuejs project by clicking on a link(the portfolio is in HTML).The fact is that i tried to link it with the index.html, but i think it's not the method. I've already did the npm run build, but i can't find more on internet. Could you give me indications? Thanks for reading. A: To link a Vue.js project in an HTML page, you can use the following steps: First, build your Vue.js project using the command npm run build. This will generate a dist folder containing the built files for your project. Copy the dist folder and paste it into the same directory as your HTML page. In your HTML page, create a link to your Vue.js project using the a tag. The href attribute should point to the index.html file in your dist folder. For example: <a href="dist/index.html">My Vue.js Project</a> When the user clicks on the link, the Vue.js project will be loaded in the same browser window or tab. Note: If you want to open the Vue.js project in a new window or tab, you can use the target attribute of the a tag, like this: <a href="dist/index.html" target="_blank">My Vue.js Project</a> Hope this helps!
How do i upload a vuejs project but i need to link it on a href
I have a portfolio and we can find all my project. I need to open a vuejs project by clicking on a link(the portfolio is in HTML).The fact is that i tried to link it with the index.html, but i think it's not the method. I've already did the npm run build, but i can't find more on internet. Could you give me indications? Thanks for reading.
[ "To link a Vue.js project in an HTML page, you can use the following steps:\nFirst, build your Vue.js project using the command npm run build. This will generate a dist folder containing the built files for your project.\nCopy the dist folder and paste it into the same directory as your HTML page.\nIn your HTML page, create a link to your Vue.js project using the a tag. The href attribute should point to the index.html file in your dist folder. For example:\n<a href=\"dist/index.html\">My Vue.js Project</a>\n\nWhen the user clicks on the link, the Vue.js project will be loaded in the same browser window or tab.\nNote: If you want to open the Vue.js project in a new window or tab, you can use the target attribute of the a tag, like this:\n<a href=\"dist/index.html\" target=\"_blank\">My Vue.js Project</a>\n\nHope this helps!\n" ]
[ 1 ]
[]
[]
[ "html", "vue.js" ]
stackoverflow_0074675066_html_vue.js.txt
Q: discord.py "sub help command" I was wondering if it's possible to make a somewhat "sub help command" basically if I were to do ;help mute it would show how to use the mute command and so on for each command. Kinda like dyno how you can do ?help (command name) and it shows you the usage of the command. I have my own help command already finished but I was thinking about adding to it so if someone did ;help commandname it would show them the usage such as arguments I tried at the bottom but I don't think that will work. If you know how please let me know @client.hybrid_command(name = "help", with_app_command=True, description="Get a list of commands") @commands.guild_only() async def help(ctx, arg = None): pages = 3 cur_page = 1 roleplayembed = discord.Embed(color=embedcolor, title="Roleplay Commands") roleplayembed.add_field(name=f"{client.command_prefix}Cuddle", value="Cuddle a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Hug", value="Hug a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Kiss", value="Kiss a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Slap", value="Slap a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Pat", value="Pat a user and add a message(Optional)",inline=False) roleplayembed.set_footer(text=f"Page {cur_page+1} of {pages}") roleplayembed.timestamp = datetime.datetime.utcnow() basicembed = discord.Embed(color=embedcolor, title="Basic Commands") basicembed.add_field(name=f"{client.command_prefix}Waifu", value="Posts a random AI Generated Image of a waifu",inline=False) basicembed.add_field(name=f"{client.command_prefix}8ball", value="Works as an 8 ball",inline=False) basicembed.add_field(name=f"{client.command_prefix}Ara", value="Gives you a random ara ara from Kurumi Tokisaki",inline=False) basicembed.add_field(name=f"{client.command_prefix}Wikipedia", value="Search something up on the wiki",inline=False) basicembed.add_field(name=f"{client.command_prefix}Userinfo", value="Look up info about a user",inline=False) basicembed.add_field(name=f"{client.command_prefix}Ask", value="Ask the bot a question",inline=False) basicembed.add_field(name=f"{client.command_prefix}Askwhy", value="Ask the boy a question beginning with 'why'",inline=False) basicembed.add_field(name=f"{client.command_prefix}Avatar", value="Get a user's avatar or your own avatar",inline=False) basicembed.set_footer(text=f"Page {cur_page} of {pages}") basicembed.timestamp = datetime.datetime.utcnow() moderationembed = discord.Embed(color=embedcolor, title="Moderation Commands") moderationembed.add_field(name=f"{client.command_prefix}Kick", value="Kick a member",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Ban", value="Ban a member",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Slowmode", value="Set the slowmode of a channel",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Purge", value="Purge an amount of messages in a channel",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Mute", value="Mute a member for a time and reason",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Unmute", value="Unmute a member for a time and reason",inline=False) moderationembed.set_footer(text=f"Page {cur_page+2} of {pages}") moderationembed.timestamp = datetime.datetime.utcnow() contents = [basicembed, roleplayembed, moderationembed] if arg == None: message = await ctx.send(embed=contents[cur_page-1]) await message.add_reaction("◀️") await message.add_reaction("▶️") def check(reaction, user): return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] while True: try: reaction, user = await client.wait_for("reaction_add", timeout=60, check=check) if str(reaction.emoji) == "▶️": cur_page += 1 elif str(reaction.emoji) == "◀️": cur_page -= 1 if cur_page > pages: #check if forward on last page cur_page = 1 elif cur_page < 1: #check if back on first page cur_page = pages await message.edit(embed=contents[cur_page-1]) await message.remove_reaction(reaction, user) except asyncio.TimeoutError: await message.delete() break if arg.lower() == client.command_name: await ctx.reply(f"{client.command_prefix}{client.command_name}{client.command_argument}") A: There are several ways you can do this. When you're using slash commands (which you are currently not,) there is a really elegant way to do this in the form of SlashCommandGroups. This would get the commands as [command name] help instead, but I don't think that is a downside. This would work like this, an example I thought of was blocking: class Block(discord.ext.commands.Cog): block = SlashCommandGroup("block") def __init__(self, bot): self.bot = bot @block.command(name="add") async def add(args): # Something here @block.command(name="remove") async def remove(args): # Something here @block.command(name="help") async def help(args): # Get help message for this command This would expose the commands block add [args], block remove [args] and block help each of which calls their own sub-command in the cog, and I think this is the cleanest way to get a consistent help system. You can add this cog to your bot with bot.add_cog(Block(bot)) somewhere in your code. Specifically, I'd look into extensions Then, for what you want to do, You're not using slash commands, so you don't need to provide autocomplete. If you want to, you can do something really hacky, using this helper function, which will work as long as you have the function in your current scope: def help(function_name): return globals()[function_name].__doc__ Now, you can define the help of every function individually using docstrings, and the help command will simply get those doc strings and presumably do something with it. The way Dyno would do it is more complex, using slash commands again, but really similar to the first version. You simply add a slash command group again, but this time it is for helping specifically. I personally don't like this as much, as I think the code is a lot less clean, but if you really want the help [function] syntax instead of [function] help, this is how to do that: class Help(discord.ext.commands.Cog): help = SlashCommandGroup("help") def __init__(self, bot): self.bot = bot @help.command(name="block") async def block(args): # Send the user the help response for blocking @help.command(name="ask") async def ask(args): # Send the user the help response for asking I hope that helps! :-)
discord.py "sub help command"
I was wondering if it's possible to make a somewhat "sub help command" basically if I were to do ;help mute it would show how to use the mute command and so on for each command. Kinda like dyno how you can do ?help (command name) and it shows you the usage of the command. I have my own help command already finished but I was thinking about adding to it so if someone did ;help commandname it would show them the usage such as arguments I tried at the bottom but I don't think that will work. If you know how please let me know @client.hybrid_command(name = "help", with_app_command=True, description="Get a list of commands") @commands.guild_only() async def help(ctx, arg = None): pages = 3 cur_page = 1 roleplayembed = discord.Embed(color=embedcolor, title="Roleplay Commands") roleplayembed.add_field(name=f"{client.command_prefix}Cuddle", value="Cuddle a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Hug", value="Hug a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Kiss", value="Kiss a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Slap", value="Slap a user and add a message(Optional)",inline=False) roleplayembed.add_field(name=f"{client.command_prefix}Pat", value="Pat a user and add a message(Optional)",inline=False) roleplayembed.set_footer(text=f"Page {cur_page+1} of {pages}") roleplayembed.timestamp = datetime.datetime.utcnow() basicembed = discord.Embed(color=embedcolor, title="Basic Commands") basicembed.add_field(name=f"{client.command_prefix}Waifu", value="Posts a random AI Generated Image of a waifu",inline=False) basicembed.add_field(name=f"{client.command_prefix}8ball", value="Works as an 8 ball",inline=False) basicembed.add_field(name=f"{client.command_prefix}Ara", value="Gives you a random ara ara from Kurumi Tokisaki",inline=False) basicembed.add_field(name=f"{client.command_prefix}Wikipedia", value="Search something up on the wiki",inline=False) basicembed.add_field(name=f"{client.command_prefix}Userinfo", value="Look up info about a user",inline=False) basicembed.add_field(name=f"{client.command_prefix}Ask", value="Ask the bot a question",inline=False) basicembed.add_field(name=f"{client.command_prefix}Askwhy", value="Ask the boy a question beginning with 'why'",inline=False) basicembed.add_field(name=f"{client.command_prefix}Avatar", value="Get a user's avatar or your own avatar",inline=False) basicembed.set_footer(text=f"Page {cur_page} of {pages}") basicembed.timestamp = datetime.datetime.utcnow() moderationembed = discord.Embed(color=embedcolor, title="Moderation Commands") moderationembed.add_field(name=f"{client.command_prefix}Kick", value="Kick a member",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Ban", value="Ban a member",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Slowmode", value="Set the slowmode of a channel",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Purge", value="Purge an amount of messages in a channel",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Mute", value="Mute a member for a time and reason",inline=False) moderationembed.add_field(name=f"{client.command_prefix}Unmute", value="Unmute a member for a time and reason",inline=False) moderationembed.set_footer(text=f"Page {cur_page+2} of {pages}") moderationembed.timestamp = datetime.datetime.utcnow() contents = [basicembed, roleplayembed, moderationembed] if arg == None: message = await ctx.send(embed=contents[cur_page-1]) await message.add_reaction("◀️") await message.add_reaction("▶️") def check(reaction, user): return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] while True: try: reaction, user = await client.wait_for("reaction_add", timeout=60, check=check) if str(reaction.emoji) == "▶️": cur_page += 1 elif str(reaction.emoji) == "◀️": cur_page -= 1 if cur_page > pages: #check if forward on last page cur_page = 1 elif cur_page < 1: #check if back on first page cur_page = pages await message.edit(embed=contents[cur_page-1]) await message.remove_reaction(reaction, user) except asyncio.TimeoutError: await message.delete() break if arg.lower() == client.command_name: await ctx.reply(f"{client.command_prefix}{client.command_name}{client.command_argument}")
[ "There are several ways you can do this.\nWhen you're using slash commands (which you are currently not,) there is a really elegant way to do this in the form of SlashCommandGroups. This would get the commands as [command name] help instead, but I don't think that is a downside.\nThis would work like this, an example I thought of was blocking:\nclass Block(discord.ext.commands.Cog):\n block = SlashCommandGroup(\"block\")\n\n def __init__(self, bot):\n self.bot = bot\n\n @block.command(name=\"add\")\n async def add(args):\n # Something here\n\n @block.command(name=\"remove\")\n async def remove(args):\n # Something here\n\n @block.command(name=\"help\")\n async def help(args):\n # Get help message for this command\n\nThis would expose the commands block add [args], block remove [args] and block help each of which calls their own sub-command in the cog, and I think this is the cleanest way to get a consistent help system.\nYou can add this cog to your bot with bot.add_cog(Block(bot)) somewhere in your code. Specifically, I'd look into extensions\n\nThen, for what you want to do, You're not using slash commands, so you don't need to provide autocomplete. If you want to, you can do something really hacky, using this helper function, which will work as long as you have the function in your current scope:\ndef help(function_name):\n return globals()[function_name].__doc__\n\nNow, you can define the help of every function individually using docstrings, and the help command will simply get those doc strings and presumably do something with it.\n\nThe way Dyno would do it is more complex, using slash commands again, but really similar to the first version. You simply add a slash command group again, but this time it is for helping specifically. I personally don't like this as much, as I think the code is a lot less clean, but if you really want the help [function] syntax instead of [function] help, this is how to do that:\nclass Help(discord.ext.commands.Cog):\n help = SlashCommandGroup(\"help\")\n\n def __init__(self, bot):\n self.bot = bot\n\n @help.command(name=\"block\")\n async def block(args):\n # Send the user the help response for blocking\n\n @help.command(name=\"ask\")\n async def ask(args):\n # Send the user the help response for asking\n\nI hope that helps! :-)\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074661669_discord_discord.py_python.txt
Q: Can't add title to mapbox map I tried to create several maps and saved as png files. In cycle I got all mapes per year. I want to add which year on the map, and I tried title=i and fig.update_layout(title_text=i, title_x=0.5), but it does not work. import plotly.express as px import pandas as pd year = [1980,1981,1983] lat = [60.572959, 60.321403, 56.990280] lon = [40.572759, 41.321203, 36.990299] dataframe = pd.DataFrame(list(zip(year,lat,lon)), columns =['year', 'lat', 'lon']) for idx, i in enumerate(sorted(dataframe['year'].unique())): #for x in range(1980,2022): sp = sp1[sp1['year']==i] fig = px.scatter_mapbox(dataframe, lat='lat', lon="lon", color_discrete_sequence=["fuchsia"], zoom=2, height=400, opacity=0.3, title = i) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.update_layout(title_text=i, title_x=0.5) fig.write_image("all/plot{idx}.png".format(idx=idx)) I put the picture of one map as example. I want to add year for every map in any place. A: Use the annotations attribute of the previously created layout object in the update_layout method to add text - specified by the x and y coordinates. fig.update_layout(annotations=[ dict(text=i, x=0.5, y=0.5, font_size=15, showarrow=False) ]) Play around with the x and y coordinates to find the proper position you want to place your text at. A: All you should do is to specify a space for the title by customizing the margin: import plotly.express as px import pandas as pd df = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv" ) fig = px.scatter_mapbox(df, lat="lat", lon="long", size="cnt", zoom=3) fig.update_layout(mapbox_style="open-street-map") fig.update_layout( title_x=0.5, title_y=0.95, title_text="2011_february_us_airport_traffic", margin={"l": 0, "r": 0, "b": 0, "t": 80} ) fig.show() Output:
Can't add title to mapbox map
I tried to create several maps and saved as png files. In cycle I got all mapes per year. I want to add which year on the map, and I tried title=i and fig.update_layout(title_text=i, title_x=0.5), but it does not work. import plotly.express as px import pandas as pd year = [1980,1981,1983] lat = [60.572959, 60.321403, 56.990280] lon = [40.572759, 41.321203, 36.990299] dataframe = pd.DataFrame(list(zip(year,lat,lon)), columns =['year', 'lat', 'lon']) for idx, i in enumerate(sorted(dataframe['year'].unique())): #for x in range(1980,2022): sp = sp1[sp1['year']==i] fig = px.scatter_mapbox(dataframe, lat='lat', lon="lon", color_discrete_sequence=["fuchsia"], zoom=2, height=400, opacity=0.3, title = i) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.update_layout(title_text=i, title_x=0.5) fig.write_image("all/plot{idx}.png".format(idx=idx)) I put the picture of one map as example. I want to add year for every map in any place.
[ "Use the annotations attribute of the previously created layout object in the update_layout method to add text - specified by the x and y coordinates.\nfig.update_layout(annotations=[\n dict(text=i, x=0.5, y=0.5, font_size=15, showarrow=False)\n])\n\nPlay around with the x and y coordinates to find the proper position you want to place your text at.\n", "All you should do is to specify a space for the title by customizing the margin:\nimport plotly.express as px\nimport pandas as pd\n\ndf = pd.read_csv(\n \"https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv\"\n)\nfig = px.scatter_mapbox(df, lat=\"lat\", lon=\"long\", size=\"cnt\", zoom=3)\nfig.update_layout(mapbox_style=\"open-street-map\")\n\nfig.update_layout(\n title_x=0.5,\n title_y=0.95,\n title_text=\"2011_february_us_airport_traffic\",\n margin={\"l\": 0, \"r\": 0, \"b\": 0, \"t\": 80}\n)\n\nfig.show()\n\nOutput:\n\n" ]
[ 1, 1 ]
[]
[]
[ "mapbox", "plotly", "python" ]
stackoverflow_0074674956_mapbox_plotly_python.txt
Q: Xamarin Android: Cannot resolve GoogleSignIn and GoogleSignInClient I am not able to use GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn ) and GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient ) while implementing Google Sign In in Visual Studio with Xamarin Android while I can access other classes in App like: com.google.android.gms.auth.api.signin.GoogleSignInAccount; com.google.android.gms.auth.api.signin.GoogleSignInOptions; This is the guide I am following: https://developers.google.com/identity/sign-in/android/sign-in Aditional, I was looking for similar post in Java and other IDE like this post: Cannot resolve GoogleSignIn and GoogleSignInClient But, in my case the issue is in Xamarin Android with Visual Studio. I tried with oficcial and preliminar version of the nuget Xamarin.GooglePlayServices.Identity: Then, I tried with all nutgets avaliables in official and preliminar version of GooglePlayServices: And this is another post It doesn't work in my case, because the version Nutget doesn't avaliable: How do you integrate the new Google Sign-In on a Xamarin.Android app? Xamarin.GooglePlayServices.Identity 29.0.0-beta1 Finally, I have configured the Google Repository Tool in the SDK Manager too: A: Installing the package Xamarin.GooglePlayServices.Auth fixed the problem for me.
Xamarin Android: Cannot resolve GoogleSignIn and GoogleSignInClient
I am not able to use GoogleSignIn(com.google.android.gms.auth.api.signin.GoogleSignIn ) and GoogleSignInClient(com.google.android.gms.auth.api.signin.GoogleSignInClient ) while implementing Google Sign In in Visual Studio with Xamarin Android while I can access other classes in App like: com.google.android.gms.auth.api.signin.GoogleSignInAccount; com.google.android.gms.auth.api.signin.GoogleSignInOptions; This is the guide I am following: https://developers.google.com/identity/sign-in/android/sign-in Aditional, I was looking for similar post in Java and other IDE like this post: Cannot resolve GoogleSignIn and GoogleSignInClient But, in my case the issue is in Xamarin Android with Visual Studio. I tried with oficcial and preliminar version of the nuget Xamarin.GooglePlayServices.Identity: Then, I tried with all nutgets avaliables in official and preliminar version of GooglePlayServices: And this is another post It doesn't work in my case, because the version Nutget doesn't avaliable: How do you integrate the new Google Sign-In on a Xamarin.Android app? Xamarin.GooglePlayServices.Identity 29.0.0-beta1 Finally, I have configured the Google Repository Tool in the SDK Manager too:
[ "Installing the package Xamarin.GooglePlayServices.Auth fixed the problem for me.\n" ]
[ 0 ]
[]
[]
[ "android", "google_api", "google_oauth", "xamarin", "xamarin.android" ]
stackoverflow_0056468727_android_google_api_google_oauth_xamarin_xamarin.android.txt
Q: Can I add element while using Java stream groupingby For loop code is this. Param : ArrayList userList Map<String, User> map = new HashMap(); for (User user : userList) { String[] arr = user.getStringSeq().split(DELIMITER); String key = String.join(DELIMITER, arr[MENU_IDX], arr[GROUP_IDX]); if (Objects.isNull(map.get(key))) { Set<IOType> ioTypeSet = new HashSet<>(); ioTypeSet.add(IOType.valueOf(arr[IO_TYPE_IDX])); user.setIoTypes(ioTypeSet); map.put(key, user); } else { map.get(key).getIoTypes().add(IOType.valueOf(arr[IO_TYPE_IDX])); } } and i want to modify stream List<List<user>> userList = userList .stream() .collect(groupingBy( e -> { String[] arr = e.getStringSeq().split(DELIMITER); return String.join(DELIMITER, arr[0], arr[1]); }, mapping(e -> { IOType ioType = IOType.valueOf(e.getNavAuthSeq().split(DELIMITER)[2]); User user = new User(); user.addIoType(ioType); return user; }, toList()) )).values() .stream() .toList(); my stream code grouping list succefully but i want to remove same key element and put splited string like this List<List<user>> userList = userList .stream() .collect(groupingBy( e -> { String[] arr = e.getStringSeq().split(DELIMITER); return String.join(DELIMITER, arr[0], arr[1]); }, mapping(e -> { if (e.getIoTypes() != null) { e.getIoTypes().add(IOType.NONE); return null; } else { IOType ioType = IOType.valueOf(e.getStringSeq().split(DELIMITER)[2]); UserNavAuthsLoginDTO userNavAuthsLoginDTO = new UserNavAuthsLoginDTO(); userNavAuthsLoginDTO.addIoType(ioType); return userNavAuthsLoginDTO; } }, toList()) )).values() .stream() .toList(); but if else code doesn't work can i resove this problem? A: If you want to discard certain elements after inside the Collector after groupingBy, you can wrap mapping() with Collector filtering(). It expects a Predicate and retains only elements for which predicate gets evaluated to true. .collect(Collectors.groupingBy( e -> { }, // classifier Function of groupingBy Collectors.filtering(e -> { }, // Predicate of filtering Collectors.mapping(e -> { }, // mapper Function of mapping Collectors.toList()) ) )) Note that there's a difference between using filter() operation and Collector filtering(). Imagine a scenario when all elements mapped to a particular Key don't pass the predicate. In this case, the entry with this Key would be present in the resulting Map (and its Value would be an empty list). And if you apply filter() in the stream - there wouldn't be such entry. Alternatively, if it's not important to filter out elements after the grouping phase, you can use filter() operation, that would be a preferred way in such case. Also, worth to point out that you're performing side-effects on the mutable function parameter inside mapping() (to put it simple, anything that a function doesn't besides computing its resulting value is a side-effect). I'm not claiming that it will break things somehow, but it's definitely not very clean.
Can I add element while using Java stream groupingby
For loop code is this. Param : ArrayList userList Map<String, User> map = new HashMap(); for (User user : userList) { String[] arr = user.getStringSeq().split(DELIMITER); String key = String.join(DELIMITER, arr[MENU_IDX], arr[GROUP_IDX]); if (Objects.isNull(map.get(key))) { Set<IOType> ioTypeSet = new HashSet<>(); ioTypeSet.add(IOType.valueOf(arr[IO_TYPE_IDX])); user.setIoTypes(ioTypeSet); map.put(key, user); } else { map.get(key).getIoTypes().add(IOType.valueOf(arr[IO_TYPE_IDX])); } } and i want to modify stream List<List<user>> userList = userList .stream() .collect(groupingBy( e -> { String[] arr = e.getStringSeq().split(DELIMITER); return String.join(DELIMITER, arr[0], arr[1]); }, mapping(e -> { IOType ioType = IOType.valueOf(e.getNavAuthSeq().split(DELIMITER)[2]); User user = new User(); user.addIoType(ioType); return user; }, toList()) )).values() .stream() .toList(); my stream code grouping list succefully but i want to remove same key element and put splited string like this List<List<user>> userList = userList .stream() .collect(groupingBy( e -> { String[] arr = e.getStringSeq().split(DELIMITER); return String.join(DELIMITER, arr[0], arr[1]); }, mapping(e -> { if (e.getIoTypes() != null) { e.getIoTypes().add(IOType.NONE); return null; } else { IOType ioType = IOType.valueOf(e.getStringSeq().split(DELIMITER)[2]); UserNavAuthsLoginDTO userNavAuthsLoginDTO = new UserNavAuthsLoginDTO(); userNavAuthsLoginDTO.addIoType(ioType); return userNavAuthsLoginDTO; } }, toList()) )).values() .stream() .toList(); but if else code doesn't work can i resove this problem?
[ "If you want to discard certain elements after inside the Collector after groupingBy, you can wrap mapping() with Collector filtering(). It expects a Predicate and retains only elements for which predicate gets evaluated to true.\n.collect(Collectors.groupingBy(\n e -> { }, // classifier Function of groupingBy\n Collectors.filtering(e -> { }, // Predicate of filtering\n Collectors.mapping(e -> { }, // mapper Function of mapping\n Collectors.toList())\n )\n))\n\nNote that there's a difference between using filter() operation and Collector filtering(). Imagine a scenario when all elements mapped to a particular Key don't pass the predicate. In this case, the entry with this Key would be present in the resulting Map (and its Value would be an empty list). And if you apply filter() in the stream - there wouldn't be such entry.\nAlternatively, if it's not important to filter out elements after the grouping phase, you can use filter() operation, that would be a preferred way in such case.\nAlso, worth to point out that you're performing side-effects on the mutable function parameter inside mapping() (to put it simple, anything that a function doesn't besides computing its resulting value is a side-effect). I'm not claiming that it will break things somehow, but it's definitely not very clean.\n" ]
[ 0 ]
[]
[]
[ "collectors", "groupingby", "java", "java_stream" ]
stackoverflow_0074674971_collectors_groupingby_java_java_stream.txt
Q: Copy SOME values of array IF condition is being met into another array int a[] = {1, 6, 3, 4, 5, 8, 7}; for(int i = 0; i < a.length; i++){ if (a[i] % 2 == 0) { int b = new int[3]; b[i] = a[i]; System.out.print(b[i] + " "); } } //I want a new array b, to have the even values of a. How can I make this work? A: I think you need to check the ordering of your code. Each For loop iteration, if your number meets the criteria your creating a new array called b and adding the value, however, on the next iteration, the array no longer exists so another new one is created. In addition to this, you're also setting the index of b, based on the index of a, however, b's array only has 3 elements, therefore it will fail from index 4 onwards. So you would also need a second index to reference (in the below I've called this 'j', and you would use this to assign values to b's array Consider declaring b under your declaration of a, then print the result outside of the for loop like so: int[] a = new int[] {1, 6, 3, 4, 5, 8, 7}; int[] b = new int[3]; int j = 0; for(int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { b[j] = a[i]; j++; } } // Output the Values of b here for(int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } One thing to keep in mind here, that this will work for the values you've provided, however what if the values change and there are more elements in a's array? You'd need to define b with more elements, so using an array with a set length wouldn't be best practise here. Consider using a List instead. A: There are two ways. First way introduce a new counter: int a[] = {1, 6, 3, 4, 5, 8, 7}; int b[] = new int[a.length/2]; int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) { b[count] = a[i]; System.out.print(b[count] + " "); count++; } } The second way is to use Java Streams: int[] ints = Arrays.stream(a).filter(item -> item % 2 == 0).toArray(); for (int i : ints) { System.out.println(i); } The second way can be problematic in performance optimized environments, or if the arrays are really huge, as we need to iterate twice over the items. See also benchmarking of Java Streams here If you only need to print the result, you can avoid the iterations via Arrays.stream(a).filter(item -> item % 2 == 0).forEach(System.out::println);
Copy SOME values of array IF condition is being met into another array
int a[] = {1, 6, 3, 4, 5, 8, 7}; for(int i = 0; i < a.length; i++){ if (a[i] % 2 == 0) { int b = new int[3]; b[i] = a[i]; System.out.print(b[i] + " "); } } //I want a new array b, to have the even values of a. How can I make this work?
[ "I think you need to check the ordering of your code.\nEach For loop iteration, if your number meets the criteria your creating a new array called b and adding the value, however, on the next iteration, the array no longer exists so another new one is created.\nIn addition to this, you're also setting the index of b, based on the index of a, however, b's array only has 3 elements, therefore it will fail from index 4 onwards. So you would also need a second index to reference (in the below I've called this 'j', and you would use this to assign values to b's array\nConsider declaring b under your declaration of a, then print the result outside of the for loop like so:\nint[] a = new int[] {1, 6, 3, 4, 5, 8, 7};\nint[] b = new int[3];\nint j = 0;\n\nfor(int i = 0; i < a.length; i++) {\n if (a[i] % 2 == 0) {\n b[j] = a[i];\n j++;\n }\n}\n// Output the Values of b here\nfor(int i = 0; i < b.length; i++) {\n System.out.print(b[i] + \" \");\n}\n\nOne thing to keep in mind here, that this will work for the values you've provided, however what if the values change and there are more elements in a's array? You'd need to define b with more elements, so using an array with a set length wouldn't be best practise here.\nConsider using a List instead.\n", "There are two ways. First way introduce a new counter:\n int a[] = {1, 6, 3, 4, 5, 8, 7};\n int b[] = new int[a.length/2];\n int count = 0;\n for (int i = 0; i < a.length; i++) {\n if (a[i] % 2 == 0) {\n b[count] = a[i];\n System.out.print(b[count] + \" \");\n count++;\n }\n }\n\nThe second way is to use Java Streams:\n int[] ints = Arrays.stream(a).filter(item -> item % 2 == 0).toArray();\n for (int i : ints) {\n System.out.println(i);\n }\n\n\nThe second way can be problematic in performance optimized environments, or if the arrays are really huge, as we need to iterate twice over the items.\nSee also benchmarking of Java Streams here\nIf you only need to print the result, you can avoid the iterations via\nArrays.stream(a).filter(item -> item % 2 == 0).forEach(System.out::println);\n\n" ]
[ 1, 1 ]
[]
[]
[ "java" ]
stackoverflow_0074674948_java.txt
Q: When writing a C++, if the source file is being saved, compile it I have this question : when I save a C++ source file in VsCode, I always need to run a task through this command, then : this one, translated to English would be : "Compile this C++ active file using g++ compiler". I would like to know if there was a way to make sure that if the file is saved it will be also compiled. I tried to search everything possible but I really couldn't file something useful, plus I am not very familiar to .json language. Infos : Code Editor : Visual Studio Code Task Language : .json Compiler : g++ Version 2.0.0 Terminal Used For Compiling : Windows PowerShell { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe compila il file attivo", "command": "C:\\msys64\\mingw64\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": ["$gcc"], "group": "build", "detail": "compilatore: C:\\msys64\\mingw64\\bin\\g++.exe" } ] } The normal procedure is to save the file, use the commands I put above, and then run the code from the terminal. A: EDIT: Sorry, my old approach didn't work and I noticed when re-reading the task. In order to automatically run the build task when a file is saved, you should use the "file_watcher" (instead of my previous implemention) setting in the .vscode/settings.json file: { "files.autoSave": "afterDelay", "files.watcherExclude": { "**/.git/objects/**": true, "**/.git/subtree-cache/**": true, "**/node_modules/**": true }, "file_watcher": { "c:\msys64\mingw64\bin\g++.exe": ["${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"] } } You will need to update the paths in the file_watcher setting to match your local configuration. You may also need to modify the build command and its arguments to match your project's requirements.
When writing a C++, if the source file is being saved, compile it
I have this question : when I save a C++ source file in VsCode, I always need to run a task through this command, then : this one, translated to English would be : "Compile this C++ active file using g++ compiler". I would like to know if there was a way to make sure that if the file is saved it will be also compiled. I tried to search everything possible but I really couldn't file something useful, plus I am not very familiar to .json language. Infos : Code Editor : Visual Studio Code Task Language : .json Compiler : g++ Version 2.0.0 Terminal Used For Compiling : Windows PowerShell { "version": "2.0.0", "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe compila il file attivo", "command": "C:\\msys64\\mingw64\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": ["$gcc"], "group": "build", "detail": "compilatore: C:\\msys64\\mingw64\\bin\\g++.exe" } ] } The normal procedure is to save the file, use the commands I put above, and then run the code from the terminal.
[ "EDIT: Sorry, my old approach didn't work and I noticed when re-reading the task.\nIn order to automatically run the build task when a file is saved, you should use the \"file_watcher\" (instead of my previous implemention) setting in the .vscode/settings.json file:\n{\n \"files.autoSave\": \"afterDelay\",\n \"files.watcherExclude\": {\n \"**/.git/objects/**\": true,\n \"**/.git/subtree-cache/**\": true,\n \"**/node_modules/**\": true\n },\n \"file_watcher\": {\n \"c:\\msys64\\mingw64\\bin\\g++.exe\": [\"${file}\", \"-o\", \"${fileDirname}\\\\${fileBasenameNoExtension}.exe\"]\n }\n}\n\nYou will need to update the paths in the file_watcher setting to match your local configuration. You may also need to modify the build command and its arguments to match your project's requirements.\n" ]
[ 1 ]
[]
[]
[ "c++", "visual_studio_code" ]
stackoverflow_0074675080_c++_visual_studio_code.txt
Q: Godot Mono : GetChild by name Some context : In Godot, one is constantly working with nodes and those nodes' children. Godot has made the design choice of letting the dev manipulate nodes with some sort of querying language that often relies on the full path (starting from the root of the current scene). For example if the scene is structured like this : MyRootNode | |-- MyChild1 | | | |-- MySubChild1 | | |-- Mychild2 ...then the devs are encouraged to access "MySubChild1" with a path : node = get_node("MyRootNode/MyChild1/MySubChild1") (note: I''m using the verbose "get_node" syntax rather than $ syntax for readability to C# devs) Because of that ease of use, I can see that GDScript devs have a tendency to do this : root = get_node("MyRootNode") child1 = get_node("MyRootNode/MyChild1") subchild1 = get_node("MyRootNode/MyChild1/MySubChild1") ...rather than this (pseudo-code) : root = get_node("MyRootNode") child1 = root.get_child("MyChild1") subchild1 = child1 .get_child("MySubChild1") It makes perfect sense to write queries in a weakly-typed scripting language : all the queryable items have more or less the same type. The named version of get_child() doesn't even exist. In reality you would need to do this : root = get_node("MyRootNode") child1 = root.get_child(0) // first child subchild1 = child1 .get_child(0) // first child ================= This is all very awkward for a C# developer. Because of the typing. It's like we're given safety but then it's instantly taken away. Imagine this : public class MyRootNode : Node { private Control MyChild1 = null; // initialized in _Ready once and for all public override void _Ready() { MyChild1 = GetNode<Control>("MyChild1"); } public override void _Process(float delta) { // Not possible!!! var mySubChild1 = MyChild1.GetChild<TextureRect>("MySubChild1"); } } My question : Is there a way of getting a child in a safe way? It seems to me that none of the solutions seem natural (as developed below), and I mean "safe" in contrast to that. If I do this : var mySubChild1 = GetNode<TextureRect>("MyRootNode/MyChild1/MySubChild1"); ...then it's extremely unsafe in case of nodes renaming or if I decide to change the tree structure. If I do this : var mySubChild1 = MyChild1.GetChild<TextureRect>(0); ....then it's still horrendously unreadable (accessing named items by index? No thanks) As a C# dev, how do you do it? A: My question : It seems to me that there's no way of getting a child in a safe way. None of the solutions seem natural. That is not a question. That is an statement of opinion. If I do this: var mySubChild1 = GetNode<TextureRect>("MyRootNode/MyChild1/MySubChild1"); …then it's extremely unsafe in case of nodes renaming or if I decide to change the tree structure. This is more unsafe that just a matter of changing the code. The problem is that the scene tree can change independently of the code. In my own terms: the scene tree is external to the code. And thus, the scene tree changing is a reason of change for the code. In other words, the scene tree changing is a responsibility of the code. Remember single responsibility principle? That is how the software architects would suggest you deal with potential external changes. Make a piece of your code that is the only part that needs to change when the external change happens, so the change does not propagate across your code. I would relax it and say that it does not have to be a separate class, it just has to be self-contained. In that order of ideas, this makes sense: onready var root = get_node("MyRootNode") onready var child1 = get_node("MyRootNode/MyChild1") onready var subchild1 = get_node("MyRootNode/MyChild1/MySubChild1") If you use these kind of declarations and initialization on top of your file, that is the only place where you would have to change the code to fix it. Granted, you don't have onready in C#, instead you have to do it on _Ready. If I do this: var mySubChild1 = MyChild1.GetChild<TextureRect>(0); … then it's still horrendously unreadable (accessing named items by index? No thanks) Agreed. Then don't do it. As a C# dev, how do you do it? I don't know what C# developers do. Because I'm not actively using C# at the time. Now, I did bring up a few other things in comments. First, if you are in control of the project, you can make sure your code does not fail. That of course might means changing the paths… However, if you use Scene Unique Nodes you can minimize it. This code: onready var root = get_node("MyRootNode") onready var child1 = get_node("MyRootNode/MyChild1") onready var subchild1 = get_node("MyRootNode/MyChild1/MySubChild1") Would turn into this: onready var root = get_node("%MyRootNode") onready var child1 = get_node("%MyChild1") onready var subchild1 = get_node("%MySubChild1") That is, the scene tree hierarchy is no longer relevant. And given that you give good names to your Nodes, you should be able to move them around in your scene tree without further issue. And to be clear, this is implemented in the get_node function so other languages such as C# can use (and GDScript gets some syntactic sugar on top, which I'm not using here). So yes, you can do that in C#: private Control MyChild1 = null; public override void _Ready() { MyChild1 = GetNode<Control>("%MyChild1"); } Second, you can use get_node_or_null (GetNodeOrNull in C#). So your code does not throw when there isn't a node. Instead you can handle the null. Speaking of nulls. When a Node is freed (e.g. by calling queue_free, which is QueueFree in C#) it does not make the references to it null. And no, Godot does not override the equality operators in C#. Which is why we also have is_instance_valid (Object.IsInstanceValid in C#). Third, the idea of getting a child by name is not needed in Godot because get_node et.al. can do it. To be clear, get_node does not work from the root of the current scene, it works from the Node on which you call it. So you can do this: public class MyRootNode : Node { private Control MyChild1 = null; // initialized in _Ready once and for all public override void _Ready() { MyChild1 = GetNode<Control>("MyChild1"); } public override void _Process(float delta) { // Notice I'm using GetNode here var mySubChild1 = MyChild1.GetNode<TextureRect>("MySubChild1"); } } I don't know if that is satisfactory for you, and I don't know if that is a common practice. A: Someone else posted this answer in a different discussion channel : It provides extra elements, more centered around C#'s possibilities. if it’s exported nodepaths I highly recommend https://github.com/31/GodotOnReady it cuts down on a lot of boilerplate code. Otherwise parentNode.GetNode(“path”) has been working great. Using % in combination with "Access as Scene Unique Name" is cool with stuff that you will tweak and move around a lot, I use it with UI mostly. For additional safety, you can rock parentNode.GetNodeOrNull(path). Unlike GetNode, GetNodeOrNull with a type won’t raise an Exception if something doesn't match (type or name), it just returns null. So at least it won’t silently burn you. Best practice I found is to only use these methods in node setup methods. Otherwise I do regular dependency injection, and groups to find what I need. That being said, I always advocate failing loudly and failing fast, so I only use GetNode and existing references. If it explodes it means I messed up.
Godot Mono : GetChild by name
Some context : In Godot, one is constantly working with nodes and those nodes' children. Godot has made the design choice of letting the dev manipulate nodes with some sort of querying language that often relies on the full path (starting from the root of the current scene). For example if the scene is structured like this : MyRootNode | |-- MyChild1 | | | |-- MySubChild1 | | |-- Mychild2 ...then the devs are encouraged to access "MySubChild1" with a path : node = get_node("MyRootNode/MyChild1/MySubChild1") (note: I''m using the verbose "get_node" syntax rather than $ syntax for readability to C# devs) Because of that ease of use, I can see that GDScript devs have a tendency to do this : root = get_node("MyRootNode") child1 = get_node("MyRootNode/MyChild1") subchild1 = get_node("MyRootNode/MyChild1/MySubChild1") ...rather than this (pseudo-code) : root = get_node("MyRootNode") child1 = root.get_child("MyChild1") subchild1 = child1 .get_child("MySubChild1") It makes perfect sense to write queries in a weakly-typed scripting language : all the queryable items have more or less the same type. The named version of get_child() doesn't even exist. In reality you would need to do this : root = get_node("MyRootNode") child1 = root.get_child(0) // first child subchild1 = child1 .get_child(0) // first child ================= This is all very awkward for a C# developer. Because of the typing. It's like we're given safety but then it's instantly taken away. Imagine this : public class MyRootNode : Node { private Control MyChild1 = null; // initialized in _Ready once and for all public override void _Ready() { MyChild1 = GetNode<Control>("MyChild1"); } public override void _Process(float delta) { // Not possible!!! var mySubChild1 = MyChild1.GetChild<TextureRect>("MySubChild1"); } } My question : Is there a way of getting a child in a safe way? It seems to me that none of the solutions seem natural (as developed below), and I mean "safe" in contrast to that. If I do this : var mySubChild1 = GetNode<TextureRect>("MyRootNode/MyChild1/MySubChild1"); ...then it's extremely unsafe in case of nodes renaming or if I decide to change the tree structure. If I do this : var mySubChild1 = MyChild1.GetChild<TextureRect>(0); ....then it's still horrendously unreadable (accessing named items by index? No thanks) As a C# dev, how do you do it?
[ "\nMy question : It seems to me that there's no way of getting a child in a safe way. None of the solutions seem natural.\n\nThat is not a question. That is an statement of opinion.\n\n\nIf I do this:\nvar mySubChild1 = GetNode<TextureRect>(\"MyRootNode/MyChild1/MySubChild1\");\n\n…then it's extremely unsafe in case of nodes renaming or if I decide to change the tree structure.\n\nThis is more unsafe that just a matter of changing the code. The problem is that the scene tree can change independently of the code. In my own terms: the scene tree is external to the code. And thus, the scene tree changing is a reason of change for the code. In other words, the scene tree changing is a responsibility of the code.\nRemember single responsibility principle? That is how the software architects would suggest you deal with potential external changes. Make a piece of your code that is the only part that needs to change when the external change happens, so the change does not propagate across your code. I would relax it and say that it does not have to be a separate class, it just has to be self-contained.\nIn that order of ideas, this makes sense:\nonready var root = get_node(\"MyRootNode\")\nonready var child1 = get_node(\"MyRootNode/MyChild1\")\nonready var subchild1 = get_node(\"MyRootNode/MyChild1/MySubChild1\")\n\nIf you use these kind of declarations and initialization on top of your file, that is the only place where you would have to change the code to fix it. Granted, you don't have onready in C#, instead you have to do it on _Ready.\n\n\nIf I do this:\nvar mySubChild1 = MyChild1.GetChild<TextureRect>(0);\n\n… then it's still horrendously unreadable (accessing named items by index? No thanks)\n\nAgreed. Then don't do it.\n\n\nAs a C# dev, how do you do it?\n\nI don't know what C# developers do. Because I'm not actively using C# at the time.\n\nNow, I did bring up a few other things in comments.\nFirst, if you are in control of the project, you can make sure your code does not fail. That of course might means changing the paths… However, if you use Scene Unique Nodes you can minimize it.\nThis code:\nonready var root = get_node(\"MyRootNode\")\nonready var child1 = get_node(\"MyRootNode/MyChild1\")\nonready var subchild1 = get_node(\"MyRootNode/MyChild1/MySubChild1\")\n\nWould turn into this:\nonready var root = get_node(\"%MyRootNode\")\nonready var child1 = get_node(\"%MyChild1\")\nonready var subchild1 = get_node(\"%MySubChild1\")\n\nThat is, the scene tree hierarchy is no longer relevant. And given that you give good names to your Nodes, you should be able to move them around in your scene tree without further issue. And to be clear, this is implemented in the get_node function so other languages such as C# can use (and GDScript gets some syntactic sugar on top, which I'm not using here).\nSo yes, you can do that in C#:\n private Control MyChild1 = null;\n\n public override void _Ready()\n {\n MyChild1 = GetNode<Control>(\"%MyChild1\");\n }\n\n\nSecond, you can use get_node_or_null (GetNodeOrNull in C#). So your code does not throw when there isn't a node. Instead you can handle the null.\nSpeaking of nulls. When a Node is freed (e.g. by calling queue_free, which is QueueFree in C#) it does not make the references to it null. And no, Godot does not override the equality operators in C#. Which is why we also have is_instance_valid (Object.IsInstanceValid in C#).\n\nThird, the idea of getting a child by name is not needed in Godot because get_node et.al. can do it.\nTo be clear, get_node does not work from the root of the current scene, it works from the Node on which you call it. So you can do this:\npublic class MyRootNode : Node\n{\n\n private Control MyChild1 = null; // initialized in _Ready once and for all\n\n public override void _Ready()\n {\n MyChild1 = GetNode<Control>(\"MyChild1\");\n }\n\n public override void _Process(float delta)\n {\n // Notice I'm using GetNode here\n var mySubChild1 = MyChild1.GetNode<TextureRect>(\"MySubChild1\");\n }\n}\n\nI don't know if that is satisfactory for you, and I don't know if that is a common practice.\n", "Someone else posted this answer in a different discussion channel : It provides extra elements, more centered around C#'s possibilities.\n\nif it’s exported nodepaths I highly recommend\nhttps://github.com/31/GodotOnReady it cuts down on a lot of\nboilerplate code.\nOtherwise parentNode.GetNode(“path”) has been working great.\nUsing % in combination with \"Access as Scene Unique Name\" is\ncool with stuff that you will tweak and move around a lot, I use\nit with UI mostly.\nFor additional safety, you can rock parentNode.GetNodeOrNull(path).\nUnlike GetNode, GetNodeOrNull with a type won’t raise an Exception if\nsomething doesn't match (type or name), it just returns null.\nSo at least it won’t silently burn you.\nBest practice I found is to only use these methods in node setup\nmethods.\nOtherwise I do regular dependency injection, and groups to\nfind what I need.\nThat being said, I always advocate failing loudly and failing fast,\nso I only use GetNode and existing references. If it explodes\nit means I messed up.\n\n" ]
[ 0, 0 ]
[]
[]
[ "godot", "mono" ]
stackoverflow_0074593927_godot_mono.txt
Q: How can I identify a common character in 2 Strings in Excel? Suppose I have ABC in cell A1 and XaA in cell B1. Taking into account upper and lower case I would like to recognize that A is indeed in common. How can I do this using Excel or Google Sheets function? Thank you I used =INDEX(FLATTEN(FILTER(FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1))),REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1)))<>"")), FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1))),REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1)))<>""))<>"")&""&TRANSPOSE(FILTER(FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2))),REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2)))<>"")), FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2))),REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2)))<>""))<>"")))) formula but clearly I am not moving in the right direction. A: Use regexmatch() and regexextract(), like this: =regexmatch( B1, join( "|", unique( transpose( regexextract(A1, rept("(.)", len(A1))) ) ) ) ) A: another approach... (handy if you have characters that needs to be escaped in regex) if you untangle each: =REGEXEXTRACT(A20, REPT("(.)", LEN(A20))) then you can filter it: =FILTER(C20:E20, COUNTIF(C21:E21, C20:E20)) in one go: =LAMBDA(a, b, FILTER(a, COUNTIF(b, a)))( REGEXEXTRACT(A20, REPT("(.)", LEN(A20))), REGEXEXTRACT(B20, REPT("(.)", LEN(B20))))
How can I identify a common character in 2 Strings in Excel?
Suppose I have ABC in cell A1 and XaA in cell B1. Taking into account upper and lower case I would like to recognize that A is indeed in common. How can I do this using Excel or Google Sheets function? Thank you I used =INDEX(FLATTEN(FILTER(FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1))),REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1)))<>"")), FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1))),REGEXEXTRACT(TO_TEXT(E1), REPT("(.)", LEN(E1)))<>""))<>"")&""&TRANSPOSE(FILTER(FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2))),REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2)))<>"")), FLATTEN(FILTER(REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2))),REGEXEXTRACT(TO_TEXT(E2), REPT("(.)", LEN(E2)))<>""))<>"")))) formula but clearly I am not moving in the right direction.
[ "Use regexmatch() and regexextract(), like this:\n=regexmatch( B1, join( \"|\", unique( transpose( regexextract(A1, rept(\"(.)\", len(A1))) ) ) ) )\n", "another approach... (handy if you have characters that needs to be escaped in regex)\nif you untangle each:\n=REGEXEXTRACT(A20, REPT(\"(.)\", LEN(A20)))\n\nthen you can filter it:\n=FILTER(C20:E20, COUNTIF(C21:E21, C20:E20))\n\n\n\nin one go:\n=LAMBDA(a, b, FILTER(a, COUNTIF(b, a)))(\n REGEXEXTRACT(A20, REPT(\"(.)\", LEN(A20))), \n REGEXEXTRACT(B20, REPT(\"(.)\", LEN(B20))))\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "google_sheets" ]
stackoverflow_0074671293_google_sheets.txt
Q: Calculating Finish Time of FCFS & SJF Scheduling Algorithm VB.Net System Need help for First Come First Serve (FCFS) and Shortest Job First (SJF) Algorithm System on getting finish time for both algorithms. Language: VB.Net System GIU Need help for getting the value of finish time for both algorithms. A: For calculating the finish time of the First Come First Serve (FCFS) scheduling algorithm, the following formula can be used: Finish Time = Arrival Time + Service Time For calculating the finish time of the Shortest Job First (SJF) scheduling algorithm, the following formula can be used: Finish Time = Maximum(Previous Finish Time, Arrival Time) + Service Time In Visual Basic .NET, the above formulas can be implemented using the following code: For FCFS: Dim finishTime as Integer finishTime = arrivalTime + serviceTime For SJF: Dim finishTime as Integer finishTime = Math.Max(previousFinishTime, arrivalTime) + serviceTime
Calculating Finish Time of FCFS & SJF Scheduling Algorithm VB.Net System
Need help for First Come First Serve (FCFS) and Shortest Job First (SJF) Algorithm System on getting finish time for both algorithms. Language: VB.Net System GIU Need help for getting the value of finish time for both algorithms.
[ "For calculating the finish time of the First Come First Serve (FCFS) scheduling algorithm, the following formula can be used:\nFinish Time = Arrival Time + Service Time\n\nFor calculating the finish time of the Shortest Job First (SJF) scheduling algorithm, the following formula can be used:\nFinish Time = Maximum(Previous Finish Time, Arrival Time) + Service Time\n\nIn Visual Basic .NET, the above formulas can be implemented using the following code:\nFor FCFS:\nDim finishTime as Integer\nfinishTime = arrivalTime + serviceTime\n\nFor SJF:\nDim finishTime as Integer\nfinishTime = Math.Max(previousFinishTime, arrivalTime) + serviceTime\n\n" ]
[ 0 ]
[]
[]
[ "algorithm", "scheduling", "vb.net" ]
stackoverflow_0074665860_algorithm_scheduling_vb.net.txt
Q: React dynamic variables I have the following code in React: const TABS = [ { value: "Names", label: "Names", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Logs", label: "Logs", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Groups", label: "Groups", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Subscriptions", label: "Subscriptions", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, ] I have tried to make the code dynamic, as the following: const values = ["Names","Logs","Groups","Subscriptions"]; const labels = ["Names","Logs","Groups","Subscriptions"]; const TABS = [ { value: {values}, label: {labels}, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }] Am I right? A: Use: const values = ["Names", "Logs", "Groups", "Subscriptions"]; const TABS = values.map((e, i) => { return { value: e, label: e, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, } } ) This would map on each element on your values array and inject new object on the Tabs array for each tab. A: If you have the same label and value array then you can do this with a single array as: const labels = ["Names", "Logs", "Groups", "Subscriptions"]; const TABS = labels.map(label => ({ value: label, label, onclick: (obj) => { tabOnClick(label); }, selected: mainTabSelected, })) A: I have tried to make the code dynamic, as the following: ... Am I right? Not quite, you've confused JSX expressions and JavaScript property shorthand notation, because they both use the form {___}. But that's only a JSX expression when you're in a JSX element (for instance: <div>{"this is a JSX expression"}</div>). Where you're using it, you're just in a JavaScript object literal. So what you have creates an array with a single element in it, a single object that has: a value property which is an object with a values property referring to your values array a label property which is an object with a labels property referring to your labels array ...and the onclick and selected properties In other words, your code produced something that looked like this: // The structure your original code produced const TABS = [ { value: { values: ["Names", "Logs", "Groups", "Subscriptions"] }, label: { labels: ["Names", "Logs", "Groups", "Subscriptions"] }, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, ]; Instead, if I'm understanding you correctly, you want one of two things: An array of objects, where each object takes its value and label from an entry in those arrays. (But in a comment you've said the value and label should be the same, which is confusing — why have separate arrays? But I'll discuss that below.) To use those arrays to render tabs in a React component. If you're rendering tabs in a React component, there's no need for an intermediate array of tab information like TABS. But first I'll address creating TABS, then I'll address using the array(s) in a React component to render tabs. Creating the TABS array (if needed) You could use a simple loop: // Note: Assumes `values` and `labels` are the same length const TABS = []; for (let n = 0; n < values.length; ++n) { const value = values[n]; const label = labels[n]; TABS.push({ value, label, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected // <== Not sure what this is }); } But a call to map would be a bit more concise: // Note: Assumes `values` and `labels` are the same length const TABS = values.map((value, index) => ({ value, label: labels[index], onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected // <== Not sure what this is })); In both cases, if you want value and label to be the same as you mentioned here, just get rid of your labels array and use value for label. For instance, with map: const TABS = values.map((value) => ({ value, label: value, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected // <== Not sure what this is })); And in all of those cases, there's no need for the obj parameter and obj.value, you could just use value directly, since the function closes over the value for each iteration: onclick: () => { tabOnClick(value); }, Using the array(s) to render in React You've edited your question to mention React, though. If you want to use the array(s) to render elements in a React component, there's no need for the TABS array at all. Just use the array(s) directly. To do that, you'd probably want to create a Tab component to handle rendering a single tab. Here's an example: const Tab = ({ value, selected, onSelected }) => { return ( <div className={`tab ${selected ? "selected" : ""}`} onClick={() => onSelected(value)}> <span className="marker">{selected ? "➔" : ""}</span> {value} </div> ); }; The Tab component expects its value, a flag for whether it's selected, and a function to call if it's clicked (to select it). (The marker could be supplied by CSS if you prefer.) Your component using it might look like this; const Example = () => { const [mainTabSelected, setMainTabSelected] = useState(values[0]); const tabOnClick = (value) => { console.log(`Tab clicked: ${value}`); setMainTabSelected(value); }; return ( <div> {values.map((value) => ( <Tab key={value} value={value} selected={value === mainTabSelected} onSelected={tabOnClick} /> ))} </div> ); }; Live example: const { useState } = React; const values = ["Names", "Logs", "Groups", "Subscriptions"]; const Tab = ({ value, selected, onSelected }) => { return ( <div className={`tab ${selected ? "selected" : ""}`} onClick={() => onSelected(value)}> <span className="marker">{selected ? "➔" : ""}</span> {value} </div> ); }; const Example = () => { const [mainTabSelected, setMainTabSelected] = useState(values[0]); const tabOnClick = (value) => { console.log(`Tab clicked: ${value}`); setMainTabSelected(value); }; return ( <div> {values.map((value) => ( <Tab key={value} value={value} selected={value === mainTabSelected} onSelected={tabOnClick} /> ))} </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Example />); body { font-family: sans-serif; } .tab { border: 1px solid #222; background-color: #eee; margin-bottom: 4px; padding: 4px; cursor: pointer; } .selected { font-weight: bold; } .tab .marker { display: inline-block; width: 1rem; } <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script> In those examples, I've used value as the value and label of the tab, because (again) of your comment. But let's suppose you wanted to have separate values and labels. You wouldn't want to have two separate arrays for it, parallel arrays are problematic (it's easy to add something to one but not the other). Instead, you'd want an array of objects with value and label (or you might even make label optional, note "Subscriptions" below): const tabInfo = [ { value: "Names", label: "The Names" }, { value: "Logs", label: "Some Logs" }, { value: "Groups", label: "Groups Of Stuff" }, { value: "Subscriptions" }, ]; Then your Tab component would accept an optional label prop, which it could default to value: const Tab = ({ value, label = value, selected, onSelected }) => { // −−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^ return ( <div className={`tab ${selected ? "selected" : ""}`} onClick={() => onSelected(value)}> <span className="marker">{selected ? "➔" : ""}</span> {label /* <−−−−−−−−−−−−−−−−−−−−−−− */} </div> ); }; The component using it would map through tabInfo: {tabInfo.map(({value, label}) => ( <Tab key={value} value={value} label={label} selected={value === mainTabSelected} onSelected={tabOnClick} /> ))} Live example: const { useState } = React; const tabInfo = [ { value: "Names", label: "The Names" }, { value: "Logs", label: "Some Logs" }, { value: "Groups", label: "Groups Of Stuff" }, { value: "Subscriptions" }, ]; const Tab = ({ value, label = value, selected, onSelected }) => { return ( <div className={`tab ${selected ? "selected" : ""}`} onClick={() => onSelected(value)}> <span className="marker">{selected ? "➔" : ""}</span> {label} </div> ); }; const Example = () => { const [mainTabSelected, setMainTabSelected] = useState(tabInfo[0].value); const tabOnClick = (value) => { console.log(`Tab clicked: ${value}`); setMainTabSelected(value); }; return ( <div> {tabInfo.map(({value, label}) => ( <Tab key={value} value={value} label={label} selected={value === mainTabSelected} onSelected={tabOnClick} /> ))} </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<Example />); body { font-family: sans-serif; } .tab { border: 1px solid #222; background-color: #eee; color: #444; margin-bottom: 4px; padding: 4px; cursor: pointer; } .selected { color: black; } .tab .marker { display: inline-block; width: 1rem; } <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
React dynamic variables
I have the following code in React: const TABS = [ { value: "Names", label: "Names", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Logs", label: "Logs", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Groups", label: "Groups", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, { value: "Subscriptions", label: "Subscriptions", onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }, ] I have tried to make the code dynamic, as the following: const values = ["Names","Logs","Groups","Subscriptions"]; const labels = ["Names","Logs","Groups","Subscriptions"]; const TABS = [ { value: {values}, label: {labels}, onclick: (obj) => { tabOnClick(obj.value); }, selected: mainTabSelected, }] Am I right?
[ "Use:\nconst values = [\"Names\", \"Logs\", \"Groups\", \"Subscriptions\"];\n\nconst TABS = values.map((e, i) =>\n {\n return {\n value: e,\n label: e,\n onclick: (obj) => {\n tabOnClick(obj.value);\n },\n selected: mainTabSelected,\n }\n }\n)\n\nThis would map on each element on your values array and inject new object on the Tabs array for each tab.\n", "If you have the same label and value array then you can do this with a single array as:\nconst labels = [\"Names\", \"Logs\", \"Groups\", \"Subscriptions\"];\nconst TABS = labels.map(label => ({\n value: label,\n label,\n onclick: (obj) => {\n tabOnClick(label);\n },\n selected: mainTabSelected,\n}))\n\n", "\nI have tried to make the code dynamic, as the following:\n...\nAm I right?\n\nNot quite, you've confused JSX expressions and JavaScript property shorthand notation, because they both use the form {___}. But that's only a JSX expression when you're in a JSX element (for instance: <div>{\"this is a JSX expression\"}</div>). Where you're using it, you're just in a JavaScript object literal. So what you have creates an array with a single element in it, a single object that has:\n\na value property which is an object with a values property referring to your values array\na label property which is an object with a labels property referring to your labels array\n...and the onclick and selected properties\n\nIn other words, your code produced something that looked like this:\n// The structure your original code produced\nconst TABS = [\n {\n value: { values: [\"Names\", \"Logs\", \"Groups\", \"Subscriptions\"] },\n label: { labels: [\"Names\", \"Logs\", \"Groups\", \"Subscriptions\"] },\n onclick: (obj) => {\n tabOnClick(obj.value);\n },\n selected: mainTabSelected,\n },\n];\n\nInstead, if I'm understanding you correctly, you want one of two things:\n\nAn array of objects, where each object takes its value and label from an entry in those arrays. (But in a comment you've said the value and label should be the same, which is confusing — why have separate arrays? But I'll discuss that below.)\n\nTo use those arrays to render tabs in a React component.\n\n\nIf you're rendering tabs in a React component, there's no need for an intermediate array of tab information like TABS. But first I'll address creating TABS, then I'll address using the array(s) in a React component to render tabs.\nCreating the TABS array (if needed)\nYou could use a simple loop:\n// Note: Assumes `values` and `labels` are the same length\nconst TABS = [];\nfor (let n = 0; n < values.length; ++n) {\n const value = values[n];\n const label = labels[n];\n TABS.push({\n value,\n label,\n onclick: (obj) => {\n tabOnClick(obj.value);\n },\n selected: mainTabSelected // <== Not sure what this is\n });\n}\n\nBut a call to map would be a bit more concise:\n// Note: Assumes `values` and `labels` are the same length\nconst TABS = values.map((value, index) => ({\n value,\n label: labels[index],\n onclick: (obj) => {\n tabOnClick(obj.value);\n },\n selected: mainTabSelected // <== Not sure what this is\n}));\n\nIn both cases, if you want value and label to be the same as you mentioned here, just get rid of your labels array and use value for label. For instance, with map:\nconst TABS = values.map((value) => ({\n value,\n label: value,\n onclick: (obj) => {\n tabOnClick(obj.value);\n },\n selected: mainTabSelected // <== Not sure what this is\n}));\n\nAnd in all of those cases, there's no need for the obj parameter and obj.value, you could just use value directly, since the function closes over the value for each iteration:\n onclick: () => {\n tabOnClick(value);\n },\n\nUsing the array(s) to render in React\nYou've edited your question to mention React, though. If you want to use the array(s) to render elements in a React component, there's no need for the TABS array at all. Just use the array(s) directly.\nTo do that, you'd probably want to create a Tab component to handle rendering a single tab. Here's an example:\nconst Tab = ({ value, selected, onSelected }) => {\n return (\n <div className={`tab ${selected ? \"selected\" : \"\"}`} onClick={() => onSelected(value)}>\n <span className=\"marker\">{selected ? \"➔\" : \"\"}</span>\n {value}\n </div>\n );\n};\n\nThe Tab component expects its value, a flag for whether it's selected, and a function to call if it's clicked (to select it). (The marker could be supplied by CSS if you prefer.)\nYour component using it might look like this;\nconst Example = () => {\n const [mainTabSelected, setMainTabSelected] = useState(values[0]);\n const tabOnClick = (value) => {\n console.log(`Tab clicked: ${value}`);\n setMainTabSelected(value);\n };\n return (\n <div>\n {values.map((value) => (\n <Tab\n key={value}\n value={value}\n selected={value === mainTabSelected}\n onSelected={tabOnClick}\n />\n ))}\n </div>\n );\n};\n\nLive example:\n\n\nconst { useState } = React;\n\nconst values = [\"Names\", \"Logs\", \"Groups\", \"Subscriptions\"];\n\nconst Tab = ({ value, selected, onSelected }) => {\n return (\n <div className={`tab ${selected ? \"selected\" : \"\"}`} onClick={() => onSelected(value)}>\n <span className=\"marker\">{selected ? \"➔\" : \"\"}</span>\n {value}\n </div>\n );\n};\nconst Example = () => {\n const [mainTabSelected, setMainTabSelected] = useState(values[0]);\n const tabOnClick = (value) => {\n console.log(`Tab clicked: ${value}`);\n setMainTabSelected(value);\n };\n return (\n <div>\n {values.map((value) => (\n <Tab\n key={value}\n value={value}\n selected={value === mainTabSelected}\n onSelected={tabOnClick}\n />\n ))}\n </div>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById(\"root\"));\nroot.render(<Example />);\nbody {\n font-family: sans-serif;\n}\n.tab {\n border: 1px solid #222;\n background-color: #eee;\n margin-bottom: 4px;\n padding: 4px;\n cursor: pointer;\n}\n.selected {\n font-weight: bold;\n}\n.tab .marker {\n display: inline-block;\n width: 1rem;\n}\n<div id=\"root\"></div>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js\"></script>\n\n\n\nIn those examples, I've used value as the value and label of the tab, because (again) of your comment. But let's suppose you wanted to have separate values and labels. You wouldn't want to have two separate arrays for it, parallel arrays are problematic (it's easy to add something to one but not the other). Instead, you'd want an array of objects with value and label (or you might even make label optional, note \"Subscriptions\" below):\nconst tabInfo = [\n { value: \"Names\", label: \"The Names\" },\n { value: \"Logs\", label: \"Some Logs\" },\n { value: \"Groups\", label: \"Groups Of Stuff\" },\n { value: \"Subscriptions\" },\n];\n\nThen your Tab component would accept an optional label prop, which it could default to value:\nconst Tab = ({ value, label = value, selected, onSelected }) => {\n// −−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^\n return (\n <div className={`tab ${selected ? \"selected\" : \"\"}`} onClick={() => onSelected(value)}>\n <span className=\"marker\">{selected ? \"➔\" : \"\"}</span>\n {label /* <−−−−−−−−−−−−−−−−−−−−−−− */}\n </div>\n );\n};\n\nThe component using it would map through tabInfo:\n {tabInfo.map(({value, label}) => (\n <Tab\n key={value}\n value={value}\n label={label}\n selected={value === mainTabSelected}\n onSelected={tabOnClick}\n />\n ))}\n\nLive example:\n\n\nconst { useState } = React;\n\nconst tabInfo = [\n { value: \"Names\", label: \"The Names\" },\n { value: \"Logs\", label: \"Some Logs\" },\n { value: \"Groups\", label: \"Groups Of Stuff\" },\n { value: \"Subscriptions\" },\n];\n\nconst Tab = ({ value, label = value, selected, onSelected }) => {\n return (\n <div className={`tab ${selected ? \"selected\" : \"\"}`} onClick={() => onSelected(value)}>\n <span className=\"marker\">{selected ? \"➔\" : \"\"}</span>\n {label}\n </div>\n );\n};\nconst Example = () => {\n const [mainTabSelected, setMainTabSelected] = useState(tabInfo[0].value);\n const tabOnClick = (value) => {\n console.log(`Tab clicked: ${value}`);\n setMainTabSelected(value);\n };\n return (\n <div>\n {tabInfo.map(({value, label}) => (\n <Tab\n key={value}\n value={value}\n label={label}\n selected={value === mainTabSelected}\n onSelected={tabOnClick}\n />\n ))}\n </div>\n );\n};\n\nconst root = ReactDOM.createRoot(document.getElementById(\"root\"));\nroot.render(<Example />);\nbody {\n font-family: sans-serif;\n}\n.tab {\n border: 1px solid #222;\n background-color: #eee;\n color: #444;\n margin-bottom: 4px;\n padding: 4px;\n cursor: pointer;\n}\n.selected {\n color: black;\n}\n.tab .marker {\n display: inline-block;\n width: 1rem;\n}\n<div id=\"root\"></div>\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js\"></script>\n\n\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "javascript", "reactjs" ]
stackoverflow_0074653446_javascript_reactjs.txt
Q: Django url change language code I am trying to change the language of the website when users click a button in Django. I have a base project and the urls are: urlpatterns += i18n_patterns( # Ecommerce is the app where I want to change the language url(r'^', include("ecommerce.urls")), ) The url inside Ecommerce.urls is: urlpatterns = [ url(r'^testing/$', views.test, name='url_testing'), ... other urls ] When I visit the url above, I first go to: http://localhost/en/testing/. I want to set a link <a href="{% url 'url_testing' %}">Change Language</a> so that when users click it, it will change language to http://localhost/zh-hans/testing/. How do I do this in my template? EDIT I can now change the language using the following code but the problem is that it only works once: <form id="languageForm" action="/i18n/setlang/" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{% url 'url_testing' %}" /> <input id="newLanguageInput" type="hidden" name="language"/> </form> And my links are: <li><a onclick="changeLanguage('zh-hans')">简体</a></li> <li><a onclick="changeLanguage('zh-hant')">繁體</a></li> The function changeLanguage is defined like: function changeLanguage(newLanguage) { $('input[name="newLanguageInput"]').val(newLanguage); $('#languageForm').submit(); } The code works when I first click any of the 2 links, and I will be redirected to the url http://localhost/zh-hans/testing/ or http://localhost/zh-hant/testing/. The problem is after I change the language once, it no longer changes. Is there something wrong with my submit? A: Actually it's not going to be a simple <a> link but a <form>. Have a read on how to set_language redirect view. This form will be responsible for changing languages. It's easy as a pie. Make sure you have set some LANGUAGES first. A: You can change the language of the website when users click a link (no url translation, no post) like this: navigation.html (with bootstrap4 and font awesome) <li class="nav-item dropdown"> {% get_current_language as LANGUAGE_CODE %} <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown">{{ LANGUAGE_CODE }}</a> <div class="dropdown-menu dropdown-menu-right"> {% get_available_languages as languages %} {% for lang_code, lang_name in languages %} <a href="{% url 'main:activate_language' lang_code %}" class="dropdown-item"> {% if lang_code == LANGUAGE_CODE %} <i class="fas fa-check-circle"></i>&nbsp;&nbsp; {% else %} <i class="far fa-circle"></i>&nbsp;&nbsp; {% endif %} {{ lang_name }} ({{ lang_code }}) </a> {% endfor %} </div> </li> views.py from django.shortcuts import redirect from django.utils import translation from django.views.generic.base import View class ActivateLanguageView(View): language_code = '' redirect_to = '' def get(self, request, *args, **kwargs): self.redirect_to = request.META.get('HTTP_REFERER') self.language_code = kwargs.get('language_code') translation.activate(self.language_code) request.session[translation.LANGUAGE_SESSION_KEY] = self.language_code return redirect(self.redirect_to) urls.py from django.urls import path from .views import ActivateLanguageView app_name = 'main' urlpatterns = [ path('language/activate/<language_code>/', ActivateLanguageView.as_view(), name='activate_language'), ] It's work for me. A: New snippets compatible with new API (Boostrap 5 and Django >= 4.0) updated from the excellent @Boris Đurkan answer. Django has dropped the translation.LANGUAGE_SESSION_KEY support. So basically we need to make this setup using the session cookie. class ActivateLanguageView(View): def get(self, request, lang, **kwargs): url = request.META.get('HTTP_REFERER', '/') translation.activate(lang) response = HttpResponseRedirect(url) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang) return response Boostrap has changed its jQuery binding for dropdown: <li class="nav-item dropdown"> {% get_current_language as LANGUAGE_CODE %} <a class="nav-link dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-bs-toggle="dropdown" aria-expanded="false"> <strong>{{ LANGUAGE_CODE }}</strong> </a> <div class="dropdown-menu dropdown-menu-right"> {% get_available_languages as languages %} {% for lang_code, lang_name in languages %} <a href="{% url 'activate_language' lang_code %}" class="dropdown-item"> {% if lang_code == LANGUAGE_CODE %} <i class="bi bi-check-circle"></i>&nbsp;&nbsp; {% else %} <i class="bi bi-circle"></i>&nbsp;&nbsp; {% endif %} {{ lang_name }} ({{ lang_code }}) </a> {% endfor %} </div> </li> Other parts of code remains basically the same.
Django url change language code
I am trying to change the language of the website when users click a button in Django. I have a base project and the urls are: urlpatterns += i18n_patterns( # Ecommerce is the app where I want to change the language url(r'^', include("ecommerce.urls")), ) The url inside Ecommerce.urls is: urlpatterns = [ url(r'^testing/$', views.test, name='url_testing'), ... other urls ] When I visit the url above, I first go to: http://localhost/en/testing/. I want to set a link <a href="{% url 'url_testing' %}">Change Language</a> so that when users click it, it will change language to http://localhost/zh-hans/testing/. How do I do this in my template? EDIT I can now change the language using the following code but the problem is that it only works once: <form id="languageForm" action="/i18n/setlang/" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{% url 'url_testing' %}" /> <input id="newLanguageInput" type="hidden" name="language"/> </form> And my links are: <li><a onclick="changeLanguage('zh-hans')">简体</a></li> <li><a onclick="changeLanguage('zh-hant')">繁體</a></li> The function changeLanguage is defined like: function changeLanguage(newLanguage) { $('input[name="newLanguageInput"]').val(newLanguage); $('#languageForm').submit(); } The code works when I first click any of the 2 links, and I will be redirected to the url http://localhost/zh-hans/testing/ or http://localhost/zh-hant/testing/. The problem is after I change the language once, it no longer changes. Is there something wrong with my submit?
[ "Actually it's not going to be a simple <a> link but a <form>.\nHave a read on how to set_language redirect view. This form will be responsible for changing languages. It's easy as a pie.\nMake sure you have set some LANGUAGES first.\n", "You can change the language of the website when users click a link (no url translation, no post) like this:\nnavigation.html (with bootstrap4 and font awesome)\n<li class=\"nav-item dropdown\">\n {% get_current_language as LANGUAGE_CODE %}\n <a class=\"nav-link dropdown-toggle\" href=\"#\" data-toggle=\"dropdown\">{{ LANGUAGE_CODE }}</a>\n <div class=\"dropdown-menu dropdown-menu-right\">\n\n {% get_available_languages as languages %}\n {% for lang_code, lang_name in languages %}\n\n <a href=\"{% url 'main:activate_language' lang_code %}\" class=\"dropdown-item\">\n {% if lang_code == LANGUAGE_CODE %}\n <i class=\"fas fa-check-circle\"></i>&nbsp;&nbsp;\n {% else %}\n <i class=\"far fa-circle\"></i>&nbsp;&nbsp;\n {% endif %}\n {{ lang_name }} ({{ lang_code }})\n </a>\n\n {% endfor %}\n </div>\n</li>\n\nviews.py\nfrom django.shortcuts import redirect\nfrom django.utils import translation\nfrom django.views.generic.base import View\n\nclass ActivateLanguageView(View):\n language_code = ''\n redirect_to = ''\n\n def get(self, request, *args, **kwargs):\n self.redirect_to = request.META.get('HTTP_REFERER')\n self.language_code = kwargs.get('language_code')\n translation.activate(self.language_code)\n request.session[translation.LANGUAGE_SESSION_KEY] = self.language_code\n return redirect(self.redirect_to)\n\nurls.py\nfrom django.urls import path\nfrom .views import ActivateLanguageView\n\napp_name = 'main'\nurlpatterns = [\n path('language/activate/<language_code>/', ActivateLanguageView.as_view(), name='activate_language'),\n]\n\nIt's work for me.\n", "New snippets compatible with new API (Boostrap 5 and Django >= 4.0) updated from the excellent @Boris Đurkan answer.\nDjango has dropped the translation.LANGUAGE_SESSION_KEY support.\nSo basically we need to make this setup using the session cookie.\nclass ActivateLanguageView(View):\n\n def get(self, request, lang, **kwargs):\n url = request.META.get('HTTP_REFERER', '/')\n translation.activate(lang)\n response = HttpResponseRedirect(url)\n response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang)\n return response\n\nBoostrap has changed its jQuery binding for dropdown:\n<li class=\"nav-item dropdown\">\n {% get_current_language as LANGUAGE_CODE %}\n <a class=\"nav-link dropdown-toggle\" href=\"#\" role=\"button\" id=\"dropdownMenuLink\" data-bs-toggle=\"dropdown\" aria-expanded=\"false\">\n <strong>{{ LANGUAGE_CODE }}</strong>\n </a>\n <div class=\"dropdown-menu dropdown-menu-right\">\n\n {% get_available_languages as languages %}\n {% for lang_code, lang_name in languages %}\n\n <a href=\"{% url 'activate_language' lang_code %}\" class=\"dropdown-item\">\n {% if lang_code == LANGUAGE_CODE %}\n <i class=\"bi bi-check-circle\"></i>&nbsp;&nbsp;\n {% else %}\n <i class=\"bi bi-circle\"></i>&nbsp;&nbsp;\n {% endif %}\n {{ lang_name }} ({{ lang_code }})\n </a>\n\n {% endfor %}\n </div>\n</li>\n\nOther parts of code remains basically the same.\n" ]
[ 4, 4, 0 ]
[]
[]
[ "django", "django_i18n", "python" ]
stackoverflow_0042745198_django_django_i18n_python.txt
Q: Azure App Service Getting error while deploying REACT JS application Getting error while deploying to azure app services from the editor. 4:48:55 pm ppdedsrftwu2-appservice1: Starting deployment... 4:48:56 pm ppdedsrftwu2-appservice1: Creating zip package... 4:49:00 pm ppdedsrftwu2-appservice1: Zip package size: 1.09 MB 4:49:04 pm ppdedsrftwu2-appservice1: Fetching changes. 4:49:06 pm ppdedsrftwu2-appservice1: Updating submodules. 4:49:06 pm ppdedsrftwu2-appservice1: Preparing deployment for commit id '2a73dbd291'. 4:49:06 pm ppdedsrftwu2-appservice1: Repository path is /tmp/zipdeploy/extracted 4:49:06 pm ppdedsrftwu2-appservice1: Running oryx build... 4:49:06 pm ppdedsrftwu2-appservice1: Command: oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform nodejs --platform-version 10 -i /tmp/8d856447f426192 -p compress_node_modules=tar-gz --log-file /tmp/build-debug.log 4:49:07 pm ppdedsrftwu2-appservice1: Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx 4:49:07 pm ppdedsrftwu2-appservice1: You can report issues at https://github.com/Microsoft/Oryx/issues 4:49:07 pm ppdedsrftwu2-appservice1: Oryx Version: 0.2.20200805.1, Commit: e7c39ede513143e9d80fd553f106f04268d770d4, ReleaseTagName: 20200805.1 4:49:07 pm ppdedsrftwu2-appservice1: Build Operation ID: |lvjLop9mFGA=.426fac1c_ 4:49:07 pm ppdedsrftwu2-appservice1: Repository Commit : 2a73dbd2834715ba1fee5082d13b60 4:49:07 pm ppdedsrftwu2-appservice1: Detecting platforms... 4:49:07 pm ppdedsrftwu2-appservice1: Could not detect any platform in the source directory. 4:49:07 pm ppdedsrftwu2-appservice1: Error: Couldn't detect a version for the platform 'nodejs' in the repo. 4:49:09 pm ppdedsrftwu2-appservice1: Error: Couldn't detect a version for the platform 'nodejs' in the repo.\n/opt/Kudu/Scripts/starter.sh oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform nodejs --platform-version 10 -i /tmp/8d856447f4292 -p compress_node_modules=tar-gz --log-file /tmp/build-debug.log 4:49:20 pm ppdedsrftwu2-appservice1: Deployment failed. Have defined all the necessary settings in the portal. SCM_DO_BUILD_DURING_DEPLOYMENT=true WEBSITE_NODE_DEFAULT_VERSION=12 WEBSITES_PORT=3000 WEBSITE_HTTPLOGGING_RETENTION_DAYS=7 Tried with node version 10 also but still the same error. A: Connected with MS Support team they suggested to make the SCM_DO_BUILD_DURING_DEPLOYMENT= FALSE. After making this as false i am able to deploy the app. But the strange thing is with this option enabled i was doing earlier deployments and it was working. A: In my case, I had the node app in a subdirectory, and this was causing this error in GitHub Actions job. Explicitly setting the working directory in the yml file fixed this. i.e - name: npm install, build, and test working-directory: ./subdirectory run: | npm install npm run build --if-present npm run test --if-present A: If you're doing a deployment from i.e., Visual Studio Code and deploying the dist/... folder then you wouldn't want to try and actually do a build hence setting SCM_DO_BUILD_DURING_DEPLOYMENT=false. There is not a running node js server to actually do a build on the agent pool deployment pipeline. Azure devops or Jenkins per se would actually have an agent pool to do a "proper (air quotes)" build. Yes, you're code is running on node hence the setting you choose when setting up the web app. So those 2 things are not the same. Rather, DevOps. I didn't find it in the documentation so appreciate the answer and responses here; but, I just wanted to give more context to the answer. It's an upgrade to visual studio web apps deployment to potentially utilize other build methods like described in an answer here about github actions. A: I also struggled with this issue. Two things helped me : When deploying from the Azure App service extension : Understanding that your root NodeJS application folder must be the root folder that is open in your explorer in vscode. If your NodeJS application is in a subfolder, azure wont be able to build ( or identify your node platform : hence the error message that you are seeing ) the scripts in your root folder. By far the easiest way to resolve this is to open vscode in the root folder ( the folder where your package.json file is located. Also : When you click the deploy button on your vscode Azure App service extension : it might allow you to specify the folder to be deployed. You can try to add the Application setting : SCM_DO_BUILD_DURING_DEPLOYMENT with the value of FALSE and Deployment slot setting of unchecked. This is on the azure portal under configuration - application settings - add + Remember to click that save button after adding new application settings ..... because azure ... lol. But i think this is mostly way to delay your app building until the files are copied. Last thing : If you are deploying from Github : Make sure that your nodeJS app is also in the root folder of the Github repo. If it is not you will need to update the workflow file to change the folder to the subfolder. You just need to add cd yourfoldername above the line where it says npm install and commit the workflow change to the repo. Hope this helps.
Azure App Service Getting error while deploying REACT JS application
Getting error while deploying to azure app services from the editor. 4:48:55 pm ppdedsrftwu2-appservice1: Starting deployment... 4:48:56 pm ppdedsrftwu2-appservice1: Creating zip package... 4:49:00 pm ppdedsrftwu2-appservice1: Zip package size: 1.09 MB 4:49:04 pm ppdedsrftwu2-appservice1: Fetching changes. 4:49:06 pm ppdedsrftwu2-appservice1: Updating submodules. 4:49:06 pm ppdedsrftwu2-appservice1: Preparing deployment for commit id '2a73dbd291'. 4:49:06 pm ppdedsrftwu2-appservice1: Repository path is /tmp/zipdeploy/extracted 4:49:06 pm ppdedsrftwu2-appservice1: Running oryx build... 4:49:06 pm ppdedsrftwu2-appservice1: Command: oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform nodejs --platform-version 10 -i /tmp/8d856447f426192 -p compress_node_modules=tar-gz --log-file /tmp/build-debug.log 4:49:07 pm ppdedsrftwu2-appservice1: Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx 4:49:07 pm ppdedsrftwu2-appservice1: You can report issues at https://github.com/Microsoft/Oryx/issues 4:49:07 pm ppdedsrftwu2-appservice1: Oryx Version: 0.2.20200805.1, Commit: e7c39ede513143e9d80fd553f106f04268d770d4, ReleaseTagName: 20200805.1 4:49:07 pm ppdedsrftwu2-appservice1: Build Operation ID: |lvjLop9mFGA=.426fac1c_ 4:49:07 pm ppdedsrftwu2-appservice1: Repository Commit : 2a73dbd2834715ba1fee5082d13b60 4:49:07 pm ppdedsrftwu2-appservice1: Detecting platforms... 4:49:07 pm ppdedsrftwu2-appservice1: Could not detect any platform in the source directory. 4:49:07 pm ppdedsrftwu2-appservice1: Error: Couldn't detect a version for the platform 'nodejs' in the repo. 4:49:09 pm ppdedsrftwu2-appservice1: Error: Couldn't detect a version for the platform 'nodejs' in the repo.\n/opt/Kudu/Scripts/starter.sh oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform nodejs --platform-version 10 -i /tmp/8d856447f4292 -p compress_node_modules=tar-gz --log-file /tmp/build-debug.log 4:49:20 pm ppdedsrftwu2-appservice1: Deployment failed. Have defined all the necessary settings in the portal. SCM_DO_BUILD_DURING_DEPLOYMENT=true WEBSITE_NODE_DEFAULT_VERSION=12 WEBSITES_PORT=3000 WEBSITE_HTTPLOGGING_RETENTION_DAYS=7 Tried with node version 10 also but still the same error.
[ "Connected with MS Support team they suggested to make the SCM_DO_BUILD_DURING_DEPLOYMENT= FALSE. After making this as false i am able to deploy the app. But the strange thing is with this option enabled i was doing earlier deployments and it was working.\n", "In my case, I had the node app in a subdirectory, and this was causing this error in GitHub Actions job. Explicitly setting the working directory in the yml file fixed this. i.e\n- name: npm install, build, and test\n working-directory: ./subdirectory\n run: |\n npm install\n npm run build --if-present\n npm run test --if-present\n\n", "If you're doing a deployment from i.e., Visual Studio Code and deploying the dist/... folder then you wouldn't want to try and actually do a build hence setting SCM_DO_BUILD_DURING_DEPLOYMENT=false.\nThere is not a running node js server to actually do a build on the agent pool deployment pipeline. Azure devops or Jenkins per se would actually have an agent pool to do a \"proper (air quotes)\" build. Yes, you're code is running on node hence the setting you choose when setting up the web app. So those 2 things are not the same. Rather, DevOps.\nI didn't find it in the documentation so appreciate the answer and responses here; but, I just wanted to give more context to the answer.\nIt's an upgrade to visual studio web apps deployment to potentially utilize other build methods like described in an answer here about github actions.\n", "I also struggled with this issue.\nTwo things helped me :\nWhen deploying from the Azure App service extension :\n\nUnderstanding that your root NodeJS application folder must be the root folder that is open in your explorer in vscode.\n\nIf your NodeJS application is in a subfolder, azure wont be able to build ( or identify your node platform : hence the error message that you are seeing ) the scripts in your root folder.\nBy far the easiest way to resolve this is to open vscode in the root folder ( the folder where your package.json file is located.\n\nAlso : When you click the deploy button on your vscode Azure App service extension : it might allow you to specify the folder to be deployed.\n\n\n\nYou can try to add the Application setting : SCM_DO_BUILD_DURING_DEPLOYMENT with the value of FALSE and Deployment slot setting of unchecked.\n\nThis is on the azure portal under configuration - application settings - add +\nRemember to click that save button after adding new application settings ..... because azure ... lol.\nBut i think this is mostly way to delay your app building until the files are copied.\nLast thing : If you are deploying from Github : Make sure that your nodeJS app is also in the root folder of the Github repo. If it is not you will need to update the workflow file to change the folder to the subfolder.\nYou just need to add cd yourfoldername above the line where it says npm install and commit the workflow change to the repo.\nHope this helps.\n" ]
[ 20, 0, 0, 0 ]
[]
[]
[ "azure", "azure_appservice", "azure_web_app_service", "reactjs", "web_deployment" ]
stackoverflow_0063846235_azure_azure_appservice_azure_web_app_service_reactjs_web_deployment.txt
Q: Flutter image save get blurred in iOS I have created a sample app that saves a container as an image using flutter. This works totally fine with the android device and the saved image is of good quality. However, when I check this in the iPhone (emulator and physical device) the saved image is not in good quality. Below is the code that I have used to save the container as an image and I just pass the global key of my container that needs to save. import 'dart:math'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'dart:ui' as ui; import 'dart:io' as Io; import 'package:path_provider/path_provider.dart'; import 'package:gallery_saver/gallery_saver.dart'; class ImageExport { save(GlobalKey globalKey) async { Random random = new Random(); int randomNumber = random.nextInt(1000); RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject(); ui.Image image = await boundary.toImage(pixelRatio: 5.0); final directory = (await getApplicationDocumentsDirectory()).path; ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); Io.File imgFile = new Io.File('$directory/test$randomNumber.jpg'); imgFile.writeAsBytes(pngBytes); imgFile.writeAsBytesSync(pngBytes); GallerySaver.saveImage(imgFile.path, albumName: "test"); } } Could some please help me resolve this issue? A: I had the same issue but @Gihan's answer of saving it as a PNG instead of a JPG fixed the issue for me.
Flutter image save get blurred in iOS
I have created a sample app that saves a container as an image using flutter. This works totally fine with the android device and the saved image is of good quality. However, when I check this in the iPhone (emulator and physical device) the saved image is not in good quality. Below is the code that I have used to save the container as an image and I just pass the global key of my container that needs to save. import 'dart:math'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'dart:ui' as ui; import 'dart:io' as Io; import 'package:path_provider/path_provider.dart'; import 'package:gallery_saver/gallery_saver.dart'; class ImageExport { save(GlobalKey globalKey) async { Random random = new Random(); int randomNumber = random.nextInt(1000); RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject(); ui.Image image = await boundary.toImage(pixelRatio: 5.0); final directory = (await getApplicationDocumentsDirectory()).path; ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); Io.File imgFile = new Io.File('$directory/test$randomNumber.jpg'); imgFile.writeAsBytes(pngBytes); imgFile.writeAsBytesSync(pngBytes); GallerySaver.saveImage(imgFile.path, albumName: "test"); } } Could some please help me resolve this issue?
[ "I had the same issue but @Gihan's answer of saving it as a PNG instead of a JPG fixed the issue for me.\n" ]
[ 0 ]
[]
[]
[ "flutter", "flutter_image", "flutter_ios", "image" ]
stackoverflow_0064736727_flutter_flutter_image_flutter_ios_image.txt
Q: how to sum with case with oracle sql I m having data in columns as: item_id month_in amount 1 1 1500 1 1 1000 2 1 2500 3 1 2600 3 1 1000 4 1 2700 4 1 1000 1 2 1500 1 2 2000 2 2 1000 3 3 2500 3 3 2500 4 3 1000 4 3 2500 i want to have like this result item_id januari februari maret 1 2500 3500 0 2 2500 1000 0 3 3600 0 0 4 3700 0 3500 in oracle sql query how to solve this. please help me i have try this select item_id, (case month_in=1 then sum(amout) end )AS januari from table group by item_id, month_in order by item_id asc but not working as i expected A: Ideally there should be tables which contain all items and all months. Absent that, we can use the following calendar table pivot approach: SELECT i.item_id, SUM(CASE WHEN m.month_in = 1 THEN t.amount ELSE 0 END) AS januari, SUM(CASE WHEN m.month_in = 2 THEN t.amount ELSE 0 END) AS februari, SUM(CASE WHEN m.month_in = 3 THEN t.amount ELSE 0 END) AS maret FROM (SELECT DISTINCT item_id FROM yourTable) i CROSS JOIN (SELECT DISTINCT month_in FROM yourTable) m LEFT JOIN yourTable t ON t.item_id = i.item_id AND t.month_in = m.month_in GROUP BY i.item_id ORDER BY i.item_id;
how to sum with case with oracle sql
I m having data in columns as: item_id month_in amount 1 1 1500 1 1 1000 2 1 2500 3 1 2600 3 1 1000 4 1 2700 4 1 1000 1 2 1500 1 2 2000 2 2 1000 3 3 2500 3 3 2500 4 3 1000 4 3 2500 i want to have like this result item_id januari februari maret 1 2500 3500 0 2 2500 1000 0 3 3600 0 0 4 3700 0 3500 in oracle sql query how to solve this. please help me i have try this select item_id, (case month_in=1 then sum(amout) end )AS januari from table group by item_id, month_in order by item_id asc but not working as i expected
[ "Ideally there should be tables which contain all items and all months. Absent that, we can use the following calendar table pivot approach:\nSELECT\n i.item_id,\n SUM(CASE WHEN m.month_in = 1 THEN t.amount ELSE 0 END) AS januari,\n SUM(CASE WHEN m.month_in = 2 THEN t.amount ELSE 0 END) AS februari,\n SUM(CASE WHEN m.month_in = 3 THEN t.amount ELSE 0 END) AS maret\nFROM (SELECT DISTINCT item_id FROM yourTable) i\nCROSS JOIN (SELECT DISTINCT month_in FROM yourTable) m\nLEFT JOIN yourTable t\n ON t.item_id = i.item_id AND\n t.month_in = m.month_in\nGROUP BY\n i.item_id\nORDER BY\n i.item_id;\n\n" ]
[ 1 ]
[]
[]
[ "oracle11g", "sql" ]
stackoverflow_0074675026_oracle11g_sql.txt
Q: Elastic Cloud Integration using Spring Rest Template? How to connect Elastic search using Sprin Rest Template. I've tried elasticsearch rest client. I would like to know if there is a way to connect to ES cloud via Spring rest template? A: use the Spring RestTemplate to connect to Elasticsearch via its REST API. RestTemplate restTemplate = new RestTemplate(); String url = "https://my-elasticsearch-host:9200/my-index/my-type/_search"; // Create the search query Map<String, Object> searchQuery = new HashMap<>(); searchQuery.put("query", "my-query"); // Execute the search request ResponseEntity<String> response = restTemplate.postForEntity(url, searchQuery, String.class); // Process the response if (response.getStatusCode() == HttpStatus.OK) { String responseBody = response.getBody(); // ... }
Elastic Cloud Integration using Spring Rest Template?
How to connect Elastic search using Sprin Rest Template. I've tried elasticsearch rest client. I would like to know if there is a way to connect to ES cloud via Spring rest template?
[ "use the Spring RestTemplate to connect to Elasticsearch via its REST API.\nRestTemplate restTemplate = new RestTemplate();\nString url = \"https://my-elasticsearch-host:9200/my-index/my-type/_search\";\n\n// Create the search query\nMap<String, Object> searchQuery = new HashMap<>();\nsearchQuery.put(\"query\", \"my-query\");\n\n// Execute the search request\nResponseEntity<String> response = restTemplate.postForEntity(url, searchQuery, String.class);\n\n// Process the response\nif (response.getStatusCode() == HttpStatus.OK) {\n String responseBody = response.getBody();\n // ...\n}\n\n" ]
[ 0 ]
[]
[]
[ "elastic_cloud", "elasticsearch", "java", "spring_boot" ]
stackoverflow_0074675124_elastic_cloud_elasticsearch_java_spring_boot.txt
Q: How do I make a HashSet from the characters in a string? I'm just starting to learn Rust and I'm still working on understanding its approach. The particular thing I'm working on is trying to find out if two strings have any characters in common. In another language I might do this by creating two sets of the characters in the strings and performing an intersection on the sets. So far I'm having no luck in creating a HashSet from the characters in a string in Rust. I'm trying variations on this: let lines: Vec<&str> = text_from_file.lines().collect(); let set1 = HashSet::from(lines[0].chars()); With this variation I get the error "the trait bound std::collections::HashSet<_, _>: std::convert::From<&[u8]> is not satisfied". I don't understand Rust enough yet to know how to interpret this. How can I create a HashSet from the characters in a string? A: You want to use HashSet::from_iter() let lines: Vec<&str> = text_from_file.lines().collect(); let set1: HashSet<char> = HashSet::from_iter(lines[0].chars()); A: HashSet::from() requires a slice as parameter, but lines[0].chars() is a Chars object, which is an iterator. To create a HashSet from an iterator, you have two possibilities: let set1: HashSet<char> = lines[0].chars().collect(); let set1: HashSet<char> = HashSet::from_iter(lines[0].chars()); I prefer the first one, as it's much easier to read for me.
How do I make a HashSet from the characters in a string?
I'm just starting to learn Rust and I'm still working on understanding its approach. The particular thing I'm working on is trying to find out if two strings have any characters in common. In another language I might do this by creating two sets of the characters in the strings and performing an intersection on the sets. So far I'm having no luck in creating a HashSet from the characters in a string in Rust. I'm trying variations on this: let lines: Vec<&str> = text_from_file.lines().collect(); let set1 = HashSet::from(lines[0].chars()); With this variation I get the error "the trait bound std::collections::HashSet<_, _>: std::convert::From<&[u8]> is not satisfied". I don't understand Rust enough yet to know how to interpret this. How can I create a HashSet from the characters in a string?
[ "You want to use HashSet::from_iter()\nlet lines: Vec<&str> = text_from_file.lines().collect();\nlet set1: HashSet<char> = HashSet::from_iter(lines[0].chars());\n\n", "HashSet::from() requires a slice as parameter, but lines[0].chars() is a Chars object, which is an iterator.\nTo create a HashSet from an iterator, you have two possibilities:\nlet set1: HashSet<char> = lines[0].chars().collect();\n\nlet set1: HashSet<char> = HashSet::from_iter(lines[0].chars());\n\nI prefer the first one, as it's much easier to read for me.\n" ]
[ 1, 0 ]
[]
[]
[ "rust" ]
stackoverflow_0074672309_rust.txt
Q: listview cannot add or insert the item in more than one place foreach I'm trying to add an item to my listview but I've got this Exception: Cannot add or insert the item '0' in more than one place. The expected result is the added item but real result is this exception and I can't add an item to my listview. My code works of this way: First, I'm declaring the namespace and my class Takenshows.cs namespace MainLayer { public partial class Takenshows : Form { int c; int f; int d = 0; public List<Show> myShows; private ListViewColumnSorter lvwColumnSorter; Main p; so my constructor method works - I have really more than one constructor - public Takenshows() { InitializeComponent(); lvwColumnSorter = new ListViewColumnSorter(); this.listView1.ListViewItemSorter = lvwColumnSorter; myShows = new List<Show>(); } public Takenshows(IEnumerable<Show> shows) : this() { AddShows(shows); } The next ones methods can receive one show from Main.cs (When I take a show pressing on taken shows button) and fill the listview from Takenshows.cs internal void AddShow(Show item) => AddShows(new[] { item }); internal void AddShows(IEnumerable<Show> items) { var lvis = items.Select(x => new ListViewItem(new[] { x.OrdNum.ToString(), x.DTshow.ToString(), x.values.ToString(), x.practiseNumber.ToString() })); listView1.Items.AddRange(lvis.ToArray()); } this is the method for empty listview: internal void emptyShows() { listView1.Items.Clear(); } the method for receive shows from the listview: public List<Show> getShows(List<Show> items) { return items; } this is the Takenshows_Load private void Takenshows_Load(object sender, EventArgs e) { // set view mode to see columns listView1.View = View.Details; listView1.Columns.Add("Order Number", 115, HorizontalAlignment.Left); listView1.Columns.Add("Practise datetime", 140, HorizontalAlignment.Left); listView1.Columns.Add("values", 420, HorizontalAlignment.Left); listView1.Columns.Add("Practise number", 105, HorizontalAlignment.Left); foreach (ListViewItem item in listView1.Items) { int index = listView1.Items.IndexOf(item); item.Tag = index; item.Text = index.ToString(); item.SubItems.Add(listView1.Items[index].SubItems[0].Text); item.SubItems.Add(listView1.Items[index].SubItems[1].Text); item.SubItems.Add(listView1.Items[index].SubItems[2].Text); item.SubItems.Add(listView1.Items[index].SubItems[3].Text); listView1.Items.Add(item); //THIS LINE gets THE ISSUE cannot add the item '0' in more than one place } myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(lvi => (Show)lvi.Tag).ToList(); for (int j = 0; j < listView1.Items.Count; j++) { c = c + 1; listView1.Items[j].SubItems[0].Text = c.ToString(); } f = Int32.Parse(c.ToString()); var frm3 = Application.OpenForms.OfType<Principal>().First(); if (frm3 != null) { frm3.devCont(); frm3.devcontlist(f); frm3.devMed(myShows); } } This is the listview1_SelectedIndexChanged, on this method, the listview updates automatically. private void listView1_SelectedIndexChanged(object sender, EventArgs e) { listView1.BeginUpdate(); listView1.EndUpdate(); listView1.Invalidate(); listView1.Update(); } Inside Takenshows.cs class when I'm removing one element pressing on delete show button happens following: private void button1_Click(object sender, EventArgs e) { c = 0; if (listView1.SelectedItems != null) { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Selected) { DialogResult dr = MessageBox.Show("Are you sure you want to remove the selected item?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); switch (dr) { case DialogResult.Yes: listView1.Items[i].Remove(); i--; for (int j = 0; j < listView1.Items.Count; j++) { c = c + 1; listView1.Items[j].SubItems[0].Text = c.ToString(); } f = Int32.Parse(c.ToString()); myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(lvi => (Show)lvi.Tag).ToList(); var frm2 = Application.OpenForms.OfType<Principal>().First(); if (frm2 != null) { frm2.devCont(); frm2.devcontlist(f); frm2.devMed(myShows); } break; case DialogResult.No: break; } } } } } In this method, the listview sorts programatically by first column inside Takenshows.cs private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) { if (e.Column == 0) { if (lvwColumnSorter.SortColumn == 0) { { lvwColumnSorter.SortColumn = e.Column; lvwColumnSorter.Order = SortOrder.Ascending; } } } this.listView1.Sort(); } } } And finally, inside Main.cs this is the code of the take show button when I take a show: private void button2_Click(object sender, EventArgs e) { string values = textBox_F.Text + " " + textBox_PT.Text + " " + textBox_QT.Text + " " + textBox_ST.Text + " " + textBox_FPT.Text; c = c + 1; watchedShow = new Show { OrdNum = c + d, DTShow = DateTime.Now, Values = values, practiseNumber = GetPractiseNumberLN.getInstance().getPractiseNum() }; watchedShows.Add(watchedShow); var frm = Application.OpenForms.OfType<Takenshows>().FirstOrDefault(); if (frm == null) { frm = new Takenshows(watchedShows); frm.Show(); } else { frm.AddShow(watchedShow); frm.Activate(); } } This line inside Takenshows.cs on Takenshows_load generates the error: listView1.Items.Add(item); Also item is an iterator which it's inside foreach loop. I don't know how can I solve this issue. Is there any way that I can fix this issue? Probably list view doesn't update after adding or removing an element to listview. I tried to replacing foreach loop by for loop on Takenshows_Load: for (int i = 0; i < listView1.Items.Count; i++) { // int index = listView1.Items.IndexOf(i); ListViewItem item = new ListViewItem(); item.Tag = i; item.Text = i.ToString(); item.SubItems.Add(listView1.Items[i].SubItems[0].Text); item.SubItems.Add(listView1.Items[i].SubItems[1].Text); item.SubItems.Add(listView1.Items[i].SubItems[2].Text); item.SubItems.Add(listView1.Items[i].SubItems[3].Text); listView1.Items.Add(item); } But in evidence it happens nothing. How can I fix this issue? I really need fix this issue, but I don't know how to fix that.
listview cannot add or insert the item in more than one place foreach
I'm trying to add an item to my listview but I've got this Exception: Cannot add or insert the item '0' in more than one place. The expected result is the added item but real result is this exception and I can't add an item to my listview. My code works of this way: First, I'm declaring the namespace and my class Takenshows.cs namespace MainLayer { public partial class Takenshows : Form { int c; int f; int d = 0; public List<Show> myShows; private ListViewColumnSorter lvwColumnSorter; Main p; so my constructor method works - I have really more than one constructor - public Takenshows() { InitializeComponent(); lvwColumnSorter = new ListViewColumnSorter(); this.listView1.ListViewItemSorter = lvwColumnSorter; myShows = new List<Show>(); } public Takenshows(IEnumerable<Show> shows) : this() { AddShows(shows); } The next ones methods can receive one show from Main.cs (When I take a show pressing on taken shows button) and fill the listview from Takenshows.cs internal void AddShow(Show item) => AddShows(new[] { item }); internal void AddShows(IEnumerable<Show> items) { var lvis = items.Select(x => new ListViewItem(new[] { x.OrdNum.ToString(), x.DTshow.ToString(), x.values.ToString(), x.practiseNumber.ToString() })); listView1.Items.AddRange(lvis.ToArray()); } this is the method for empty listview: internal void emptyShows() { listView1.Items.Clear(); } the method for receive shows from the listview: public List<Show> getShows(List<Show> items) { return items; } this is the Takenshows_Load private void Takenshows_Load(object sender, EventArgs e) { // set view mode to see columns listView1.View = View.Details; listView1.Columns.Add("Order Number", 115, HorizontalAlignment.Left); listView1.Columns.Add("Practise datetime", 140, HorizontalAlignment.Left); listView1.Columns.Add("values", 420, HorizontalAlignment.Left); listView1.Columns.Add("Practise number", 105, HorizontalAlignment.Left); foreach (ListViewItem item in listView1.Items) { int index = listView1.Items.IndexOf(item); item.Tag = index; item.Text = index.ToString(); item.SubItems.Add(listView1.Items[index].SubItems[0].Text); item.SubItems.Add(listView1.Items[index].SubItems[1].Text); item.SubItems.Add(listView1.Items[index].SubItems[2].Text); item.SubItems.Add(listView1.Items[index].SubItems[3].Text); listView1.Items.Add(item); //THIS LINE gets THE ISSUE cannot add the item '0' in more than one place } myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(lvi => (Show)lvi.Tag).ToList(); for (int j = 0; j < listView1.Items.Count; j++) { c = c + 1; listView1.Items[j].SubItems[0].Text = c.ToString(); } f = Int32.Parse(c.ToString()); var frm3 = Application.OpenForms.OfType<Principal>().First(); if (frm3 != null) { frm3.devCont(); frm3.devcontlist(f); frm3.devMed(myShows); } } This is the listview1_SelectedIndexChanged, on this method, the listview updates automatically. private void listView1_SelectedIndexChanged(object sender, EventArgs e) { listView1.BeginUpdate(); listView1.EndUpdate(); listView1.Invalidate(); listView1.Update(); } Inside Takenshows.cs class when I'm removing one element pressing on delete show button happens following: private void button1_Click(object sender, EventArgs e) { c = 0; if (listView1.SelectedItems != null) { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Selected) { DialogResult dr = MessageBox.Show("Are you sure you want to remove the selected item?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); switch (dr) { case DialogResult.Yes: listView1.Items[i].Remove(); i--; for (int j = 0; j < listView1.Items.Count; j++) { c = c + 1; listView1.Items[j].SubItems[0].Text = c.ToString(); } f = Int32.Parse(c.ToString()); myShows = listView1.SelectedItems.Cast<ListViewItem>().Select(lvi => (Show)lvi.Tag).ToList(); var frm2 = Application.OpenForms.OfType<Principal>().First(); if (frm2 != null) { frm2.devCont(); frm2.devcontlist(f); frm2.devMed(myShows); } break; case DialogResult.No: break; } } } } } In this method, the listview sorts programatically by first column inside Takenshows.cs private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) { if (e.Column == 0) { if (lvwColumnSorter.SortColumn == 0) { { lvwColumnSorter.SortColumn = e.Column; lvwColumnSorter.Order = SortOrder.Ascending; } } } this.listView1.Sort(); } } } And finally, inside Main.cs this is the code of the take show button when I take a show: private void button2_Click(object sender, EventArgs e) { string values = textBox_F.Text + " " + textBox_PT.Text + " " + textBox_QT.Text + " " + textBox_ST.Text + " " + textBox_FPT.Text; c = c + 1; watchedShow = new Show { OrdNum = c + d, DTShow = DateTime.Now, Values = values, practiseNumber = GetPractiseNumberLN.getInstance().getPractiseNum() }; watchedShows.Add(watchedShow); var frm = Application.OpenForms.OfType<Takenshows>().FirstOrDefault(); if (frm == null) { frm = new Takenshows(watchedShows); frm.Show(); } else { frm.AddShow(watchedShow); frm.Activate(); } } This line inside Takenshows.cs on Takenshows_load generates the error: listView1.Items.Add(item); Also item is an iterator which it's inside foreach loop. I don't know how can I solve this issue. Is there any way that I can fix this issue? Probably list view doesn't update after adding or removing an element to listview. I tried to replacing foreach loop by for loop on Takenshows_Load: for (int i = 0; i < listView1.Items.Count; i++) { // int index = listView1.Items.IndexOf(i); ListViewItem item = new ListViewItem(); item.Tag = i; item.Text = i.ToString(); item.SubItems.Add(listView1.Items[i].SubItems[0].Text); item.SubItems.Add(listView1.Items[i].SubItems[1].Text); item.SubItems.Add(listView1.Items[i].SubItems[2].Text); item.SubItems.Add(listView1.Items[i].SubItems[3].Text); listView1.Items.Add(item); } But in evidence it happens nothing. How can I fix this issue? I really need fix this issue, but I don't know how to fix that.
[]
[]
[ "foreach (ListViewItem item in listView1.Items)\n{\n int index = listView1.Items.IndexOf(item);\n item.Tag = index;\n item.Text = index.ToString();\n item.SubItems.Add(listView1.Items[index].SubItems[0].Text);\n}\n\nThe problem is that you are taking item and try to insert again to the same listview, this don't work. Try to create a new listviewitem.\nWrite me if you need more simpler sample, for example:\nstring[] row = { textBox1.Text, textBox2.Text, textBox3.Text };\n var listViewItem = new ListViewItem(row); \n listView1.Items.Add(listViewItem);\n\nthis is a fast way to create a listviewitem.\n" ]
[ -1 ]
[ "c#", "listview" ]
stackoverflow_0074674536_c#_listview.txt
Q: decoding a Byte Array sent from arduino to TCP Server made with Python I am converting sensor data to byte and writing a byte array from an arduino to a TCP server made with Python, but somehow the sensor data which are in the array triggers variations of the UTF-8 errors displayed below when decoded. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 1: invalid continuation byte Where "0xcf" and "0xff" change from error to error. I suspect this is because the sensor data can sometimes be negative values. I know a byte cannot hold a negative number and UTF-8 can do 0-256. I think I must send a dedicated "-" sign before the negative values. However, I cannot predict when the negative values occur. Therefore, there must be a better way of doing this. I am able to send the array of bytes without decoding it, but I suspect there are some problems here as well because the two first positions should hold different values than the remaining 6 positions, as shown below: b'\xff\x00\x00\x00\x00\x00\x00\x00' b'\x02\x00\x00\x00\x00\x00\x00\x00' My question is: how can I send negative values as byte and decode it correctly. For context I will attach my code. Arduino Client: ` #include <Ethernet.h> #include <SPI.h> #include "AK09918.h" #include "ICM20600.h" #include <Wire.h> //---------------------------------- //tiltsensor AK09918_err_type_t err; int32_t x, y, z; AK09918 ak09918; ICM20600 icm20600(true); int16_t acc_x, acc_y, acc_z; int32_t offset_x, offset_y, offset_z; double roll, pitch; //---------------------------------- //Ethernet byte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //not important if only one ethernet shield byte ip[] = { 192, 168, X, X}; //IP of this arduino unit byte server[] = { 192, 168, X, X}; //IP of server you want to contact int tcp_port = 65432; // a nice port to send/acess the information on EthernetClient client; //---------------------------------- //byte array byte array[8] = {0, 0, 0, 0, 0, 0, 0, 0}; //---------------------------------- void setup() { //tiltsensor Wire.begin(); err = ak09918.initialize(); icm20600.initialize(); ak09918.switchMode(AK09918_POWER_DOWN); ak09918.switchMode(AK09918_CONTINUOUS_100HZ); Serial.begin(9600); err = ak09918.isDataReady(); while (err != AK09918_ERR_OK) { Serial.println("Waiting Sensor"); delay(100); err = ak09918.isDataReady();} Serial.println("Start figure-8 calibration after 2 seconds."); delay(2000); //calibrate(10000, &offset_x, &offset_y, &offset_z); Serial.println(""); //---------------------------------- //Ethernet Ethernet.begin(mac, ip); //Serial.begin(9600); delay(1000); Serial.println("Connecting..."); if (client.connect(server, tcp_port)) { // Connection to server Serial.println("Connected to server.js"); client.println();} else { Serial.println("connection failed");} //---------------------------------- } void loop() { //tiltsensor acc_x = icm20600.getAccelerationX(); acc_y = icm20600.getAccelerationY(); acc_z = icm20600.getAccelerationZ(); roll = atan2((float)acc_y, (float)acc_z) * 57.3; pitch = atan2(-(float)acc_x, sqrt((float)acc_y * acc_y + (float)acc_z * acc_z)) * 57.3; //---------------------------------- //bytearray array[0] = byte(roll); array[1] = byte(pitch); //---------------------------------- //test Serial.write(array, 8); Serial.println(); delay(500); //---------------------------------- //Ethernet if (client.available()) { //client.print(array); //client.write(array[0]); client.write(array, 8); //client.write(array, 8);//((uint8_t*) array, sizeof(array)); delay(3000); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; } //---------------------------------- } ` TCP server (python): ` # echo-server.py import time import socket HOST = "192.168.X.X" # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(1024) #msg = s.recv(1024) #print(msg.decode("utf-8")) print(data.decode("utf-8")) #time.sleep(3) #conn.sendall(data) if not data: break conn.send(data) ` I am able to establish a connection to the server and the client can write to it. However, I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 0: invalid start byte type errors. A: I was able to make some progress, for Arduino: #include <Ethernet.h> #include <SPI.h> #include "AK09918.h" #include "ICM20600.h" #include <Wire.h> //---------------------------------- //tiltsensor AK09918_err_type_t err; int32_t x, y, z; AK09918 ak09918; ICM20600 icm20600(true); int16_t acc_x, acc_y, acc_z; int32_t offset_x, offset_y, offset_z; double roll, pitch; //---------------------------------- //Ethernet byte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //not important if only one ethernet shield byte ip[] = { 192, 168, X, XX}; //IP of this arduino unit byte server[] = { 192, 168, X, XX}; //IP of server you want to contact int tcp_port = 65432; // a nice port to send/acess the information on EthernetClient client; //---------------------------------- //byte array union some_data{ //convert a float to 4 bytes float tobytes; byte bytearray[4]; }; byte array[14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //intial array //---------------------------------- void setup() { //tiltsensor Wire.begin(); err = ak09918.initialize(); icm20600.initialize(); ak09918.switchMode(AK09918_POWER_DOWN); ak09918.switchMode(AK09918_CONTINUOUS_100HZ); Serial.begin(9600); err = ak09918.isDataReady(); while (err != AK09918_ERR_OK) { Serial.println("Waiting Sensor"); delay(100); err = ak09918.isDataReady();} Serial.println("Start figure-8 calibration after 2 seconds."); delay(2000); //calibrate(10000, &offset_x, &offset_y, &offset_z); Serial.println(""); //---------------------------------- //Ethernet Ethernet.begin(mac, ip); //Serial.begin(9600); delay(1000); Serial.println("Connecting..."); if (client.connect(server, tcp_port)) { // Connection to server Serial.println("Connected to server.js"); client.println();} else { Serial.println("connection failed");} //---------------------------------- //byte array //---------------------------------- } void loop() { //tiltsensor acc_x = icm20600.getAccelerationX(); acc_y = icm20600.getAccelerationY(); acc_z = icm20600.getAccelerationZ(); roll = atan2((float)acc_y, (float)acc_z) * 57.3; pitch = atan2(-(float)acc_x, sqrt((float)acc_y * acc_y + (float)acc_z * acc_z)) * 57.3; //---------------------------------- //bytearray if (roll < 0) {array[0] = 0;} //put identifier for positive or negative value in specific posision in byte array else {array[0] = 1;} if (pitch < 0) {array[5] = 0;} // same for second sensor value else {array[5] = 1;} union some_data sensor1; //use the union function separately union some_data sensor2; sensor1.tobytes =abs(roll); //get byte array for sensor value sensor2.tobytes =abs(pitch); //get byte array for sensor value for (int i=0; i<sizeof sensor1.bytearray/sizeof sensor1.bytearray[0]; i++) { //put sensor value byte array into main byte array array[1+i] = sensor1.bytearray[i]; array[6+i] = sensor2.bytearray[i]; } //---------------------------------- //test Serial.write(array, sizeof array); Serial.println(); delay(500); //---------------------------------- //Ethernet if (client.available()) { //client.print(array); //client.write(array[0]); client.write(array, sizeof array); //client.write(array, 8);//((uint8_t*) array, sizeof(array)); delay(3000); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; } //---------------------------------- } For python TCP Server. # echo-server.py import time import socket HOST = "192.168.XX.XX" # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(1024) #msg = s.recv(1024) #print(msg.decode("utf-8")) print(data)#.decode("utf-8")) #time.sleep(3) #conn.sendall(data) if not data: break conn.send(data) A: As @hcheung mentioned in the comment, in the Arduino side you can simply use Serial.write(&roll, 4); Serial.wirte(&pitch,4); The sign is already encoded in these bytes as the first bits. See wiki for example. On your python side, I would suggest you look into the struct module For your specific case just use roll, pitch = struct.unpack("dd", data) where "dd" describes your format of two doubles.
decoding a Byte Array sent from arduino to TCP Server made with Python
I am converting sensor data to byte and writing a byte array from an arduino to a TCP server made with Python, but somehow the sensor data which are in the array triggers variations of the UTF-8 errors displayed below when decoded. UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 1: invalid continuation byte Where "0xcf" and "0xff" change from error to error. I suspect this is because the sensor data can sometimes be negative values. I know a byte cannot hold a negative number and UTF-8 can do 0-256. I think I must send a dedicated "-" sign before the negative values. However, I cannot predict when the negative values occur. Therefore, there must be a better way of doing this. I am able to send the array of bytes without decoding it, but I suspect there are some problems here as well because the two first positions should hold different values than the remaining 6 positions, as shown below: b'\xff\x00\x00\x00\x00\x00\x00\x00' b'\x02\x00\x00\x00\x00\x00\x00\x00' My question is: how can I send negative values as byte and decode it correctly. For context I will attach my code. Arduino Client: ` #include <Ethernet.h> #include <SPI.h> #include "AK09918.h" #include "ICM20600.h" #include <Wire.h> //---------------------------------- //tiltsensor AK09918_err_type_t err; int32_t x, y, z; AK09918 ak09918; ICM20600 icm20600(true); int16_t acc_x, acc_y, acc_z; int32_t offset_x, offset_y, offset_z; double roll, pitch; //---------------------------------- //Ethernet byte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //not important if only one ethernet shield byte ip[] = { 192, 168, X, X}; //IP of this arduino unit byte server[] = { 192, 168, X, X}; //IP of server you want to contact int tcp_port = 65432; // a nice port to send/acess the information on EthernetClient client; //---------------------------------- //byte array byte array[8] = {0, 0, 0, 0, 0, 0, 0, 0}; //---------------------------------- void setup() { //tiltsensor Wire.begin(); err = ak09918.initialize(); icm20600.initialize(); ak09918.switchMode(AK09918_POWER_DOWN); ak09918.switchMode(AK09918_CONTINUOUS_100HZ); Serial.begin(9600); err = ak09918.isDataReady(); while (err != AK09918_ERR_OK) { Serial.println("Waiting Sensor"); delay(100); err = ak09918.isDataReady();} Serial.println("Start figure-8 calibration after 2 seconds."); delay(2000); //calibrate(10000, &offset_x, &offset_y, &offset_z); Serial.println(""); //---------------------------------- //Ethernet Ethernet.begin(mac, ip); //Serial.begin(9600); delay(1000); Serial.println("Connecting..."); if (client.connect(server, tcp_port)) { // Connection to server Serial.println("Connected to server.js"); client.println();} else { Serial.println("connection failed");} //---------------------------------- } void loop() { //tiltsensor acc_x = icm20600.getAccelerationX(); acc_y = icm20600.getAccelerationY(); acc_z = icm20600.getAccelerationZ(); roll = atan2((float)acc_y, (float)acc_z) * 57.3; pitch = atan2(-(float)acc_x, sqrt((float)acc_y * acc_y + (float)acc_z * acc_z)) * 57.3; //---------------------------------- //bytearray array[0] = byte(roll); array[1] = byte(pitch); //---------------------------------- //test Serial.write(array, 8); Serial.println(); delay(500); //---------------------------------- //Ethernet if (client.available()) { //client.print(array); //client.write(array[0]); client.write(array, 8); //client.write(array, 8);//((uint8_t*) array, sizeof(array)); delay(3000); } if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); for(;;) ; } //---------------------------------- } ` TCP server (python): ` # echo-server.py import time import socket HOST = "192.168.X.X" # Standard loopback interface address (localhost) PORT = 65432 # Port to listen on (non-privileged ports are > 1023) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) s.listen() conn, addr = s.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(1024) #msg = s.recv(1024) #print(msg.decode("utf-8")) print(data.decode("utf-8")) #time.sleep(3) #conn.sendall(data) if not data: break conn.send(data) ` I am able to establish a connection to the server and the client can write to it. However, I get UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa4 in position 0: invalid start byte type errors.
[ "I was able to make some progress,\nfor Arduino:\n#include <Ethernet.h>\n#include <SPI.h>\n#include \"AK09918.h\"\n#include \"ICM20600.h\"\n#include <Wire.h>\n//----------------------------------\n\n//tiltsensor\nAK09918_err_type_t err;\nint32_t x, y, z;\nAK09918 ak09918;\nICM20600 icm20600(true);\nint16_t acc_x, acc_y, acc_z;\nint32_t offset_x, offset_y, offset_z;\ndouble roll, pitch;\n//----------------------------------\n\n//Ethernet\nbyte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //not important if only one ethernet shield\nbyte ip[] = { 192, 168, X, XX}; //IP of this arduino unit\nbyte server[] = { 192, 168, X, XX}; //IP of server you want to contact\nint tcp_port = 65432; // a nice port to send/acess the information on\nEthernetClient client; \n//----------------------------------\n\n\n//byte array\nunion some_data{ //convert a float to 4 bytes\n float tobytes;\n byte bytearray[4];\n};\n\nbyte array[14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //intial array\n//----------------------------------\n\nvoid setup()\n{\n //tiltsensor\n Wire.begin();\n err = ak09918.initialize();\n icm20600.initialize();\n ak09918.switchMode(AK09918_POWER_DOWN);\n ak09918.switchMode(AK09918_CONTINUOUS_100HZ);\n Serial.begin(9600);\n err = ak09918.isDataReady();\n while (err != AK09918_ERR_OK) {\n Serial.println(\"Waiting Sensor\");\n delay(100);\n err = ak09918.isDataReady();}\n Serial.println(\"Start figure-8 calibration after 2 seconds.\");\n delay(2000);\n //calibrate(10000, &offset_x, &offset_y, &offset_z);\n Serial.println(\"\");\n //----------------------------------\n\n //Ethernet\n Ethernet.begin(mac, ip);\n //Serial.begin(9600);\n delay(1000);\n Serial.println(\"Connecting...\");\n if (client.connect(server, tcp_port)) { // Connection to server\n Serial.println(\"Connected to server.js\");\n client.println();} \n else {\n Serial.println(\"connection failed\");}\n //----------------------------------\n\n //byte array\n\n //----------------------------------\n}\n\nvoid loop()\n{\n //tiltsensor\n acc_x = icm20600.getAccelerationX();\n acc_y = icm20600.getAccelerationY();\n acc_z = icm20600.getAccelerationZ();\n roll = atan2((float)acc_y, (float)acc_z) * 57.3;\n pitch = atan2(-(float)acc_x, sqrt((float)acc_y * acc_y + (float)acc_z * acc_z)) * 57.3;\n //----------------------------------\n\n\n //bytearray\n if (roll < 0) {array[0] = 0;} //put identifier for positive or negative value in specific posision in byte array\n else {array[0] = 1;}\n\n if (pitch < 0) {array[5] = 0;} // same for second sensor value\n else {array[5] = 1;}\n\n union some_data sensor1; //use the union function separately\n union some_data sensor2;\n\n sensor1.tobytes =abs(roll); //get byte array for sensor value\n sensor2.tobytes =abs(pitch); //get byte array for sensor value\n\n for (int i=0; i<sizeof sensor1.bytearray/sizeof sensor1.bytearray[0]; i++) { //put sensor value byte array into main byte array\n array[1+i] = sensor1.bytearray[i];\n array[6+i] = sensor2.bytearray[i];\n }\n //----------------------------------\n\n //test\n Serial.write(array, sizeof array);\n Serial.println();\n delay(500); \n //----------------------------------\n\n\n //Ethernet\n if (client.available()) {\n //client.print(array);\n //client.write(array[0]);\n client.write(array, sizeof array);\n //client.write(array, 8);//((uint8_t*) array, sizeof(array));\n delay(3000); \n }\n if (!client.connected()) {\n Serial.println();\n Serial.println(\"disconnecting.\");\n client.stop();\n for(;;)\n ;\n }\n //----------------------------------\n}\n\nFor python TCP Server.\n# echo-server.py\nimport time\nimport socket\n\nHOST = \"192.168.XX.XX\" # Standard loopback interface address (localhost)\nPORT = 65432 # Port to listen on (non-privileged ports are > 1023)\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n s.listen()\n conn, addr = s.accept()\n with conn:\n print(f\"Connected by {addr}\")\n while True:\n data = conn.recv(1024)\n #msg = s.recv(1024)\n #print(msg.decode(\"utf-8\"))\n print(data)#.decode(\"utf-8\"))\n #time.sleep(3)\n #conn.sendall(data)\n if not data:\n break\n conn.send(data)\n \n\n", "As @hcheung mentioned in the comment, in the Arduino side you can simply use\nSerial.write(&roll, 4);\nSerial.wirte(&pitch,4);\n\nThe sign is already encoded in these bytes as the first bits. See wiki for example.\nOn your python side, I would suggest you look into the struct module\nFor your specific case just use\nroll, pitch = struct.unpack(\"dd\", data)\n\nwhere \"dd\" describes your format of two doubles.\n" ]
[ 0, 0 ]
[]
[]
[ "arduino", "python", "tcpclient", "utf_8" ]
stackoverflow_0074613294_arduino_python_tcpclient_utf_8.txt
Q: Zip or create key-value pairs from two lists of lists I have the following MWE: token_uniqueness_sparse = pd.DataFrame({'token_a': [0.1, 0.0], 'token_b': [0.0, 0.2], 'token_c': [0.3, 0.0] } ) sf_fake = pd.DataFrame({'items': [ ['token_a', 'token_c'], ['token_b']], 'rcol': [1,2] }) token_uniqueness_dense = (token_uniqueness_sparse .apply(lambda x: list(x[x.ne(0)]), axis=1) .to_frame('output_column')) token_uniqueness_dense output_column 0 [0.1, 0.3] 1 [0.2] I'm trying to combine the two lists of lists such that I get key-value pairs and can sort the keys by the value. For example: {token_a: 0.1, token_c: 0.3} {token_b: 0.2} If there's a better/smarter way than the way I'm asking for, please let me know. A: Here is a one way: sf_fake=sf_fake.explode('items').set_index('items').T.reset_index(drop=True) ''' items token_a token_c token_b 0 1 1 2 ''' #for example, token_a takes the value in index number 1 in token_uniqueness_sparse df final={i:token_uniqueness_sparse[i].iloc[sf_fake[i].iloc[0] -1] for i in token_uniqueness_sparse.columns} #token_uniqueness_sparse' index starting 0. Thats why subtract 1. # output: {'token_a': 0.1, 'token_b': 0.2, 'token_c': 0.3}
Zip or create key-value pairs from two lists of lists
I have the following MWE: token_uniqueness_sparse = pd.DataFrame({'token_a': [0.1, 0.0], 'token_b': [0.0, 0.2], 'token_c': [0.3, 0.0] } ) sf_fake = pd.DataFrame({'items': [ ['token_a', 'token_c'], ['token_b']], 'rcol': [1,2] }) token_uniqueness_dense = (token_uniqueness_sparse .apply(lambda x: list(x[x.ne(0)]), axis=1) .to_frame('output_column')) token_uniqueness_dense output_column 0 [0.1, 0.3] 1 [0.2] I'm trying to combine the two lists of lists such that I get key-value pairs and can sort the keys by the value. For example: {token_a: 0.1, token_c: 0.3} {token_b: 0.2} If there's a better/smarter way than the way I'm asking for, please let me know.
[ "Here is a one way:\nsf_fake=sf_fake.explode('items').set_index('items').T.reset_index(drop=True)\n'''\nitems token_a token_c token_b\n0 1 1 2\n'''\n#for example, token_a takes the value in index number 1 in token_uniqueness_sparse df\n\nfinal={i:token_uniqueness_sparse[i].iloc[sf_fake[i].iloc[0] -1] for i in token_uniqueness_sparse.columns} #token_uniqueness_sparse' index starting 0. Thats why subtract 1.\n\n# output: {'token_a': 0.1, 'token_b': 0.2, 'token_c': 0.3}\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074670491_python.txt
Q: Failure to report number that is too small I did the following calculations in Julia z = LinRange(-0.09025000000000001,0.19025000000000003,5) d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* (similar(z) .*0 .+1)) minimum(cdf.(d, (z[3]+z[2])/2)) The problem I have is that the last code sometimes gives me the correct result 4.418051841202834e-239, sometimes reports the error DomainError with NaN: Normal: the condition σ >= zero(σ) is not satisfied. I think this is because 4.418051841202834e-239 is too small. But I was wondering why my code can give me different results. A: In addition to points mentioned by others, here are a few more: Firstly, don't use LinRange when numerical accuracy is of importance. This is what the range function is for. LinRange can be used when numerical precision is of lesser importance, since it is faster. From the docstring of range: Special care is taken to ensure intermediate values are computed rationally. To avoid this induced overhead, see the LinRange constructor. Example: julia> LinRange(-0.09025000000000001,0.19025000000000003,5) .- range(-0.09025000000000001,0.19025000000000003,5) 0.0:-3.469446951953614e-18:-1.3877787807814457e-17 Secondly, this is a pretty terrible way to create a vector of a certain value: 0.0051 .* (similar(z) .*0 .+1) Other's have mentioned ones, etc. but I think it's better to use fill fill(0.0051, size(z)) which directly fills the array with the right value. Perhaps one should use convert(eltype(z), 0.0051) inside fill. Thirdly, don't create this vector at all! You use broadcasting, so just use the scalar value: d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051) # look! just a scalar! This is how broadcasting works, it expands singleton dimensions implicitly to match other arguments (without actually wasting that memory). Much of the point of broadcasting is that you don't need to create that sort of 'dummy arrays' anymore. If you find yourself doing that, give it another think; constant-valued arrays are inherently wasteful, and you shouldn't need to create them. A: You are using the Normal function to generate a normal distribution with a mean and standard deviation that are both very small numbers. This can cause numerical precision errors, which can lead to the DomainError you are seeing. To avoid this problem is to use the BigFloat type to represent your numbers with higher precision. This will allow you to work with very small or very large numbers without encountering numerical precision errors. using Pkg Pkg.add("SpecialFunctions") using SpecialFunctions z = LinRange(-0.09025000000000001,0.19025000000000003,5) d = Normal.(BigFloat.(0.05*(1-0.95)) .+ BigFloat.(0.95)*BigFloat.(z) .- BigFloat(0.0051^2/2), BigFloat.(0.0051) .* (similar(z) .*0 .+1)) minimum(cdf.(d, (z[3]+z[2])/2)) A: The problem in the code is similar(z) which produces a vector with undefined entries and is used without initialization. Use ones(length(z)) instead. A: There are two problems: Noted by @Dan Getz: similar does no initialize the values and quite often unused areas of memory have values corresponding to NaN. In that case multiplication by 0 does not help since NaN * 0 == NaN. Instead you want to have ones(eltype(z),size(z)) you need to use higher precision than Float64. BigFloat is one way to go - just you need to remember to call setprecision(BigFloat, 128) so you actually control how many bits you use. However, much more time-efficient solution (if you run computations at scale) will be to use a dedicated package such as DoubleFloats. Sample corrected code using DoubleFloats below: julia> z = LinRange(df64"-0.09025000000000001",df64"0.19025000000000003",5) 5-element LinRange{Double64, Int64}: -0.09025000000000001,-0.020125,0.05000000000000001,0.12012500000000002,0.19025000000000003 julia> d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* ones(eltype(z),size(z))) 5-element Vector{Normal{Double64}}: Normal{Double64}(μ=-0.083250505, σ=0.0051) Normal{Double64}(μ=-0.016631754999999998, σ=0.0051) Normal{Double64}(μ=0.049986995000000006, σ=0.0051) Normal{Double64}(μ=0.11660574500000001, σ=0.0051) Normal{Double64}(μ=0.18322449500000001, σ=0.0051) julia> minimum(cdf.(d, (z[3]+z[2])/2)) 4.418051841203009e-239
Failure to report number that is too small
I did the following calculations in Julia z = LinRange(-0.09025000000000001,0.19025000000000003,5) d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* (similar(z) .*0 .+1)) minimum(cdf.(d, (z[3]+z[2])/2)) The problem I have is that the last code sometimes gives me the correct result 4.418051841202834e-239, sometimes reports the error DomainError with NaN: Normal: the condition σ >= zero(σ) is not satisfied. I think this is because 4.418051841202834e-239 is too small. But I was wondering why my code can give me different results.
[ "In addition to points mentioned by others, here are a few more:\nFirstly, don't use LinRange when numerical accuracy is of importance. This is what the range function is for. LinRange can be used when numerical precision is of lesser importance, since it is faster. From the docstring of range:\n\nSpecial care is taken to ensure intermediate values are computed rationally. To avoid this induced overhead, see the LinRange constructor.\n\nExample:\njulia> LinRange(-0.09025000000000001,0.19025000000000003,5) .- range(-0.09025000000000001,0.19025000000000003,5)\n0.0:-3.469446951953614e-18:-1.3877787807814457e-17\n\nSecondly, this is a pretty terrible way to create a vector of a certain value:\n0.0051 .* (similar(z) .*0 .+1)\n\nOther's have mentioned ones, etc. but I think it's better to use fill\nfill(0.0051, size(z))\n\nwhich directly fills the array with the right value. Perhaps one should use convert(eltype(z), 0.0051) inside fill.\nThirdly, don't create this vector at all! You use broadcasting, so just use the scalar value:\nd = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051) # look! just a scalar!\n\nThis is how broadcasting works, it expands singleton dimensions implicitly to match other arguments (without actually wasting that memory).\nMuch of the point of broadcasting is that you don't need to create that sort of 'dummy arrays' anymore. If you find yourself doing that, give it another think; constant-valued arrays are inherently wasteful, and you shouldn't need to create them.\n", "You are using the Normal function to generate a normal distribution with a mean and standard deviation that are both very small numbers. This can cause numerical precision errors, which can lead to the DomainError you are seeing.\nTo avoid this problem is to use the BigFloat type to represent your numbers with higher precision. This will allow you to work with very small or very large numbers without encountering numerical precision errors.\nusing Pkg\nPkg.add(\"SpecialFunctions\")\nusing SpecialFunctions\n\nz = LinRange(-0.09025000000000001,0.19025000000000003,5)\nd = Normal.(BigFloat.(0.05*(1-0.95)) .+ BigFloat.(0.95)*BigFloat.(z) .- BigFloat(0.0051^2/2), BigFloat.(0.0051) .* (similar(z) .*0 .+1))\nminimum(cdf.(d, (z[3]+z[2])/2))\n\n", "The problem in the code is similar(z) which produces a vector with undefined entries and is used without initialization. Use ones(length(z)) instead.\n", "There are two problems:\n\nNoted by @Dan Getz: similar does no initialize the values and quite often unused areas of memory have values corresponding to NaN. In that case multiplication by 0 does not help since NaN * 0 == NaN. Instead you want to have ones(eltype(z),size(z))\nyou need to use higher precision than Float64. BigFloat is one way to go - just you need to remember to call setprecision(BigFloat, 128) so you actually control how many bits you use. However, much more time-efficient solution (if you run computations at scale) will be to use a dedicated package such as DoubleFloats.\n\nSample corrected code using DoubleFloats below:\njulia> z = LinRange(df64\"-0.09025000000000001\",df64\"0.19025000000000003\",5)\n5-element LinRange{Double64, Int64}:\n -0.09025000000000001,-0.020125,0.05000000000000001,0.12012500000000002,0.19025000000000003\n\njulia> d = Normal.(0.05*(1-0.95) .+ 0.95.*z .- 0.0051^2/2, 0.0051 .* ones(eltype(z),size(z)))\n5-element Vector{Normal{Double64}}:\n Normal{Double64}(μ=-0.083250505, σ=0.0051)\n Normal{Double64}(μ=-0.016631754999999998, σ=0.0051)\n Normal{Double64}(μ=0.049986995000000006, σ=0.0051)\n Normal{Double64}(μ=0.11660574500000001, σ=0.0051)\n Normal{Double64}(μ=0.18322449500000001, σ=0.0051)\n\njulia> minimum(cdf.(d, (z[3]+z[2])/2))\n4.418051841203009e-239\n\n" ]
[ 2, 1, 1, 1 ]
[]
[]
[ "julia" ]
stackoverflow_0074672480_julia.txt
Q: 401. That’s an error. Error: invalid_client The OAuth client was not found I am working with Google Drive File Picker by following this Google Drive File Picker Example demo project. I have generated API Key and Client Id. But when I run the project I am getting following error That’s an error. Error: invalid_client The OAuth client was not found. I have also checked This Google Drive File Picker Example Link but it does not work, Please help me to solve my issue. invalid_client in google oauth2. A: Your client_id is not correct, re-check pls A: In the following pic, I made with restricted mode in API keys section. This helped me to to remove the display. Hence finally, shown as: No API keys to display Try to validate the client_id with those that you created for your project as: https://console.developers.google.com/google/maps-apis/credentials?folder=&organizationId=&project=saml-281612 The project name, like in my case, it is saml, should match with the project apps as saml to mitigate mismatch_uri error. This helped me to remove all those errors as: 1. Error 400 : mismatch_uri 2. Error 401 : invalid client_id A: In my case, i mistakenly add a , in the values in my .env files so better check that file # check the comma at the end AUTH_CLIENT_SECRET=randomauthsecret, AUTH_CLIENT_ID=randomclientid, That causes the wrong client id value. So just remove the ,. Another thing, also don't enclose them in quotes. AUTH_CLIENT_SECRET=randomauthsecret AUTH_CLIENT_ID=randomclientid A: you may be getting this error if you are already logged in to a google account on your system so log out of all accounts and then run the code A: Also facing the same issue and wasted half an hour, the thing that worked for me was creating a new credential and replacing old credential in code with new. And then it was working as expected A: It worked for me after I removed the quotation marks I had set in my environment variable A: The problem was how vscode format the code, it leaves spaces within the client_id, so I used atom to write the client_id in the .env file and ran app.js through hyper. It worked. A: make sure, there is no space when passing the client id on. speaking from experience A: May be values are not correct in .env file for "Client ID" and "Client secret" or mistake of using "," in file.
401. That’s an error. Error: invalid_client The OAuth client was not found
I am working with Google Drive File Picker by following this Google Drive File Picker Example demo project. I have generated API Key and Client Id. But when I run the project I am getting following error That’s an error. Error: invalid_client The OAuth client was not found. I have also checked This Google Drive File Picker Example Link but it does not work, Please help me to solve my issue. invalid_client in google oauth2.
[ "Your client_id is not correct, re-check pls\n", "\nIn the following pic, I made with restricted mode in API keys section. This helped me to to remove the display. Hence finally, shown as:\nNo API keys to display\n\nTry to validate the client_id with those that you created for your project as:\nhttps://console.developers.google.com/google/maps-apis/credentials?folder=&organizationId=&project=saml-281612\nThe project name, like in my case, it is saml, should match with the project apps as saml to mitigate mismatch_uri error.\nThis helped me to remove all those errors as:\n1. Error 400 : mismatch_uri\n2. Error 401 : invalid client_id \n\n", "In my case, i mistakenly add a , in the values in my .env files so better check that file\n# check the comma at the end\nAUTH_CLIENT_SECRET=randomauthsecret,\nAUTH_CLIENT_ID=randomclientid, \n\nThat causes the wrong client id value. So just remove the ,. Another thing, also don't enclose them in quotes.\nAUTH_CLIENT_SECRET=randomauthsecret\nAUTH_CLIENT_ID=randomclientid\n\n", "you may be getting this error if you are already logged in to a google account on your system so log out of all accounts and then run the code\n", "Also facing the same issue and wasted half an hour, the thing that worked for me was creating a new credential and replacing old credential in code with new.\nAnd then it was working as expected\n", "It worked for me after I removed the quotation marks I had set in my environment variable\n", "The problem was how vscode format the code, it leaves spaces within the client_id, so I used atom to write the client_id in the .env file and ran app.js through hyper. It worked.\n", "make sure, there is no space when passing the client id on. speaking from experience\n", "May be values are not correct in .env file for \"Client ID\" and \"Client secret\" or mistake of using \",\" in file.\n" ]
[ 12, 6, 4, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "google_drive_api", "google_oauth", "oauth", "oauth_2.0", "php" ]
stackoverflow_0032205824_google_drive_api_google_oauth_oauth_oauth_2.0_php.txt
Q: Reference value from state’s input, using JSONPath syntax in combination with a hard-coded string Im creating a SSM document with a state machine, in the api parameter: Name. I want to combine a value from the state’s input (InstanceID) with the hard-coded text EC2-PROD-WEBSRV-CP_RAM_SWAP-Document. Im wondering if something like "key2.$": "$.inputValue[+hardcodedstring]" is possible. So the final value will be i-013165f64447e25e0-EC2-PROD-WEBSRV-CP_RAM_SWAP-Document. SSM CreateDocument schema: { "Attachments": [ { "Key": "string", "Name": "string", "Values": [ "string" ] } ], "Content": "string", "DisplayName": "string", "DocumentFormat": "string", "DocumentType": "string", "Name": "string", "Requires": [ { "Name": "string", "Version": "string" } ], "Tags": [ { "Key": "string", "Value": "string" } ], "TargetType": "string", "VersionName": "string" } I read the documentation but It seems it is possible just one or the other option. https://aws.amazon.com/blogs/compute/using-jsonpath-effectively-in-aws-step-functions/ A: Use the States.Format intrinsic function to interpolate the value into a string: "key2.$": "States.Format('{}-EC2-PROD-WEBSRV-CP_RAM_SWAP-Document', $.inputValue)"
Reference value from state’s input, using JSONPath syntax in combination with a hard-coded string
Im creating a SSM document with a state machine, in the api parameter: Name. I want to combine a value from the state’s input (InstanceID) with the hard-coded text EC2-PROD-WEBSRV-CP_RAM_SWAP-Document. Im wondering if something like "key2.$": "$.inputValue[+hardcodedstring]" is possible. So the final value will be i-013165f64447e25e0-EC2-PROD-WEBSRV-CP_RAM_SWAP-Document. SSM CreateDocument schema: { "Attachments": [ { "Key": "string", "Name": "string", "Values": [ "string" ] } ], "Content": "string", "DisplayName": "string", "DocumentFormat": "string", "DocumentType": "string", "Name": "string", "Requires": [ { "Name": "string", "Version": "string" } ], "Tags": [ { "Key": "string", "Value": "string" } ], "TargetType": "string", "VersionName": "string" } I read the documentation but It seems it is possible just one or the other option. https://aws.amazon.com/blogs/compute/using-jsonpath-effectively-in-aws-step-functions/
[ "Use the States.Format intrinsic function to interpolate the value into a string:\n\"key2.$\": \"States.Format('{}-EC2-PROD-WEBSRV-CP_RAM_SWAP-Document', $.inputValue)\"\n\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_step_functions", "json", "jsonpath" ]
stackoverflow_0074672424_amazon_web_services_aws_step_functions_json_jsonpath.txt