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: Why is my code still runing after few iterations? I was programing some simple algorithms in C and then i got to a problem where my while loop won't stop. Problem was phrased like this: write a program that loads natural number n < 11 and writes smallest natural number m with this property: m mod 2 = 1, m mod 3 = 2, ..., m mod n = n-1. #include <stdio.h> int main(void){ int n, m, k, p; scanf("%d", &n); k=n-1; while(k){ for(m=n+1; ;m++){ for(p=2; p<=i; p++){ if(i%p==p-1)k--; } } } printf("%d", m); return 0; } Why is it still running even after n iterations? A: There are a few problems with your code. First, the for loop you have defined is missing its loop condition, which means it will run indefinitely. This is what is causing the infinite loop. Here is how you can fix it: #include <stdio.h> int main(void){ int n, i, k; scanf("%d", &n); k=n-1; while(k){ for(i=n+1; i <= k; i++){ // Add loop condition here printf("%d", i); k--; // Move this statement inside the for loop } } return 0; } In this code, I have added a loop condition to the for loop so that it will only run a certain number of times. I have also moved the k-- statement inside the for loop so that it is executed on each iteration. This will decrement k as expected, and eventually cause the while loop to stop.
Why is my code still runing after few iterations?
I was programing some simple algorithms in C and then i got to a problem where my while loop won't stop. Problem was phrased like this: write a program that loads natural number n < 11 and writes smallest natural number m with this property: m mod 2 = 1, m mod 3 = 2, ..., m mod n = n-1. #include <stdio.h> int main(void){ int n, m, k, p; scanf("%d", &n); k=n-1; while(k){ for(m=n+1; ;m++){ for(p=2; p<=i; p++){ if(i%p==p-1)k--; } } } printf("%d", m); return 0; } Why is it still running even after n iterations?
[ "There are a few problems with your code. First, the for loop you have defined is missing its loop condition, which means it will run indefinitely. This is what is causing the infinite loop.\nHere is how you can fix it:\n #include <stdio.h>\n\nint main(void){\n int n, i, k;\n\n scanf(\"%d\", &n);\n\n k=n-1;\n\n while(k){\n for(i=n+1; i <= k; i++){ // Add loop condition here\n printf(\"%d\", i);\n k--; // Move this statement inside the for loop\n }\n }\n\n return 0;\n}\n\nIn this code, I have added a loop condition to the for loop so that it will only run a certain number of times. I have also moved the k-- statement inside the for loop so that it is executed on each iteration. This will decrement k as expected, and eventually cause the while loop to stop.\n" ]
[ 0 ]
[]
[]
[ "c", "for_loop", "while_loop" ]
stackoverflow_0074671271_c_for_loop_while_loop.txt
Q: Send data file from client UDP ipv6 to the server I try to send a file data size of around 100MB from the client to the server in UDP ipv6. the server I think it works well but the client I cannot figure out why I cannot send the file. When I try to "sendto" I got the message: perror("[-]Error in sending the file. in UDP CLIENT")" here is my code: void client() { int sockfd; char buffer[65536]; struct sockaddr_in servaddr; // Creating socket file descriptor if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(P); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len; FILE *fp = fopen("data.txt","r"); char data[SIZE] = {0}; while (fgets(data, SIZE, fp) != NULL) { if (sendto(sockfd, data, sizeof(data), MSG_CONFIRM, (const struct sockaddr *) &servaddr, sizeof(servaddr)) == -1) { perror("[-]Error in sending file. in UDP CLIENT"); exit(1); } bzero(data, SIZE); } printf("Hello message sent.\n"); n = recvfrom(sockfd, (char *) buffer, 65536, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); buffer[n] = '\0'; printf("Server : %s\n", buffer); close(sockfd); } A: In order to send a file over UDP, you will need to break the file into smaller pieces and send each piece individually. UDP is not a reliable protocol, which means that packets can be lost or arrive out of order. Therefore, you will need to implement some sort of error-checking and retransmission mechanism to ensure that the entire file is successfully sent. In your current code, you are trying to send the entire file in one go using the sendto() function. This is not possible with UDP because there is a limit on the maximum size of a UDP packet. The maximum size of a UDP packet is determined by the maximum transmission unit (MTU) of the network, which is typically around 1500 bytes. If you try to send a packet larger than the MTU, it will be fragmented and may not reach the destination. To fix this, you will need to break the file into smaller pieces and send each piece individually. You can do this by using a loop to read a chunk of the file into a buffer and then send the buffer using sendto(). You will also need to add some error-checking and retransmission logic to ensure that each piece of the file is successfully sent and received. Here is an example of how you could modify your code to send the file in smaller pieces: void client() { int sockfd; char buffer[65536]; struct sockaddr_in servaddr; // Creating socket file descriptor if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(P); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len; FILE *fp = fopen("data.txt","r"); char data[SIZE] = {0}; // Loop through the file and send each chunk of data while (fgets(data, SIZE, fp) != NULL) { // Send the data using sendto() if (sendto(sockfd, data, sizeof(data), MSG_CONFIRM, (const struct sockaddr *) &servaddr, sizeof(servaddr)) == -1) { perror("[-]Error in sending file. in UDP CLIENT"); exit(1); } // Clear the buffer for the next chunk of data bzero(data, SIZE); } printf("Hello message sent.\n"); n = recvfrom(sockfd, (char *) buffer, 65536, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); buffer[n] = '\0'; printf("Server : %s\n", buffer); close(sockfd); } Note that this code is only an example and does not include any error-checking or retransmission logic. In order to make your file transfer reliable, you will need to add this additional logic yourself. I hope this helps!
Send data file from client UDP ipv6 to the server
I try to send a file data size of around 100MB from the client to the server in UDP ipv6. the server I think it works well but the client I cannot figure out why I cannot send the file. When I try to "sendto" I got the message: perror("[-]Error in sending the file. in UDP CLIENT")" here is my code: void client() { int sockfd; char buffer[65536]; struct sockaddr_in servaddr; // Creating socket file descriptor if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } memset(&servaddr, 0, sizeof(servaddr)); // Filling server information servaddr.sin_family = AF_INET; servaddr.sin_port = htons(P); servaddr.sin_addr.s_addr = INADDR_ANY; int n, len; FILE *fp = fopen("data.txt","r"); char data[SIZE] = {0}; while (fgets(data, SIZE, fp) != NULL) { if (sendto(sockfd, data, sizeof(data), MSG_CONFIRM, (const struct sockaddr *) &servaddr, sizeof(servaddr)) == -1) { perror("[-]Error in sending file. in UDP CLIENT"); exit(1); } bzero(data, SIZE); } printf("Hello message sent.\n"); n = recvfrom(sockfd, (char *) buffer, 65536, MSG_WAITALL, (struct sockaddr *) &servaddr, &len); buffer[n] = '\0'; printf("Server : %s\n", buffer); close(sockfd); }
[ "In order to send a file over UDP, you will need to break the file into smaller pieces and send each piece individually. UDP is not a reliable protocol, which means that packets can be lost or arrive out of order. Therefore, you will need to implement some sort of error-checking and retransmission mechanism to ensure that the entire file is successfully sent.\nIn your current code, you are trying to send the entire file in one go using the sendto() function. This is not possible with UDP because there is a limit on the maximum size of a UDP packet. The maximum size of a UDP packet is determined by the maximum transmission unit (MTU) of the network, which is typically around 1500 bytes. If you try to send a packet larger than the MTU, it will be fragmented and may not reach the destination.\nTo fix this, you will need to break the file into smaller pieces and send each piece individually. You can do this by using a loop to read a chunk of the file into a buffer and then send the buffer using sendto(). You will also need to add some error-checking and retransmission logic to ensure that each piece of the file is successfully sent and received.\nHere is an example of how you could modify your code to send the file in smaller pieces:\nvoid client() {\n int sockfd;\n char buffer[65536];\n struct sockaddr_in servaddr;\n\n // Creating socket file descriptor\n if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n perror(\"socket creation failed\");\n exit(EXIT_FAILURE);\n }\n memset(&servaddr, 0, sizeof(servaddr));\n\n // Filling server information\n servaddr.sin_family = AF_INET;\n servaddr.sin_port = htons(P);\n servaddr.sin_addr.s_addr = INADDR_ANY;\n\n int n, len;\n FILE *fp = fopen(\"data.txt\",\"r\");\n char data[SIZE] = {0};\n\n // Loop through the file and send each chunk of data\n while (fgets(data, SIZE, fp) != NULL) {\n // Send the data using sendto()\n if (sendto(sockfd, data, sizeof(data),\n MSG_CONFIRM, (const struct sockaddr *) &servaddr,\n sizeof(servaddr)) == -1) {\n perror(\"[-]Error in sending file. in UDP CLIENT\");\n exit(1);\n }\n\n // Clear the buffer for the next chunk of data\n bzero(data, SIZE);\n }\n printf(\"Hello message sent.\\n\");\n\n n = recvfrom(sockfd, (char *) buffer, 65536,\n MSG_WAITALL, (struct sockaddr *) &servaddr,\n &len);\n buffer[n] = '\\0';\n printf(\"Server : %s\\n\", buffer);\n\n close(sockfd);\n}\n\nNote that this code is only an example and does not include any error-checking or retransmission logic. In order to make your file transfer reliable, you will need to add this additional logic yourself.\nI hope this helps!\n" ]
[ 0 ]
[]
[]
[ "c", "file", "sockets", "udp" ]
stackoverflow_0074671264_c_file_sockets_udp.txt
Q: Modify array to make it usable with RegExp I have an input array which contains various domains: var sites = ["site2.com", "site2.com", "site3.com"]; I need to check, whether certain string domainName matches one of these sites. I used indexOf which worked fine, however problem occured when certain domainName was shown with subpage, e.g. subpage.site1.com. I tried to use some method with RegExp testing instead: if(sites.some(function(rx) { return rx.test(domainName); }) however the first problem was that I needed to change "" for every element to "\\" to make it work with RegExp: var sites = [/site1.com/, /site2.com/, /site3.com/]; while I want to keep array with quotation marks for end-user. Second problem was that it returns true for in cases where compared domainName is not in array, but partially its name contains is part of element in array, for example anothersite1.com with site1.com. It's rare case but happens. I can modify my input array with RegExp will start and end with ^$ escape characters, but it will complicate it even more, especially that I will need to also add ([a-z0-9]+[.]) to match subpages. I tried to use replace to change "foo" to \foo\, but I was unable since quation marks defines array elements. Also I tried to use replace with concat to merge string with escape characters to achieve element looking like RegExp formula from site1.com to ^([a-z0-9]+[.])*site1\.com$ but got issues with escaping characters. Is there a simpler way to achieve this goal? A: Use the String.prototype.includes() method to check if a string is included in another string. var domainName = "subpage.site1.com"; var sites = ["site1.com", "site2.com", "site3.com"]; // Check if any of the sites are included in the domain name var isMatch = sites.some(site => domainName.includes(site)); This will return true if domainName includes any of the sites in the sites array. Alternatively, you could use the String.prototype.indexOf() method, which will return the index of the first occurrence of the specified string within the string. var domainName = "subpage.site1.com"; var sites = ["site1.com", "site2.com", "site3.com"]; // Check if any of the sites are included in the domain name var isMatch = sites.some(site => domainName.indexOf(site) !== -1); This will return true if domainName includes any of the sites in the sites array. Note that this method does not support regular expressions, so you will not be able to use it to match subdomains as in your example. You could also use the Array.prototype.filter() method to create a new array containing only the matching sites, and then check the length of that array to see if any matches were found. var domainName = "subpage.site1.com"; var sites = ["site1.com", "site2.com", "site3.com"]; // Create a new array containing only the sites that are included in the domain name var matchingSites = sites.filter(site => domainName.includes(site)); // Check if any matches were found var isMatch = matchingSites.length > 0; This will return true if domainName includes any of the sites in the sites array. Overall, the includes() or indexOf() methods are probably the simplest ways to check if a string is included in another string. A: You can use the String.prototype.match method and pass in a regular expression to check if the domain name matches any of the sites in your array. Here's an example: var sites = ["site1.com", "site2.com", "site3.com"]; var domainName = "subpage.site1.com"; var regex = new RegExp(`^([a-z0-9]+[.])*${domainName}$`); var matches = sites.filter(site => site.match(regex)); console.log(matches); // ["site1.com"] In the code above, we create a regular expression that matches the domainName with any subpage prefixes. We then use the Array.prototype.filter method to find any elements in the sites array that match the regular expression. This will return an array of matching elements, or an empty array if no matches were found. Note that you can also use the Array.prototype.some method to check if any element in the sites array matches the regular expression, like this: var matches = sites.some(site => site.match(regex)); console.log(matches); // true This will return true if at least one element in the sites array matches the regular expression, and false otherwise. A: You can build a regex from the sites array and do a single regex test: const sites = ["site1.com", "site2.com", "site3.com"]; const sitesRegex = new RegExp( '\\b(' + sites.map(site => site.replace(/([\\\.(){}])/g, '\\$1')).join('|') + ')$' ); console.log('sitesRegex: ' + sitesRegex); // tests: ['foo.com', 'notsite1.com', 'site1.com', 'www.site1.com'].forEach(site => { console.log(site + ' => ' + sitesRegex.test(site)); }); Output: sitesRegex: /\b(site1\.com|site2\.com|site3\.com)$/ foo.com => false notsite1.com => false site1.com => true www.site1.com => true Explanation of .replace() regex: ( -- capture group 1 start [\\\.(){}] -- character class with regex chars that need to be escaped ) -- capture group 1 end g flag -- global (match multiple times) Explanation of resulting /\b(site1\.com|site2\.com|site3\.com)$/ regex: \b -- word boundary ( -- group start site1\.com|site2\.com|site3\.com -- logically ORed and escaped sites ) -- group end $ -- anchor at end of string A: I don't think regex is needed here. You could temporarily prefix both the domainName and the site with a dot, and then call endsWith: const sites = ["site1.com", "site2.com", "site3.com"]; const isValid = domainName => sites.some(site => ("." + domainName).endsWith("." + site)); // demo console.log(isValid("site1.com")); // true console.log(isValid("subpage.site1.com")); // true console.log(isValid("othersite1.com")); // false
Modify array to make it usable with RegExp
I have an input array which contains various domains: var sites = ["site2.com", "site2.com", "site3.com"]; I need to check, whether certain string domainName matches one of these sites. I used indexOf which worked fine, however problem occured when certain domainName was shown with subpage, e.g. subpage.site1.com. I tried to use some method with RegExp testing instead: if(sites.some(function(rx) { return rx.test(domainName); }) however the first problem was that I needed to change "" for every element to "\\" to make it work with RegExp: var sites = [/site1.com/, /site2.com/, /site3.com/]; while I want to keep array with quotation marks for end-user. Second problem was that it returns true for in cases where compared domainName is not in array, but partially its name contains is part of element in array, for example anothersite1.com with site1.com. It's rare case but happens. I can modify my input array with RegExp will start and end with ^$ escape characters, but it will complicate it even more, especially that I will need to also add ([a-z0-9]+[.]) to match subpages. I tried to use replace to change "foo" to \foo\, but I was unable since quation marks defines array elements. Also I tried to use replace with concat to merge string with escape characters to achieve element looking like RegExp formula from site1.com to ^([a-z0-9]+[.])*site1\.com$ but got issues with escaping characters. Is there a simpler way to achieve this goal?
[ "Use the String.prototype.includes() method to check if a string is included in another string.\nvar domainName = \"subpage.site1.com\";\nvar sites = [\"site1.com\", \"site2.com\", \"site3.com\"];\n\n// Check if any of the sites are included in the domain name\nvar isMatch = sites.some(site => domainName.includes(site));\n\nThis will return true if domainName includes any of the sites in the sites array.\nAlternatively, you could use the String.prototype.indexOf() method, which will return the index of the first occurrence of the specified string within the string.\nvar domainName = \"subpage.site1.com\";\nvar sites = [\"site1.com\", \"site2.com\", \"site3.com\"];\n\n// Check if any of the sites are included in the domain name\nvar isMatch = sites.some(site => domainName.indexOf(site) !== -1);\n\nThis will return true if domainName includes any of the sites in the sites array. Note that this method does not support regular expressions, so you will not be able to use it to match subdomains as in your example.\nYou could also use the Array.prototype.filter() method to create a new array containing only the matching sites, and then check the length of that array to see if any matches were found.\nvar domainName = \"subpage.site1.com\";\nvar sites = [\"site1.com\", \"site2.com\", \"site3.com\"];\n\n// Create a new array containing only the sites that are included in the domain name\nvar matchingSites = sites.filter(site => domainName.includes(site));\n\n// Check if any matches were found\nvar isMatch = matchingSites.length > 0;\n\nThis will return true if domainName includes any of the sites in the sites array.\nOverall, the includes() or indexOf() methods are probably the simplest ways to check if a string is included in another string.\n", "You can use the String.prototype.match method and pass in a regular expression to check if the domain name matches any of the sites in your array.\nHere's an example:\nvar sites = [\"site1.com\", \"site2.com\", \"site3.com\"];\nvar domainName = \"subpage.site1.com\";\n\nvar regex = new RegExp(`^([a-z0-9]+[.])*${domainName}$`);\nvar matches = sites.filter(site => site.match(regex));\n\nconsole.log(matches); // [\"site1.com\"]\n\nIn the code above, we create a regular expression that matches the domainName with any subpage prefixes. We then use the Array.prototype.filter method to find any elements in the sites array that match the regular expression. This will return an array of matching elements, or an empty array if no matches were found.\nNote that you can also use the Array.prototype.some method to check if any element in the sites array matches the regular expression, like this:\nvar matches = sites.some(site => site.match(regex));\nconsole.log(matches); // true\n\nThis will return true if at least one element in the sites array matches the regular expression, and false otherwise.\n", "You can build a regex from the sites array and do a single regex test:\n\n\nconst sites = [\"site1.com\", \"site2.com\", \"site3.com\"];\nconst sitesRegex = new RegExp(\n '\\\\b(' +\n sites.map(site => site.replace(/([\\\\\\.(){}])/g, '\\\\$1')).join('|') +\n ')$'\n);\nconsole.log('sitesRegex: ' + sitesRegex);\n// tests:\n['foo.com', 'notsite1.com', 'site1.com', 'www.site1.com'].forEach(site => {\n console.log(site + ' => ' + sitesRegex.test(site));\n});\n\n\n\nOutput:\nsitesRegex: /\\b(site1\\.com|site2\\.com|site3\\.com)$/\nfoo.com => false\nnotsite1.com => false\nsite1.com => true\nwww.site1.com => true\n\nExplanation of .replace() regex:\n\n( -- capture group 1 start\n[\\\\\\.(){}] -- character class with regex chars that need to be escaped\n) -- capture group 1 end\ng flag -- global (match multiple times)\n\nExplanation of resulting /\\b(site1\\.com|site2\\.com|site3\\.com)$/ regex:\n\n\\b -- word boundary\n( -- group start\nsite1\\.com|site2\\.com|site3\\.com -- logically ORed and escaped sites\n) -- group end\n$ -- anchor at end of string\n\n", "I don't think regex is needed here. You could temporarily prefix both the domainName and the site with a dot, and then call endsWith:\n\n\nconst sites = [\"site1.com\", \"site2.com\", \"site3.com\"];\n\nconst isValid = domainName => \n sites.some(site => (\".\" + domainName).endsWith(\".\" + site));\n\n// demo\nconsole.log(isValid(\"site1.com\")); // true\nconsole.log(isValid(\"subpage.site1.com\")); // true\nconsole.log(isValid(\"othersite1.com\")); // false\n\n\n\n" ]
[ 1, 1, 1, 1 ]
[]
[]
[ "javascript", "regex" ]
stackoverflow_0074671170_javascript_regex.txt
Q: Use jq to extract sublist into a single line From, jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + "," + .DomainName' << EOF { "DistributionList": { "Items": [ { "Id": "EG3MOA", "Status": "Deployed", "LastModifiedTime": "2022-12-03T19:32:35.007000+00:00", "DomainName": "a***.cloudfront.net", "Aliases": { "Quantity": 1, "Items": [ "a.domain.tld", "b.domain.tld" ] } }, { "Id": "EG3MOB", "Status": "Deployed", "LastModifiedTime": "2022-12-03T19:32:35.007000+00:00", "DomainName": "b***.cloudfront.net", "Aliases": { "Quantity": 1, "Items": [ "c.domain.tld", "d.domain.tld" ] } } ] } } EOF It yields: "EG3MOA,a***.cloudfront.net" "EG3MOB,b***.cloudfront.net" How would I also get the `Alias Items, so that I have: "EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'" "EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'" A: To extract the Aliases.Items array and combine it into a single string, you can use the join() method in jq. For example, this jq filter would extract the Id, DomainName, and Aliases.Items values and combine them into a single string, with the Aliases.Items values joined together with a comma: jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + "," + .DomainName + ",'" + (.Aliases.Items | join(",")) + "'" Here's an example of how you could use this filter in your command: jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + "," + .DomainName + ",'" + (.Aliases.Items | join(",")) + "'" << EOF { "DistributionList": { "Items": [ { "Id": "EG3MOA", "Status": "Deployed", "LastModifiedTime": "2022-12-03T19:32:35.007000+00:00", "DomainName": "a***.cloudfront.net", "Aliases": { "Quantity": 1, "Items": [ "a.domain.tld", "b.domain.tld" ] } }, { "Id": "EG3MOB", "Status": "Deployed", "LastModifiedTime": "2022-12-03T19:32:35.007000+00:00", "DomainName": "b***.cloudfront.net", "Aliases": { "Quantity": 1, "Items": [ "c.domain.tld", "d.domain.tld" ] } } ] } } EOF This should output the following: "EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'" "EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'" A: If you are struggling to enclose an apostrophe ' with JSON string quotes " withing a jq filter enclosed again by apostrophes, you can use the codepoint notation instead: \u0027 jq '… | "\(.Id),\(.DomainName),\u0027\(.Aliases.Items | join(","))\u0027"' Demo
Use jq to extract sublist into a single line
From, jq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + "," + .DomainName' << EOF { "DistributionList": { "Items": [ { "Id": "EG3MOA", "Status": "Deployed", "LastModifiedTime": "2022-12-03T19:32:35.007000+00:00", "DomainName": "a***.cloudfront.net", "Aliases": { "Quantity": 1, "Items": [ "a.domain.tld", "b.domain.tld" ] } }, { "Id": "EG3MOB", "Status": "Deployed", "LastModifiedTime": "2022-12-03T19:32:35.007000+00:00", "DomainName": "b***.cloudfront.net", "Aliases": { "Quantity": 1, "Items": [ "c.domain.tld", "d.domain.tld" ] } } ] } } EOF It yields: "EG3MOA,a***.cloudfront.net" "EG3MOB,b***.cloudfront.net" How would I also get the `Alias Items, so that I have: "EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'" "EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'"
[ "To extract the Aliases.Items array and combine it into a single string, you can use the join() method in jq. For example, this jq filter would extract the Id, DomainName, and Aliases.Items values and combine them into a single string, with the Aliases.Items values joined together with a comma:\njq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + \",\" + .DomainName + \",'\" + (.Aliases.Items | join(\",\")) + \"'\"\n\nHere's an example of how you could use this filter in your command:\njq '.DistributionList.Items[] | select(.Aliases.Items != null) | .Id + \",\" + .DomainName + \",'\" + (.Aliases.Items | join(\",\")) + \"'\" << EOF\n{\n\"DistributionList\": {\n \"Items\": [\n {\n \"Id\": \"EG3MOA\",\n \"Status\": \"Deployed\",\n \"LastModifiedTime\": \"2022-12-03T19:32:35.007000+00:00\",\n \"DomainName\": \"a***.cloudfront.net\",\n \"Aliases\": {\n \"Quantity\": 1,\n \"Items\": [\n \"a.domain.tld\",\n \"b.domain.tld\"\n ]\n }\n },\n {\n \"Id\": \"EG3MOB\",\n \"Status\": \"Deployed\",\n \"LastModifiedTime\": \"2022-12-03T19:32:35.007000+00:00\",\n \"DomainName\": \"b***.cloudfront.net\",\n \"Aliases\": {\n \"Quantity\": 1,\n \"Items\": [\n \"c.domain.tld\",\n \"d.domain.tld\"\n ]\n }\n }\n ]\n }\n}\nEOF\n\nThis should output the following:\n\"EG3MOA,a***.cloudfront.net,'a.domain.tld,b.domain.tld'\"\n\"EG3MOB,b***.cloudfront.net,'c.domain.tld,d.domain.tld'\"\n\n", "If you are struggling to enclose an apostrophe ' with JSON string quotes \" withing a jq filter enclosed again by apostrophes, you can use the codepoint notation instead: \\u0027\njq '… | \"\\(.Id),\\(.DomainName),\\u0027\\(.Aliases.Items | join(\",\"))\\u0027\"'\n\nDemo\n" ]
[ 1, 1 ]
[]
[]
[ "amazon_web_services", "bash", "jq" ]
stackoverflow_0074671244_amazon_web_services_bash_jq.txt
Q: Sound Not Recorded in GUVCView - Possible ALSA/JACK Issue I can't seem to record sound on any integrated (Using Linux Manjaro) Video/Audio recorder. I have tried using GUVCView from the command line and I get the following error: V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory) attempt to connect to server failed connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory) attempt to connect to server failed ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory) attempt to connect to server failed V4L2_CORE: (jpeg decoder) error while decoding frame I have been able to record sound with the sound recorder app. I can record video with GUVCView, but no there is no sound recorded along with the video. I see that ALSA and JACK errors are generating. A pull of the logs with inxi -Fxzc0 gives: Sound Server-1: ALSA v: k5.11.19-1-MANJARO running: yes Sound Server-2: JACK v: 0.125.0 running: no Sound Server-3: PulseAudio v: 14.2 running: yes Sound Server-4: PipeWire v: 0.3.28 running: yes Not sure what to do next to get integrated sound recording with this application. Edit: I have tried turning on Jack and then attempting to record with GUVCView. From the command line: GUVCVIEW: version 2.0.6 V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (jpeg decoder) error while decoding frame GUVCVIEW: (status) saving video to /home/avltbyzn/Videos/Webcam/video-37.mkv ENCODER: add stream 0 to stream list ENCODER: add stream 1 to stream list ENCODER: (matroska) add seekhead entry 0 (max 10) ENCODER: (matroska) add seekhead entry 1 (max 10) AUDIO: Pulseaudio pa_stream_get_latency() failed ENCODER: (matroska) closing context ENCODER: (matroska) closing cluster ENCODER: (matroska)writing cues ENCODER: (matroska)add seekhead ENCODER: (matroska) add seekhead entry 2 (max 10) ENCODER: (matroska)write seekhead ENCODER: (matroska) end duration = 9932 (9932.000000) A: Probably someone at https://sourceforge.net/projects/guvcview/ would know. Click on tickets and add your question there. It could use more documentation like everything.
Sound Not Recorded in GUVCView - Possible ALSA/JACK Issue
I can't seem to record sound on any integrated (Using Linux Manjaro) Video/Audio recorder. I have tried using GUVCView from the command line and I get the following error: V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2660:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory) attempt to connect to server failed connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory) attempt to connect to server failed ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port ALSA lib pcm_oss.c:377:(_snd_pcm_oss_open) Unknown field port ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card ALSA lib pcm_usb_stream.c:486:(_snd_pcm_usb_stream_open) Invalid type for card connect(2) call to /dev/shm/jack-1000/default/jack_0 failed (err=No such file or directory) attempt to connect to server failed V4L2_CORE: (jpeg decoder) error while decoding frame I have been able to record sound with the sound recorder app. I can record video with GUVCView, but no there is no sound recorded along with the video. I see that ALSA and JACK errors are generating. A pull of the logs with inxi -Fxzc0 gives: Sound Server-1: ALSA v: k5.11.19-1-MANJARO running: yes Sound Server-2: JACK v: 0.125.0 running: no Sound Server-3: PulseAudio v: 14.2 running: yes Sound Server-4: PipeWire v: 0.3.28 running: yes Not sure what to do next to get integrated sound recording with this application. Edit: I have tried turning on Jack and then attempting to record with GUVCView. From the command line: GUVCVIEW: version 2.0.6 V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (UVCIOC_CTRL_MAP) Error: No such file or directory V4L2_CORE: (jpeg decoder) error while decoding frame GUVCVIEW: (status) saving video to /home/avltbyzn/Videos/Webcam/video-37.mkv ENCODER: add stream 0 to stream list ENCODER: add stream 1 to stream list ENCODER: (matroska) add seekhead entry 0 (max 10) ENCODER: (matroska) add seekhead entry 1 (max 10) AUDIO: Pulseaudio pa_stream_get_latency() failed ENCODER: (matroska) closing context ENCODER: (matroska) closing cluster ENCODER: (matroska)writing cues ENCODER: (matroska)add seekhead ENCODER: (matroska) add seekhead entry 2 (max 10) ENCODER: (matroska)write seekhead ENCODER: (matroska) end duration = 9932 (9932.000000)
[ "Probably someone at https://sourceforge.net/projects/guvcview/ would know. Click on tickets and add your question there. It could use more documentation like everything.\n" ]
[ 0 ]
[]
[]
[ "alsa", "audio_recording", "jack" ]
stackoverflow_0067775351_alsa_audio_recording_jack.txt
Q: How to access the first two elements for each product_catogory I have already sorted the dataframe(dfDogNew) based on product_category and quantity_sold. Now I want to access the first two most sold product in each product category, how can I achieve this? I have written a for loop to access them, but the system tells me there is a key error, does anyone can help me on this? Thank you! Also, if it only has one product in the dfDogNew, then it will only return one row, I assume there should be no difference if I set the slicing as [:2], pandas will automatically pass to the next category there is only 1 product in the previous cstegory? I will attach my for loop code below: for i in product_category: for g in dfDogNew['product_category']: if i == g: finaldf = dfDogNew[dfDogNew[g]].iloc[:2] else: pass sorted dataframe based on product_category and quantity_sold list of each product category for loop attempt to access the first two elements out of each category error I have listed all my attempts in the previous description. A: It looks like you're trying to filter your DataFrame to get the first two rows for each unique value of the product_category column. One way to do this is to use the DataFrame.groupby method, which allows you to group your data by a particular column and then apply a function to each group. In your case, you can group your data by the product_category column and then apply the DataFrame.head method to each group to get the first two rows of each group. Here is an example of how you could do this: # Group the data by the 'product_category' column groups = dfDogNew.groupby("product_category") # Apply the head method to each group to get the first two rows finaldf = groups.head(2) The finaldf DataFrame that is returned will contain the first two rows for each unique value of the product_category column in your original DataFrame. Note that this approach does not require a for loop, and is generally more efficient than looping over the rows of your DataFrame. If you only want to include rows from your original DataFrame that have a product_category value that is present in the product_category array, you can filter your DataFrame using the DataFrame.isin method before grouping it. For example: # Filter the DataFrame to include only rows with a 'product_category' # value that is present in the 'product_category' array dfDogNew = dfDogNew[dfDogNew["product_category"].isin(product_category)] # Group the data by the 'product_category' column groups = dfDogNew.groupby("product_category") # Apply the head method to each group to get the first two rows finaldf = groups.head(2) This will include only rows in the dfDogNew DataFrame that have a product_category value that is present in the product_category array, and then group and filter the data as described above. Note that when using the DataFrame.head method, if there are fewer than two rows in a group, the resulting DataFrame will only include the available rows. So, if a product_category value only has one row in your original DataFrame, the resulting finaldf DataFrame will only include that one row for that category. You do not need to worry about handling this case separately.
How to access the first two elements for each product_catogory
I have already sorted the dataframe(dfDogNew) based on product_category and quantity_sold. Now I want to access the first two most sold product in each product category, how can I achieve this? I have written a for loop to access them, but the system tells me there is a key error, does anyone can help me on this? Thank you! Also, if it only has one product in the dfDogNew, then it will only return one row, I assume there should be no difference if I set the slicing as [:2], pandas will automatically pass to the next category there is only 1 product in the previous cstegory? I will attach my for loop code below: for i in product_category: for g in dfDogNew['product_category']: if i == g: finaldf = dfDogNew[dfDogNew[g]].iloc[:2] else: pass sorted dataframe based on product_category and quantity_sold list of each product category for loop attempt to access the first two elements out of each category error I have listed all my attempts in the previous description.
[ "It looks like you're trying to filter your DataFrame to get the first two rows for each unique value of the product_category column. One way to do this is to use the DataFrame.groupby method, which allows you to group your data by a particular column and then apply a function to each group.\nIn your case, you can group your data by the product_category column and then apply the DataFrame.head method to each group to get the first two rows of each group. Here is an example of how you could do this:\n# Group the data by the 'product_category' column\ngroups = dfDogNew.groupby(\"product_category\")\n\n# Apply the head method to each group to get the first two rows\nfinaldf = groups.head(2)\n\nThe finaldf DataFrame that is returned will contain the first two rows for each unique value of the product_category column in your original DataFrame. Note that this approach does not require a for loop, and is generally more efficient than looping over the rows of your DataFrame.\nIf you only want to include rows from your original DataFrame that have a product_category value that is present in the product_category array, you can filter your DataFrame using the DataFrame.isin method before grouping it. For example:\n# Filter the DataFrame to include only rows with a 'product_category'\n# value that is present in the 'product_category' array\ndfDogNew = dfDogNew[dfDogNew[\"product_category\"].isin(product_category)]\n\n# Group the data by the 'product_category' column\ngroups = dfDogNew.groupby(\"product_category\")\n\n# Apply the head method to each group to get the first two rows\nfinaldf = groups.head(2)\n\nThis will include only rows in the dfDogNew DataFrame that have a product_category value that is present in the product_category array, and then group and filter the data as described above.\nNote that when using the DataFrame.head method, if there are fewer than two rows in a group, the resulting DataFrame will only include the available rows. So, if a product_category value only has one row in your original DataFrame, the resulting finaldf DataFrame will only include that one row for that category. You do not need to worry about handling this case separately.\n" ]
[ 1 ]
[]
[]
[ "numpy_slicing", "pandas", "python" ]
stackoverflow_0074671202_numpy_slicing_pandas_python.txt
Q: Displaying text onto pygame window from file using readline() I'm currently trying to read text from a .txt file then display it onto a pygame window. The problem I'm facing is that it just displays nothing at all when I try to read through the whole txt file using a readline() loop. When I run the code below, it prints all the lines to the terminal but doesn't display it onto the pygame window. import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode([800,600]) red = (255,0,0) yellow = (255, 191, 0) file = open('file.txt') count = 0 while True: count += 1 # Get next line from file line = file.readline() # if line is empty # end of file is reached if not line: break print("Line{}: {}".format(count, line.strip())) file.close() centerx, centery = screen.get_rect().centerx, screen.get_rect().centery deltaY = centery + 50 # adjust so it goes below screen start running =True while running: for event in pygame.event.get(): if event.type == QUIT: running = False screen.fill(0) deltaY-= 1 i=0 msg_list=[] pos_list=[] pygame.time.delay(10) font = pygame.font.SysFont('impact', 30) for line in line.split('\n'): msg=font.render(line, True, yellow) msg_list.append(msg) pos= msg.get_rect(center=(centerx, centery+deltaY+30*i)) pos_list.append(pos) i=i+1 for j in range(i): screen.blit(msg_list[j], pos_list[j]) pygame.display.update() pygame.quit()` What I've tried to do is use a different way to read all the text from the file but this just ends up printing the very last line in the .txt file opposed to displaying the whole thing. I believe using the readline() method would be much more effiecent as that reads the file line by line and then displays it onto the pygame window. It also might be helpful to know I am trying to display the text line by line on the window such as: hello bonjour hola welcome file = open('file.txt') for line in file: movie_credits = line file.close() centerx, centery = screen.get_rect().centerx, screen.get_rect().centery deltaY = centery + 50 # adjust so it goes below screen start running =True while running: for event in pygame.event.get(): if event.type == QUIT: running = False screen.fill(0) deltaY-= 1 i=0 msg_list=[] pos_list=[] pygame.time.delay(10) font = pygame.font.SysFont('impact', 30) for line in movie_credits.split('\n'): msg=font.render(line, True, yellow) msg_list.append(msg) pos= msg.get_rect(center=(centerx, centery+deltaY+30*i)) pos_list.append(pos) i=i+1 for j in range(i): screen.blit(msg_list[j], pos_list[j]) pygame.display.update() pygame.quit() A: You have to add the lines read from the file to a list (see How to read a file line-by-line into a list?): list_of_lines = [] with open('file.txt') as file: list_of_lines = [line.rstrip() for line in file] After that you can render the text lines from the list: font = pygame.font.SysFont('impact', 30) msg_list = [] for line in list_of_lines: msg = font.render(line, True, yellow) msg_list.append(msg) Complete example: import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode([800,600]) clock = pygame.time.Clock() red = (255,0,0) yellow = (255, 191, 0) list_of_lines = [] with open('file.txt') as file: list_of_lines = [line.rstrip() for line in file] file.close() font = pygame.font.SysFont('impact', 30) msg_list = [] for line in list_of_lines: msg = font.render(line, True, yellow) msg_list.append(msg) centerx, centery = screen.get_rect().centerx, screen.get_rect().centery deltaY = centery + 50 # adjust so it goes below screen start running =True while running: clock.tick(100) for event in pygame.event.get(): if event.type == QUIT: running = False screen.fill(0) deltaY -= 1 for i, msg in enumerate(msg_list): pos = msg.get_rect(center=(centerx, centery + deltaY + 30 * i)) screen.blit(msg, pos) pygame.display.update() pygame.quit()
Displaying text onto pygame window from file using readline()
I'm currently trying to read text from a .txt file then display it onto a pygame window. The problem I'm facing is that it just displays nothing at all when I try to read through the whole txt file using a readline() loop. When I run the code below, it prints all the lines to the terminal but doesn't display it onto the pygame window. import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode([800,600]) red = (255,0,0) yellow = (255, 191, 0) file = open('file.txt') count = 0 while True: count += 1 # Get next line from file line = file.readline() # if line is empty # end of file is reached if not line: break print("Line{}: {}".format(count, line.strip())) file.close() centerx, centery = screen.get_rect().centerx, screen.get_rect().centery deltaY = centery + 50 # adjust so it goes below screen start running =True while running: for event in pygame.event.get(): if event.type == QUIT: running = False screen.fill(0) deltaY-= 1 i=0 msg_list=[] pos_list=[] pygame.time.delay(10) font = pygame.font.SysFont('impact', 30) for line in line.split('\n'): msg=font.render(line, True, yellow) msg_list.append(msg) pos= msg.get_rect(center=(centerx, centery+deltaY+30*i)) pos_list.append(pos) i=i+1 for j in range(i): screen.blit(msg_list[j], pos_list[j]) pygame.display.update() pygame.quit()` What I've tried to do is use a different way to read all the text from the file but this just ends up printing the very last line in the .txt file opposed to displaying the whole thing. I believe using the readline() method would be much more effiecent as that reads the file line by line and then displays it onto the pygame window. It also might be helpful to know I am trying to display the text line by line on the window such as: hello bonjour hola welcome file = open('file.txt') for line in file: movie_credits = line file.close() centerx, centery = screen.get_rect().centerx, screen.get_rect().centery deltaY = centery + 50 # adjust so it goes below screen start running =True while running: for event in pygame.event.get(): if event.type == QUIT: running = False screen.fill(0) deltaY-= 1 i=0 msg_list=[] pos_list=[] pygame.time.delay(10) font = pygame.font.SysFont('impact', 30) for line in movie_credits.split('\n'): msg=font.render(line, True, yellow) msg_list.append(msg) pos= msg.get_rect(center=(centerx, centery+deltaY+30*i)) pos_list.append(pos) i=i+1 for j in range(i): screen.blit(msg_list[j], pos_list[j]) pygame.display.update() pygame.quit()
[ "You have to add the lines read from the file to a list (see How to read a file line-by-line into a list?):\nlist_of_lines = []\nwith open('file.txt') as file:\n list_of_lines = [line.rstrip() for line in file]\n\nAfter that you can render the text lines from the list:\nfont = pygame.font.SysFont('impact', 30)\nmsg_list = []\nfor line in list_of_lines:\n msg = font.render(line, True, yellow)\n msg_list.append(msg)\n\n\nComplete example:\n\nimport pygame\nfrom pygame.locals import *\n\npygame.init()\nscreen=pygame.display.set_mode([800,600])\nclock = pygame.time.Clock()\n\nred = (255,0,0)\nyellow = (255, 191, 0)\n\nlist_of_lines = []\nwith open('file.txt') as file:\n list_of_lines = [line.rstrip() for line in file]\nfile.close()\n\nfont = pygame.font.SysFont('impact', 30)\nmsg_list = []\nfor line in list_of_lines:\n msg = font.render(line, True, yellow)\n msg_list.append(msg)\n\ncenterx, centery = screen.get_rect().centerx, screen.get_rect().centery\ndeltaY = centery + 50 # adjust so it goes below screen start\n\nrunning =True\nwhile running:\n clock.tick(100)\n for event in pygame.event.get():\n if event.type == QUIT:\n running = False\n\n screen.fill(0)\n \n deltaY -= 1\n for i, msg in enumerate(msg_list):\n pos = msg.get_rect(center=(centerx, centery + deltaY + 30 * i))\n screen.blit(msg, pos)\n \n pygame.display.update()\n\npygame.quit()\n\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074671176_pygame_python.txt
Q: C++: Always prefer value initialization over default initialization? If I understand correctly, value initialization T obj {}; uses the user-define constructor while default initialization T obj; either uses the user-define constructor or leaves obj uninitialized (i.e. undefined). Since having uninitialized values is in general bad style, should we always prefer value initialization over default initialization? Is there any scenario where default initialization is actually better than value initialization? A: T obj; either uses the user-define constructor or leaves obj uninitialized (i.e. undefined). obj in this case is initialised. Moreover all non-static members of class type are also default-initialised and only non-static members of built-in types (pointers, int, char, etc...) are left with indeterminate value. That means that required memory is allocated for those members anyway, but no extra effort was done to set them to any specific value (my personal analogy from C programming language is malloc vs calloc functions). T obj {}; uses the user-define constructor while default initialization T obj; either uses the user-define constructor or leaves obj uninitialized If a user defined constructor is provided, both default initialisation and value initialisation ({}) invoke the same constructor and have the same effect (depending on how the constructor is implemented). If there is no user-defined default constructor (or it's defined with default keyword) and no constructors that take a std::initializer_list parameter then value initialisation ({}) ensures that all non-static members are value-initialised, while default initialisation ensures that the members are default-initialised (for primitives it means their value is indeterminate). should we always prefer value initialization over default initialization? Zero-initialisation is an additional computation, and in C++ you don't pay for what you don't use, so in case you don't need some parts of your class to have determinate value, you can use default initialisation (T obj) instead of value initialisation (T obj{}) to buy some computation power. A: One key difference between value-initialization and default-initialization is that value-initialization guarantees that an object is properly initialized with a default value, whereas default-initialization does not provide this guarantee. This means that value-initialization is safer and more reliable, because it ensures that an object is always in a well-defined state. Another difference between value-initialization and default-initialization is that value-initialization can be used to initialize objects of any type, including built-in types, user-defined types, and abstract types, whereas default-initialization is only applicable to objects of non-abstract types. This means that value-initialization is more versatile and flexible, because it can be used in a wider range of situations. Overall, the choice between value-initialization and default-initialization depends on the specific needs and requirements of the situation. In general, value-initialization is a safer and more reliable way to initialize objects, but it may require more code and may not be applicable in all cases. Default-initialization is a simpler and more concise way to initialize objects, but it can lead to unpredictable behavior if the object is not properly initialized. A: Yes, you are correct that value initialization with T obj {}; will always use the user-defined constructor to initialize the object, while default initialization with T obj; may either use the user-defined constructor or leave the object uninitialized (i.e. with an indeterminate value). In general, it is good practice to avoid using uninitialized values, as they can lead to undefined behavior in your program. Therefore, you should prefer value initialization over default initialization whenever possible. There are a few scenarios where default initialization may be necessary or desirable, however. For example, if you are declaring a large array of objects and want to initialize each element with the default constructor, default initialization can be more efficient than value initialization, because it does not require calling the user-defined constructor for each element. In this case, default initialization can be a useful optimization. Another scenario where default initialization may be useful is when you are declaring a class or struct that contains other objects as members, and you want to initialize the member objects with their default constructors. In this case, default initialization can be useful because it allows you to initialize the member objects without explicitly calling their default constructors in the class or struct's initializer list. Here is an example of how default initialization can be used in this way: struct MyStruct { int a; std::string b; std::vector<double> c; }; int main() { // Use default initialization to initialize the member objects // with their default constructors MyStruct s; // s.a will be uninitialized (i.e. indeterminate) // s.b will be initialized to the empty string // s.c will be initialized to an empty vector } In this example, the MyStruct struct contains three member objects - an int, a std::string, and a std::vector. When we declare an instance of MyStruct using default initialization, the int member a will be left uninitialized, while the std::string member b and the std::vector member c will be initialized with their default constructors. Overall, while default initialization can be useful in some cases, it should generally be avoided in favor of value initialization, to ensure that your objects are always properly initialized and avoid undefined behavior in your program.
C++: Always prefer value initialization over default initialization?
If I understand correctly, value initialization T obj {}; uses the user-define constructor while default initialization T obj; either uses the user-define constructor or leaves obj uninitialized (i.e. undefined). Since having uninitialized values is in general bad style, should we always prefer value initialization over default initialization? Is there any scenario where default initialization is actually better than value initialization?
[ "\nT obj; either uses the user-define constructor or leaves obj uninitialized (i.e. undefined).\n\nobj in this case is initialised. Moreover all non-static members of class type are also default-initialised and only non-static members of built-in types (pointers, int, char, etc...) are left with indeterminate value. That means that required memory is allocated for those members anyway, but no extra effort was done to set them to any specific value (my personal analogy from C programming language is malloc vs calloc functions).\n\nT obj {}; uses the user-define constructor while default initialization T obj; either uses the user-define constructor or leaves obj uninitialized\n\nIf a user defined constructor is provided, both default initialisation and value initialisation ({}) invoke the same constructor and have the same effect (depending on how the constructor is implemented).\nIf there is no user-defined default constructor (or it's defined with default keyword) and no constructors that take a std::initializer_list parameter then value initialisation ({}) ensures that all non-static members are value-initialised, while default initialisation ensures that the members are default-initialised (for primitives it means their value is indeterminate).\n\nshould we always prefer value initialization over default initialization?\n\nZero-initialisation is an additional computation, and in C++ you don't pay for what you don't use, so in case you don't need some parts of your class to have determinate value, you can use default initialisation (T obj) instead of value initialisation (T obj{}) to buy some computation power.\n", "One key difference between value-initialization and default-initialization is that value-initialization guarantees that an object is properly initialized with a default value, whereas default-initialization does not provide this guarantee. This means that value-initialization is safer and more reliable, because it ensures that an object is always in a well-defined state.\nAnother difference between value-initialization and default-initialization is that value-initialization can be used to initialize objects of any type, including built-in types, user-defined types, and abstract types, whereas default-initialization is only applicable to objects of non-abstract types. This means that value-initialization is more versatile and flexible, because it can be used in a wider range of situations.\nOverall, the choice between value-initialization and default-initialization depends on the specific needs and requirements of the situation. In general, value-initialization is a safer and more reliable way to initialize objects, but it may require more code and may not be applicable in all cases. Default-initialization is a simpler and more concise way to initialize objects, but it can lead to unpredictable behavior if the object is not properly initialized.\n", "Yes, you are correct that value initialization with T obj {}; will always use the user-defined constructor to initialize the object, while default initialization with T obj; may either use the user-defined constructor or leave the object uninitialized (i.e. with an indeterminate value).\nIn general, it is good practice to avoid using uninitialized values, as they can lead to undefined behavior in your program. Therefore, you should prefer value initialization over default initialization whenever possible.\nThere are a few scenarios where default initialization may be necessary or desirable, however. For example, if you are declaring a large array of objects and want to initialize each element with the default constructor, default initialization can be more efficient than value initialization, because it does not require calling the user-defined constructor for each element. In this case, default initialization can be a useful optimization.\nAnother scenario where default initialization may be useful is when you are declaring a class or struct that contains other objects as members, and you want to initialize the member objects with their default constructors. In this case, default initialization can be useful because it allows you to initialize the member objects without explicitly calling their default constructors in the class or struct's initializer list.\nHere is an example of how default initialization can be used in this way:\nstruct MyStruct {\n int a;\n std::string b;\n std::vector<double> c;\n};\n\nint main() {\n // Use default initialization to initialize the member objects\n // with their default constructors\n MyStruct s;\n\n // s.a will be uninitialized (i.e. indeterminate)\n // s.b will be initialized to the empty string\n // s.c will be initialized to an empty vector\n}\n\nIn this example, the MyStruct struct contains three member objects - an int, a std::string, and a std::vector. When we declare an instance of MyStruct using default initialization, the int member a will be left uninitialized, while the std::string member b and the std::vector member c will be initialized with their default constructors.\nOverall, while default initialization can be useful in some cases, it should generally be avoided in favor of value initialization, to ensure that your objects are always properly initialized and avoid undefined behavior in your program.\n" ]
[ 2, 1, 0 ]
[ "Value initialization is generally preferred over default initialization because it guarantees that the object is properly initialized with a defined value. This is particularly important for built-in types, such as integers and floats, which have undefined values when default-initialized.\nFor example, the following code will print the value 0 when using value initialization, but it may print an undefined value when using default initialization:\nint a {}; // value initialization\nstd::cout << a << std::endl;\n\nint b; // default initialization\nstd::cout << b << std::endl;\n\nValue initialization is also preferred because it is less error-prone and more consistent than default initialization.\nFor example, the following code will compile and run without any issues when using value initialization, but it will produce a compile-time error when using default initialization:\nstruct S {\nS() {}\n};\n\nint main() {\nS s1 {}; // value initialization\nS s2; // default initialization - compile-time error\n\nreturn 0;\n}\n\nTherefore, it is generally recommended to use value initialization over default initialization in C++.\n" ]
[ -2 ]
[ "c++", "c++17" ]
stackoverflow_0074671171_c++_c++17.txt
Q: Getting Uncaught RangeError: Maximum call stack size exceeded in React I'm a beginner with React and I have been coding a project for one of the courses in uni. However, I have been now struggling for quite some time with following error: Uncaught RangeError: Maximum call stack size exceeded. I have tried to find a solution with no luck. Here is my code for the React component that causes the error: ` import { Container } from "react-bootstrap" import { useParams } from "react-router" import apiService from "../services/apiService" import { useEffect, useState } from "react" import Spinner from 'react-bootstrap/Spinner'; const GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY export const TreeProfile = (props) => { const [tree, setTree] = useState({}) const [fetching, setFetching] = useState(true) const [zoom, setZoom] = useState("12") const [location, setLocation] = useState({latitude: "", longitude: ""}) let { id } = useParams() const handleZoomChange2 = (event) => { console.log(event.target.value) setZoom(event.target.value) } console.log("Called TreeProfile") useEffect(() => { console.log("id", id) apiService.getOne(id).then(t => { console.log("data", t) setTree(t) setLocation({latitude: t.location.latitude, longitude: t.location.longitude}) setFetching(false) }) }, []) return ( <Container className="treeprofile-page"> { fetching === false ? <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' /> : <Spinner animation="border" variant="primary" /> } <h1>{tree.name}</h1> { fetching === false ? <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3> : null } <h3>Planted by {tree.user}</h3> { fetching === false ? <div> <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' /> </div> : null } <div> <input className="m-3" type="range" min="1" max="16" value={zoom} onChange={handleZoomChange2} /> </div> <button type="button" className="btn btn-primary" >Add update</button> </Container> ) } ` The error happens every time I try to update the zoom level by sliding the slider, which calls handleZoomChange2 function that sets the state. I have other component in different route with the same functionality and it works fine. However, this one for some reason causes the error constantly. The apiService fetches the data with axios from the backend, which in turn fetches the data from MongoDB. I tried to update zoom level by sliding the slider input, which calls on handleZoomChange2 setting a new state to the zoom. However, the code throws an error Maximum call stack size exceeded. Please, help! Error: TreeProfile.js:38 Uncaught RangeError: Maximum call stack size exceeded at TreeProfile (TreeProfile.js:38:1) at renderWithHooks (react-dom.development.js:16305:1) at updateFunctionComponent (react-dom.development.js:19588:1) at beginWork (react-dom.development.js:21601:1) at beginWork$1 (react-dom.development.js:27426:1) at performUnitOfWork (react-dom.development.js:26557:1) at workLoopSync (react-dom.development.js:26466:1) at renderRootSync (react-dom.development.js:26434:1) at recoverFromConcurrentError (react-dom.development.js:25850:1) at performSyncWorkOnRoot (react-dom.development.js:26096:1) A: In case somebody stumbles upon this, here's the solution: Cause of the problem Encoding of the image from array buffer tree.image.data.data to base64 was causing the error of Uncaught RangeError: Maximum call stack size exceeded. I'm not quite certain why exactly, somebody smarted than me may explain it. <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' /> Solution I found the solution to this problem from this Stackoverflow thread. There they discuss the problem more in detail, however, here is the solution that worked for me. const _arrayBufferToBase64 = ( buffer ) => { var binary = ''; var bytes = new Uint8Array( buffer ); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode( bytes[ i ] ); } return window.btoa( binary ); } here the buffer is tree.image.data.data (the array buffer of unit8array) and the function returns base64 encoded result. My code after these changes looks following import { Container } from "react-bootstrap" import { useParams } from "react-router" import apiService from "../services/apiService" import { useEffect, useState } from "react" import Spinner from 'react-bootstrap/Spinner'; const GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY export const TreeProfile = (props) => { const [tree, setTree] = useState(null) const [fetching, setFetching] = useState(true) const [zoom, setZoom] = useState("12") const [location, setLocation] = useState({latitude: "", longitude: ""}) let { id } = useParams() console.log("Called TreeProfile") console.log("fetching", fetching) useEffect(() => { console.log("id", id) apiService.getOne(id).then(t => { console.log("data", t) setTree(t) setLocation({latitude: t.location.latitude, longitude: t.location.longitude}) setFetching(false) }) }, []) const handleZoomChange2 = (event) => { console.log(event.target.value) setZoom(event.target.value) } const test = (event) => { console.log(event.target.value) setFetching(!fetching) } const _arrayBufferToBase64 = ( buffer ) => { var binary = ''; var bytes = new Uint8Array( buffer ); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode( bytes[ i ] ); } return window.btoa( binary ); } if (tree) { return ( <Container className="treeprofile-page"> <div> <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${_arrayBufferToBase64(tree.image.data.data)}`} alt='' /> <h1>{tree.name}</h1> <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3> <h3>Planted by {tree.user}</h3> </div> <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' /> <div> <input className="m-3" type="range" min="1" max="16" value={zoom} onChange={handleZoomChange2} /> </div> <button type="button" className="btn btn-primary" onClick={test} >Add update</button> </Container> ) } else { return ( <Container> <Spinner animation="border" variant="primary" /> </Container> ) } } Hope this helps anybody facing the same problems!
Getting Uncaught RangeError: Maximum call stack size exceeded in React
I'm a beginner with React and I have been coding a project for one of the courses in uni. However, I have been now struggling for quite some time with following error: Uncaught RangeError: Maximum call stack size exceeded. I have tried to find a solution with no luck. Here is my code for the React component that causes the error: ` import { Container } from "react-bootstrap" import { useParams } from "react-router" import apiService from "../services/apiService" import { useEffect, useState } from "react" import Spinner from 'react-bootstrap/Spinner'; const GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY export const TreeProfile = (props) => { const [tree, setTree] = useState({}) const [fetching, setFetching] = useState(true) const [zoom, setZoom] = useState("12") const [location, setLocation] = useState({latitude: "", longitude: ""}) let { id } = useParams() const handleZoomChange2 = (event) => { console.log(event.target.value) setZoom(event.target.value) } console.log("Called TreeProfile") useEffect(() => { console.log("id", id) apiService.getOne(id).then(t => { console.log("data", t) setTree(t) setLocation({latitude: t.location.latitude, longitude: t.location.longitude}) setFetching(false) }) }, []) return ( <Container className="treeprofile-page"> { fetching === false ? <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' /> : <Spinner animation="border" variant="primary" /> } <h1>{tree.name}</h1> { fetching === false ? <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3> : null } <h3>Planted by {tree.user}</h3> { fetching === false ? <div> <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' /> </div> : null } <div> <input className="m-3" type="range" min="1" max="16" value={zoom} onChange={handleZoomChange2} /> </div> <button type="button" className="btn btn-primary" >Add update</button> </Container> ) } ` The error happens every time I try to update the zoom level by sliding the slider, which calls handleZoomChange2 function that sets the state. I have other component in different route with the same functionality and it works fine. However, this one for some reason causes the error constantly. The apiService fetches the data with axios from the backend, which in turn fetches the data from MongoDB. I tried to update zoom level by sliding the slider input, which calls on handleZoomChange2 setting a new state to the zoom. However, the code throws an error Maximum call stack size exceeded. Please, help! Error: TreeProfile.js:38 Uncaught RangeError: Maximum call stack size exceeded at TreeProfile (TreeProfile.js:38:1) at renderWithHooks (react-dom.development.js:16305:1) at updateFunctionComponent (react-dom.development.js:19588:1) at beginWork (react-dom.development.js:21601:1) at beginWork$1 (react-dom.development.js:27426:1) at performUnitOfWork (react-dom.development.js:26557:1) at workLoopSync (react-dom.development.js:26466:1) at renderRootSync (react-dom.development.js:26434:1) at recoverFromConcurrentError (react-dom.development.js:25850:1) at performSyncWorkOnRoot (react-dom.development.js:26096:1)
[ "In case somebody stumbles upon this, here's the solution:\nCause of the problem\nEncoding of the image from array buffer tree.image.data.data to base64 was causing the error of Uncaught RangeError: Maximum call stack size exceeded. I'm not quite certain why exactly, somebody smarted than me may explain it.\n<img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${btoa(String.fromCharCode(...new Uint8Array(tree.image.data.data)))}`} alt='' />\n\nSolution\nI found the solution to this problem from this Stackoverflow thread. There they discuss the problem more in detail, however, here is the solution that worked for me.\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n\nhere the buffer is tree.image.data.data (the array buffer of unit8array) and the function returns base64 encoded result. My code after these changes looks following\nimport { Container } from \"react-bootstrap\"\nimport { useParams } from \"react-router\"\nimport apiService from \"../services/apiService\"\nimport { useEffect, useState } from \"react\"\nimport Spinner from 'react-bootstrap/Spinner';\n\nconst GOOGLE_API_KEY = process.env.REACT_APP_GOOGLE_API_KEY\n\nexport const TreeProfile = (props) => {\n const [tree, setTree] = useState(null)\n const [fetching, setFetching] = useState(true)\n const [zoom, setZoom] = useState(\"12\")\n const [location, setLocation] = useState({latitude: \"\", longitude: \"\"})\n\n let { id } = useParams()\n\n console.log(\"Called TreeProfile\")\n console.log(\"fetching\", fetching)\n\n useEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n }, [])\n \n const handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n }\n const test = (event) => {\n console.log(event.target.value)\n setFetching(!fetching)\n }\n\n const _arrayBufferToBase64 = ( buffer ) => {\n var binary = '';\n var bytes = new Uint8Array( buffer );\n var len = bytes.byteLength;\n for (var i = 0; i < len; i++) {\n binary += String.fromCharCode( bytes[ i ] );\n }\n return window.btoa( binary );\n }\n\n\n if (tree) {\n return (\n <Container className=\"treeprofile-page\">\n <div>\n <img style={{height: '200px', width: '300px'}} src={`data:image/${tree.image.contentType};base64,${_arrayBufferToBase64(tree.image.data.data)}`} alt='' />\n <h1>{tree.name}</h1>\n <h3>Planted on {new Date(tree.createdAt).toDateString()}</h3>\n <h3>Planted by {tree.user}</h3>\n </div>\n <img src={`https://maps.googleapis.com/maps/api/staticmap?center=${location.latitude},${location.longitude}&format=gif&zoom=${zoom}&size=300x200&markers=color:red%7C${location.latitude},${location.longitude}&key=${GOOGLE_API_KEY}`} alt='' />\n <div>\n <input className=\"m-3\" type=\"range\" min=\"1\" max=\"16\" value={zoom} onChange={handleZoomChange2} />\n </div>\n \n <button type=\"button\" className=\"btn btn-primary\" onClick={test} >Add update</button>\n \n </Container>\n )\n } else {\n return (\n <Container>\n <Spinner animation=\"border\" variant=\"primary\" />\n </Container>\n )\n }\n \n}\n\nHope this helps anybody facing the same problems!\n" ]
[ 0 ]
[ "the handleZoomChange2 method is calling itself in an infinite loop. try moving the setZoom call to the end of the function.\nconst handleZoomChange2 = (event) => {\n console.log(event.target.value)\n setZoom(event.target.value)\n}\n\nThis will prevent the function from calling itself again before it has finished executing.\nAlso if you want to update the location state whenever the tree state is updated, you can add it to the dependency array in the useEffect hook.\nuseEffect(() => {\n console.log(\"id\", id)\n apiService.getOne(id).then(t => {\n console.log(\"data\", t)\n setTree(t)\n setLocation({latitude: t.location.latitude, longitude: t.location.longitude})\n setFetching(false)\n })\n}, [tree])\n\nThis will cause the useEffect hook to run again whenever tree is updated.\n" ]
[ -1 ]
[ "express", "hook", "javascript", "reactjs" ]
stackoverflow_0074670396_express_hook_javascript_reactjs.txt
Q: Doesn't redirect when pressing ok in the alert. Why? (Edited)If i copy the code from the answer given bellow from a different user it works perfectly in a new black html file.Something must be going on with my code not allowing the redirection to happend.I will include some of the html/css of the program <header class='header'> <title>Εγγραφή</title> <link rel="stylesheet" type="text/css" href="mystyle.css" > <center><img src="logo.png" alt="LOGO" height=100></center> </header> <div class="text"> <p style="font-family: system-ui; font-size: 15pt;"> <label for="onoma" style="font-size:15pt;">Διεύθυνση*:</label>&nbsp; <input id="address" type="text" name="address" value="" >&nbsp;&nbsp; <p style="font-family: system-ui; font-size: 15pt;"> <div class="text"> <label for="mera" style="font-size:15pt;">Συνθηματικό πρόσβασης*:</label>&nbsp; <input id="password" type="password" name="mera" value="" >&nbsp;&nbsp; <label for="minas" style="font-size:15pt;">Κωδικός πρόσβασης*:</label>&nbsp; <input id="password2" type="password" name="minas" value="" >&nbsp;&nbsp; div align="center"> <input type="reset" value="Reset"> <input type="submit" id="btn" value="submit"> </div> <br><br>&nbsp;<br><br>&nbsp; <script type="text/javascript" src="java.js"></script> CSS body { margin: 0; font-family: system-ui } .logocolor { background-color:cornflowerblue; } .background{ background-color:wheat; } header { background-color: rgb(0, 132, 255); } .text{ text-align:left; text-indent: 150px; } label { font-family: system-ui } .change{ display: flex; } Also the current java function CheckPassword(address, password, password2) { if (password === "" || password2 === "" || address === "") { alert("Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά") } else { alert('message'); window.location = 'newpage.html'; } } function ClickMe() { CheckPassword( document.getElementById('address').value, document.getElementById('password').value, document.getElementById('password2').value ); } document.getElementById('btn').addEventListener("click", function() {ClickMe()}); A: Edit: The answer is updated as per the question's update. Hence it still contains the same reproduced working code sample enquirer provided. It's working as per the snippet and the new codesandbox here. The older one is also still here for you to compare them even there's not much change but rather typos needed to be fixed. I made a couple necessary fixes and changes in order to provide best practices even some parts still same in order to not make it more complicated for you. In order to get an HTML page successfully working, you just need to be sure that; HTML is valid (you may not understand it when you look at it on a regular page but all tags should be closed respectively), All necessary files (Js/CSS) imported within that HTML file accordingly, The HTML page desired to be redirected exists and correctly named besides matching the exact path within the expression. You can also successfully redirect via methods below; window.location.href = 'newPage.html' window.location.replace('newPage.html'); You can take a look at here for their difference. function CheckPassword(address, password, password2) { if (password === "" || password2 === "" || address === "") { alert("Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά") } else { alert('message'); window.location = 'https://stackoverflow.com'; } } function ClickMe() { CheckPassword( document.getElementById('address').value, document.getElementById('password').value, document.getElementById('password2').value ); } document.getElementById('btn').addEventListener("click", function() {ClickMe()}); <input type="text" id="address" /> <input type="text" id="password" /> <input type="text" id="password2" /> <button id="btn">Button</button>
Doesn't redirect when pressing ok in the alert. Why?
(Edited)If i copy the code from the answer given bellow from a different user it works perfectly in a new black html file.Something must be going on with my code not allowing the redirection to happend.I will include some of the html/css of the program <header class='header'> <title>Εγγραφή</title> <link rel="stylesheet" type="text/css" href="mystyle.css" > <center><img src="logo.png" alt="LOGO" height=100></center> </header> <div class="text"> <p style="font-family: system-ui; font-size: 15pt;"> <label for="onoma" style="font-size:15pt;">Διεύθυνση*:</label>&nbsp; <input id="address" type="text" name="address" value="" >&nbsp;&nbsp; <p style="font-family: system-ui; font-size: 15pt;"> <div class="text"> <label for="mera" style="font-size:15pt;">Συνθηματικό πρόσβασης*:</label>&nbsp; <input id="password" type="password" name="mera" value="" >&nbsp;&nbsp; <label for="minas" style="font-size:15pt;">Κωδικός πρόσβασης*:</label>&nbsp; <input id="password2" type="password" name="minas" value="" >&nbsp;&nbsp; div align="center"> <input type="reset" value="Reset"> <input type="submit" id="btn" value="submit"> </div> <br><br>&nbsp;<br><br>&nbsp; <script type="text/javascript" src="java.js"></script> CSS body { margin: 0; font-family: system-ui } .logocolor { background-color:cornflowerblue; } .background{ background-color:wheat; } header { background-color: rgb(0, 132, 255); } .text{ text-align:left; text-indent: 150px; } label { font-family: system-ui } .change{ display: flex; } Also the current java function CheckPassword(address, password, password2) { if (password === "" || password2 === "" || address === "") { alert("Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά") } else { alert('message'); window.location = 'newpage.html'; } } function ClickMe() { CheckPassword( document.getElementById('address').value, document.getElementById('password').value, document.getElementById('password2').value ); } document.getElementById('btn').addEventListener("click", function() {ClickMe()});
[ "Edit: The answer is updated as per the question's update. Hence it still contains the same reproduced working code sample enquirer provided.\nIt's working as per the snippet and the new codesandbox here. The older one is also still here for you to compare them even there's not much change but rather typos needed to be fixed.\nI made a couple necessary fixes and changes in order to provide best practices even some parts still same in order to not make it more complicated for you. In order to get an HTML page successfully working, you just need to be sure that;\n\nHTML is valid (you may not understand it when you look at it on a regular page but all tags should be closed respectively),\nAll necessary files (Js/CSS) imported within that HTML file accordingly,\nThe HTML page desired to be redirected exists and correctly named besides matching the exact path within the expression.\n\nYou can also successfully redirect via methods below;\n\nwindow.location.href = 'newPage.html'\nwindow.location.replace('newPage.html');\n\n\nYou can take a look at here for their difference.\n\n\n\nfunction CheckPassword(address, password, password2) {\n if (password === \"\" || password2 === \"\" || address === \"\") {\n alert(\"Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά\")\n } else {\n alert('message');\n window.location = 'https://stackoverflow.com';\n }\n}\n\nfunction ClickMe() {\n CheckPassword(\n document.getElementById('address').value,\n document.getElementById('password').value,\n document.getElementById('password2').value\n );\n}\n\ndocument.getElementById('btn').addEventListener(\"click\", function() {ClickMe()});\n<input type=\"text\" id=\"address\" />\n<input type=\"text\" id=\"password\" />\n<input type=\"text\" id=\"password2\" />\n\n<button id=\"btn\">Button</button>\n\n\n\n" ]
[ 0 ]
[ "The current web URL is located in window.location.href, not window.location. Here's an example navigation snippet:\n\n\ndocument.getElementById(\"navigate\").addEventListener(\"click\", (e) => {\n window.location.href = \"https://example.com/\";\n})\n<button type=\"button\" id=\"navigate\">Navigate</button>\n\n\n\n\n\nfunction CheckPassword(address, password, password2) {\n if ((password == \"\") || (password2 == \"\") || (address == \"\")) {\n alert(\"Καποιο/Καποια κενά δεν συμπληρώθηκαν σωστά ή ειναι κενά\")\n } else {\n alert('message');\n window.location.href = 'new page.html';\n }\n}\n\nfunction ClickMe() {\n CheckPassword(document.getElementById('password2').value, document.getElementById('password').value, document.getElementById('address').value)\n}\n\ndocument.getElementById('btn').addEventListener(\"click\", function() {\n ClickMe()\n});\n\n\n\nSo your corrected code would use window.location.href instead of window.loaction.\n" ]
[ -1 ]
[ "javascript" ]
stackoverflow_0074671077_javascript.txt
Q: How to merge two groupingBy in java streams? I have a input object @Getter class Txn { private String hash; private String withdrawId; private String depositId; private Integer amount; private String date; } and the output object is @Builder @Getter class UserTxn { private String hash; private String walletId; private String txnType; private Integer amount; } In the Txn object transfers the amount from the withdrawId -> depositId. what I am doing is I am adding all the transactions (Txn objects) in a single amount grouped by hash. but for that I have to make two streams for groupingby withdrawId and second or for depositId and then the third stream for merging them grouping by withdrawId var withdrawStream = txnList.stream().collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -> UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType("WITHDRAW") .amount(withdrawEntrySet.getValue().stream().map(Txn::getAmount).reduce(0, Integer::sum)) .build() )); grouping by depositId var depositStream = txnList.stream().collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getDepositId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -> UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType("DEPOSIT") .amount(withdrawEntrySet.getValue().stream().map(Txn::getAmount).reduce(0, Integer::sum)) .build() )); then merging them again, using deposites - withdraws var res = Stream.concat(withdrawStream, depositStream).collect(Collectors.groupingBy(UserTxn::getHash, LinkedHashMap::new, Collectors.groupingBy(UserTxn::getWalletId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -> { var depositAmount = withdrawEntrySet.getValue().stream().filter(userTxn -> userTxn.txnType.equals("DEPOSIT")).map(UserTxn::getAmount).reduce(0, Integer::sum); var withdrawAmount = withdrawEntrySet.getValue().stream().filter(userTxn -> userTxn.txnType.equals("WITHDRAW")).map(UserTxn::getAmount).reduce(0, Integer::sum); var totalAmount = depositAmount-withdrawAmount; return UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType(totalAmount > 0 ? "DEPOSIT": "WITHDRAW") .amount(totalAmount) .build(); } )); My question is, How can I do this in one stream. Like by somehow groupingBy withdrawId and depositId is one grouping. something like res = txnList.stream() .collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId && Txn::getDepositId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(walletEntrySet -> { var totalAmount = walletEntrySet.getValue().stream().map( txn -> Objects.equals(txn.getDepositId(), walletEntrySet.getKey()) ? txn.getAmount() : (-txn.getAmount())).reduce(0, Integer::sum); return UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(walletEntrySet.getKey()) .txnType("WITHDRAW") .amount(totalAmount) .build(); } )); A: I wouldn’t use this in my code because I think it’s not readable and will be very hard to change and manage in the future(SOLID). But in case you still want this- If I got your design right hash is unique per user and transaction will only have deposit or withdrawal, if so, this will work- You could triple groupBy via collectors chaining like you did in your example. You can create the Txn type via simple map function just check which id is null. Map<String, Map<String, Map<String, List<Txn>>>> groupBy = txnList.stream() .collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getDepositId, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId, LinkedHashMap::new, Collectors.toList())))); then use the logic from your example on this stream. A: TL;DR For those who didn't understand the question, OP wants to generate from each Txn instance (Txn probably stands for transaction) two peaces of data: hash and withdrawId + aggregated amount, and hash and depositId + aggregated amount. And then they want to merge the two parts together (for that reason they were creating the two streams, and then concatenating them). Note: it seems like there's a logical flow in the original code: the same amount gets associated with withdrawId and depositId. Which doesn't reflect that this amount has been taken from one account and transferred to another. Hence, it would make sense if for depositId amount would be used as is, and for withdrawId - negated (i.e. -1 * amount). Collectors.teeing() You can make use of the Java 12 Collector teeing() and internally group stream elements into two distinct Maps: the first one by grouping the stream data by withdrawId and hash. and another one by grouping the data depositId and hash. Teeing expects three arguments: 2 downstream Collectors and a Function combining the results produced by collectors. As the downstream of teeing() we can use a combination of Collectors groupingBy() and summingInt(), the second one is needed to accumulate integer amount of the transaction. Note that there's no need in using nested Collector groupingBy() instead we can create a custom type that would hold id and hash (and its equals/hashCode should be implemented based on the wrapped id and hash). Java 16 record fits into this role perfectly well: public record HashWalletId(String hash, String walletId) {} Instances of HashWalletId would be used as Keys in both intermediate Maps. The finisher function of teeing() would merge the results of the two Maps together. The only thing left is to generate instances of UserTxn out of map entries. List<Txn> txnList = // initializing the list List<UserTxn> result = txnList.stream() .collect(Collectors.teeing( Collectors.groupingBy( txn -> new HashWalletId(txn.getHash(), txn.getWithdrawId()), Collectors.summingInt(txn -> -1 * txn.getAmount())), // because amount has been withdrawn Collectors.groupingBy( txn -> new HashWalletId(txn.getHash(), txn.getDepositId()), Collectors.summingInt(Txn::getAmount)), (map1, map2) -> { map2.forEach((k, v) -> map1.merge(k, v, Integer::sum)); return map1; } )) .entrySet().stream() .map(entry -> UserTxn.builder() .hash(entry.getKey().hash()) .walletId(entry.getKey().walletId()) .txnType(entry.getValue() > 0 ? "DEPOSIT" : "WITHDRAW") .amount(entry.getValue()) .build() ) .toList(); // remove the terminal operation if your goal is to produce a Stream
How to merge two groupingBy in java streams?
I have a input object @Getter class Txn { private String hash; private String withdrawId; private String depositId; private Integer amount; private String date; } and the output object is @Builder @Getter class UserTxn { private String hash; private String walletId; private String txnType; private Integer amount; } In the Txn object transfers the amount from the withdrawId -> depositId. what I am doing is I am adding all the transactions (Txn objects) in a single amount grouped by hash. but for that I have to make two streams for groupingby withdrawId and second or for depositId and then the third stream for merging them grouping by withdrawId var withdrawStream = txnList.stream().collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -> UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType("WITHDRAW") .amount(withdrawEntrySet.getValue().stream().map(Txn::getAmount).reduce(0, Integer::sum)) .build() )); grouping by depositId var depositStream = txnList.stream().collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getDepositId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -> UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType("DEPOSIT") .amount(withdrawEntrySet.getValue().stream().map(Txn::getAmount).reduce(0, Integer::sum)) .build() )); then merging them again, using deposites - withdraws var res = Stream.concat(withdrawStream, depositStream).collect(Collectors.groupingBy(UserTxn::getHash, LinkedHashMap::new, Collectors.groupingBy(UserTxn::getWalletId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(withdrawEntrySet -> { var depositAmount = withdrawEntrySet.getValue().stream().filter(userTxn -> userTxn.txnType.equals("DEPOSIT")).map(UserTxn::getAmount).reduce(0, Integer::sum); var withdrawAmount = withdrawEntrySet.getValue().stream().filter(userTxn -> userTxn.txnType.equals("WITHDRAW")).map(UserTxn::getAmount).reduce(0, Integer::sum); var totalAmount = depositAmount-withdrawAmount; return UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(withdrawEntrySet.getKey()) .txnType(totalAmount > 0 ? "DEPOSIT": "WITHDRAW") .amount(totalAmount) .build(); } )); My question is, How can I do this in one stream. Like by somehow groupingBy withdrawId and depositId is one grouping. something like res = txnList.stream() .collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new, Collectors.groupingBy(Txn::getWithdrawId && Txn::getDepositId, LinkedHashMap::new, Collectors.toList()))) .entrySet().stream().flatMap(hashEntrySet -> hashEntrySet.getValue().entrySet().stream() .map(walletEntrySet -> { var totalAmount = walletEntrySet.getValue().stream().map( txn -> Objects.equals(txn.getDepositId(), walletEntrySet.getKey()) ? txn.getAmount() : (-txn.getAmount())).reduce(0, Integer::sum); return UserTxn.builder() .hash(hashEntrySet.getKey()) .walletId(walletEntrySet.getKey()) .txnType("WITHDRAW") .amount(totalAmount) .build(); } ));
[ "I wouldn’t use this in my code because I think it’s not readable and will be very hard to change and manage in the future(SOLID).\nBut in case you still want this-\nIf I got your design right hash is unique per user and transaction will only have deposit or withdrawal, if so, this will work-\nYou could triple groupBy via collectors chaining like you did in your example.\nYou can create the Txn type via simple map function just check which id is null.\nMap<String, Map<String, Map<String, List<Txn>>>> groupBy = \n txnList.stream()\n .collect(Collectors.groupingBy(Txn::getHash, LinkedHashMap::new,\n Collectors.groupingBy(Txn::getDepositId, LinkedHashMap::new,\n Collectors.groupingBy(Txn::getWithdrawId, LinkedHashMap::new, Collectors.toList()))));\n\nthen use the logic from your example on this stream.\n", "TL;DR\nFor those who didn't understand the question, OP wants to generate from each Txn instance (Txn probably stands for transaction) two peaces of data: hash and withdrawId + aggregated amount, and hash and depositId + aggregated amount.\nAnd then they want to merge the two parts together (for that reason they were creating the two streams, and then concatenating them).\nNote: it seems like there's a logical flow in the original code: the same amount gets associated with withdrawId and depositId. Which doesn't reflect that this amount has been taken from one account and transferred to another. Hence, it would make sense if for depositId amount would be used as is, and for withdrawId - negated (i.e. -1 * amount).\nCollectors.teeing()\nYou can make use of the Java 12 Collector teeing() and internally group stream elements into two distinct Maps:\n\nthe first one by grouping the stream data by withdrawId and hash.\n\nand another one by grouping the data depositId and hash.\n\n\nTeeing expects three arguments: 2 downstream Collectors and a Function combining the results produced by collectors.\nAs the downstream of teeing() we can use a combination of Collectors groupingBy() and summingInt(), the second one is needed to accumulate integer amount of the transaction.\nNote that there's no need in using nested Collector groupingBy() instead we can create a custom type that would hold id and hash (and its equals/hashCode should be implemented based on the wrapped id and hash). Java 16 record fits into this role perfectly well:\npublic record HashWalletId(String hash, String walletId) {}\n\nInstances of HashWalletId would be used as Keys in both intermediate Maps.\nThe finisher function of teeing() would merge the results of the two Maps together.\nThe only thing left is to generate instances of UserTxn out of map entries.\nList<Txn> txnList = // initializing the list\n \nList<UserTxn> result = txnList.stream()\n .collect(Collectors.teeing(\n Collectors.groupingBy(\n txn -> new HashWalletId(txn.getHash(), txn.getWithdrawId()),\n Collectors.summingInt(txn -> -1 * txn.getAmount())), // because amount has been withdrawn\n Collectors.groupingBy(\n txn -> new HashWalletId(txn.getHash(), txn.getDepositId()),\n Collectors.summingInt(Txn::getAmount)),\n (map1, map2) -> {\n map2.forEach((k, v) -> map1.merge(k, v, Integer::sum));\n return map1;\n }\n ))\n .entrySet().stream()\n .map(entry -> UserTxn.builder()\n .hash(entry.getKey().hash())\n .walletId(entry.getKey().walletId())\n .txnType(entry.getValue() > 0 ? \"DEPOSIT\" : \"WITHDRAW\")\n .amount(entry.getValue())\n .build()\n )\n .toList(); // remove the terminal operation if your goal is to produce a Stream\n\n" ]
[ 2, 2 ]
[]
[]
[ "collectors", "groupingby", "hashmap", "java", "java_stream" ]
stackoverflow_0074670924_collectors_groupingby_hashmap_java_java_stream.txt
Q: AWS Lambda with 10 different roles executing it. Can I get their tags? General question here. I have a lambda function that has an assigned role. I also have 10 other roles in my AWS account that need to execute this function. Fine. I can assign those permissions in a policy that they can attach to their role. My question is, I want to know more information inside my lambda function about the 10 different roles that is calling my main lambda function. Is it possible to get the tags of the roles that is trying to execute my function? If so, how A: Yes, it is possible to get the tags of the roles that are calling your Lambda function. In order to do this, you can use the AWS.STS.getCallerIdentity() function. This function returns information about the caller, including the caller's identity, the caller's AWS account ID, and the caller's ARN. You can then use the AWS.IAM.getRole() function to retrieve the role's tags, given its ARN. Here is an example of how you might use these functions to get the tags of the calling role: // First, get the caller's identity const callerIdentity = AWS.STS.getCallerIdentity(); // Then, use the caller's ARN to get the caller's role const role = AWS.IAM.getRole({ RoleName: callerIdentity.arn }); // Finally, retrieve the role's tags const tags = role.Tags; Keep in mind that in order for your Lambda function to be able to call these functions, you will need to grant it permission to do so. You can do this by attaching the appropriate IAM policy to the role that your Lambda function uses.
AWS Lambda with 10 different roles executing it. Can I get their tags?
General question here. I have a lambda function that has an assigned role. I also have 10 other roles in my AWS account that need to execute this function. Fine. I can assign those permissions in a policy that they can attach to their role. My question is, I want to know more information inside my lambda function about the 10 different roles that is calling my main lambda function. Is it possible to get the tags of the roles that is trying to execute my function? If so, how
[ "Yes, it is possible to get the tags of the roles that are calling your Lambda function. In order to do this, you can use the AWS.STS.getCallerIdentity() function. This function returns information about the caller, including the caller's identity, the caller's AWS account ID, and the caller's ARN. You can then use the AWS.IAM.getRole() function to retrieve the role's tags, given its ARN.\nHere is an example of how you might use these functions to get the tags of the calling role:\n// First, get the caller's identity\nconst callerIdentity = AWS.STS.getCallerIdentity();\n\n// Then, use the caller's ARN to get the caller's role\nconst role = AWS.IAM.getRole({ RoleName: callerIdentity.arn });\n\n// Finally, retrieve the role's tags\nconst tags = role.Tags;\n\nKeep in mind that in order for your Lambda function to be able to call these functions, you will need to grant it permission to do so. You can do this by attaching the appropriate IAM policy to the role that your Lambda function uses.\n" ]
[ 0 ]
[]
[]
[ "amazon_iam", "amazon_web_services", "aws_lambda", "python_3.x" ]
stackoverflow_0074670409_amazon_iam_amazon_web_services_aws_lambda_python_3.x.txt
Q: Nestjs swagger array of strings with one parameter When I send only one parameter, I got query result like string, not like string[]. This heppend only from UI swagger, if I send from Postman - it works good. I just want send from swagger-ui one parammeter and got array of string, not string How I can fix it? Help me please. Example1: send one paramenter and in my controller I got string like '25' Example2: when I send 2 parameters in controller I can see array of strings ('25', '21') export class List { @ApiProperty({ isArray: true, type: String, required: false }) @IsOptional() public categories?: string[]; } A: You should try to spread your parameter in a const in services
Nestjs swagger array of strings with one parameter
When I send only one parameter, I got query result like string, not like string[]. This heppend only from UI swagger, if I send from Postman - it works good. I just want send from swagger-ui one parammeter and got array of string, not string How I can fix it? Help me please. Example1: send one paramenter and in my controller I got string like '25' Example2: when I send 2 parameters in controller I can see array of strings ('25', '21') export class List { @ApiProperty({ isArray: true, type: String, required: false }) @IsOptional() public categories?: string[]; }
[ "You should try to spread your parameter in a const in services\n" ]
[ 1 ]
[]
[]
[ "nestjs", "swagger", "swagger_ui" ]
stackoverflow_0074652818_nestjs_swagger_swagger_ui.txt
Q: Find the Gaussian probability density of x for a normal distribution So, I'm supposed to write a function normpdf(x , avg, std) that returns the Gaussian probability density function of x for a normal distribution with mean avg and standard deviation std, with avg = 0 and std = 1. This is what I got so far, but when I click run, I get this message: Input In [95] return pdf ^ SyntaxError: invalid syntax I'm confused on what I did wrong on that part. import numpy as np import math def normpdf(x, avg=0, std=1) : # normal distribution eq exponent = math.exp(-0.5 * ((x - avg) / std) ** 2) pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent) return pdf # set x values x = np.linspace(1, 50) normpdf(x, avg, std) I added the parenthesis here and math.sqrt: pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent) ... but then I got this message: TypeError Traceback (most recent call last) Input In [114], in <cell line: 11>() 9 pdf = (1/(std*math.sqrt(2*math.pi))*exponent) 10 return pdf ---> 11 normpdf(x, avg, std) Input In [114], in normpdf(x, avg, std) 6 def normpdf(x, avg=0, std=1) : 7 #normal distribution eq ----> 8 exponent = math.exp(-0.5*((x-avg)/std)**2) 9 pdf = (1/(std*math.sqrt(2*math.pi))*exponent) 10 return pdf TypeError: only size-1 arrays can be converted to Python scalars A: You don't need the math module. Use just numpy functions: import numpy as np def normpdf(x, avg=0, std=1): exp = np.exp(-0.5 * ((x - avg) / std) ** 2) pdf = (1 / (std * np.sqrt(2 * np.pi)) * exp) return pdf x = np.linspace(1, 50) print(normpdf(x)) The code above will result in: [2.41970725e-001 5.39909665e-002 4.43184841e-003 1.33830226e-004 1.48671951e-006 6.07588285e-009 9.13472041e-012 5.05227108e-015 1.02797736e-018 7.69459863e-023 2.11881925e-027 2.14638374e-032 7.99882776e-038 1.09660656e-043 5.53070955e-050 1.02616307e-056 7.00418213e-064 1.75874954e-071 1.62463604e-079 5.52094836e-088 6.90202942e-097 3.17428155e-106 5.37056037e-116 3.34271444e-126 7.65392974e-137 6.44725997e-148 1.99788926e-159 2.27757748e-171 9.55169454e-184 1.47364613e-196 8.36395161e-210 1.74636626e-223 1.34141967e-237 3.79052640e-252 3.94039628e-267 1.50690472e-282 2.12000655e-298 1.09722105e-314 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000] A: Your implementation of the normal probability density function is almost correct. The issue you're encountering is that you're trying to evaluate the function for an array of values, but the math operations you're using only work with scalar values (single numbers). To fix this, you can either evaluate the function for each value in the array separately, or you can use numpy functions that can operate on arrays. Here's an example of how you could do this using numpy: import numpy as np def normpdf(x, avg=0, std=1): # Compute the exponent exponent = np.exp(-0.5 * ((x - avg) / std) ** 2) # Compute the normalization constant const = 1 / (std * np.sqrt(2 * np.pi)) # Compute the normal probability density function pdf = const * exponent return pdf # Set x values x = np.linspace(1, 50) # Compute the probability density function for the given values of x pdf = normpdf(x, avg, std) # Print the result print(pdf) Note that in this example I used numpy functions for the exponent and square root, which allows the function to operate on arrays of values instead of just scalars. I also used a numpy array for the x values, which means that the function will return an array of probabilities, one for each value of x. A: You are trying to calculate the normal probability density function of an array of values, but the math.exp() function expects a scalar value as input. To solve this issue, you can use the np.exp() function from the NumPy library, which can handle arrays as input and will apply the exponent calculation element-wise. import numpy as np def normpdf(x, avg=0, std=1): # normal distribution eq exponent = np.exp(-0.5 * ((x - avg) / std) ** 2) pdf = (1 / (std * np.sqrt(2 * np.pi)) * exponent) return pdf # set x values x = np.linspace(1, 50) normpdf(x) I replaced the math.exp() and math.sqrt() functions with their NumPy equivalents, np.exp() and np.sqrt(). These functions can handle arrays as input and will return an array of results.
Find the Gaussian probability density of x for a normal distribution
So, I'm supposed to write a function normpdf(x , avg, std) that returns the Gaussian probability density function of x for a normal distribution with mean avg and standard deviation std, with avg = 0 and std = 1. This is what I got so far, but when I click run, I get this message: Input In [95] return pdf ^ SyntaxError: invalid syntax I'm confused on what I did wrong on that part. import numpy as np import math def normpdf(x, avg=0, std=1) : # normal distribution eq exponent = math.exp(-0.5 * ((x - avg) / std) ** 2) pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent) return pdf # set x values x = np.linspace(1, 50) normpdf(x, avg, std) I added the parenthesis here and math.sqrt: pdf = (1 / (std * math.sqrt(2 * math.pi)) * exponent) ... but then I got this message: TypeError Traceback (most recent call last) Input In [114], in <cell line: 11>() 9 pdf = (1/(std*math.sqrt(2*math.pi))*exponent) 10 return pdf ---> 11 normpdf(x, avg, std) Input In [114], in normpdf(x, avg, std) 6 def normpdf(x, avg=0, std=1) : 7 #normal distribution eq ----> 8 exponent = math.exp(-0.5*((x-avg)/std)**2) 9 pdf = (1/(std*math.sqrt(2*math.pi))*exponent) 10 return pdf TypeError: only size-1 arrays can be converted to Python scalars
[ "You don't need the math module. Use just numpy functions:\nimport numpy as np\n\n\ndef normpdf(x, avg=0, std=1):\n exp = np.exp(-0.5 * ((x - avg) / std) ** 2)\n pdf = (1 / (std * np.sqrt(2 * np.pi)) * exp)\n return pdf\n\n\nx = np.linspace(1, 50)\n\nprint(normpdf(x))\n\nThe code above will result in:\n[2.41970725e-001 5.39909665e-002 4.43184841e-003 1.33830226e-004\n 1.48671951e-006 6.07588285e-009 9.13472041e-012 5.05227108e-015\n 1.02797736e-018 7.69459863e-023 2.11881925e-027 2.14638374e-032\n 7.99882776e-038 1.09660656e-043 5.53070955e-050 1.02616307e-056\n 7.00418213e-064 1.75874954e-071 1.62463604e-079 5.52094836e-088\n 6.90202942e-097 3.17428155e-106 5.37056037e-116 3.34271444e-126\n 7.65392974e-137 6.44725997e-148 1.99788926e-159 2.27757748e-171\n 9.55169454e-184 1.47364613e-196 8.36395161e-210 1.74636626e-223\n 1.34141967e-237 3.79052640e-252 3.94039628e-267 1.50690472e-282\n 2.12000655e-298 1.09722105e-314 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000\n 0.00000000e+000 0.00000000e+000]\n\n", "Your implementation of the normal probability density function is almost correct. The issue you're encountering is that you're trying to evaluate the function for an array of values, but the math operations you're using only work with scalar values (single numbers).\nTo fix this, you can either evaluate the function for each value in the array separately, or you can use numpy functions that can operate on arrays. Here's an example of how you could do this using numpy:\nimport numpy as np\n\ndef normpdf(x, avg=0, std=1):\n # Compute the exponent\n exponent = np.exp(-0.5 * ((x - avg) / std) ** 2)\n\n # Compute the normalization constant\n const = 1 / (std * np.sqrt(2 * np.pi))\n\n # Compute the normal probability density function\n pdf = const * exponent\n\n return pdf\n\n# Set x values\nx = np.linspace(1, 50)\n\n# Compute the probability density function for the given values of x\npdf = normpdf(x, avg, std)\n\n# Print the result\nprint(pdf)\n\nNote that in this example I used numpy functions for the exponent and square root, which allows the function to operate on arrays of values instead of just scalars. I also used a numpy array for the x values, which means that the function will return an array of probabilities, one for each value of x.\n", "You are trying to calculate the normal probability density function of an array of values, but the math.exp() function expects a scalar value as input. To solve this issue, you can use the np.exp() function from the NumPy library, which can handle arrays as input and will apply the exponent calculation element-wise.\nimport numpy as np\n\ndef normpdf(x, avg=0, std=1):\n # normal distribution eq\n exponent = np.exp(-0.5 * ((x - avg) / std) ** 2)\n pdf = (1 / (std * np.sqrt(2 * np.pi)) * exponent)\n return pdf\n\n# set x values\nx = np.linspace(1, 50)\n\nnormpdf(x)\n\nI replaced the math.exp() and math.sqrt() functions with their NumPy equivalents, np.exp() and np.sqrt(). These functions can handle arrays as input and will return an array of results.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "gaussian", "normal_distribution", "python" ]
stackoverflow_0074670914_gaussian_normal_distribution_python.txt
Q: C++ multithreaded version of creating vector of random numbers slower than single-threaded version I am trying to write a multi-threaded program to produce a vector of N*NumPerThread uniform random integers, where N is the return value of std::thread::hardware_concurrency() and NumPerThread is the amount of random numbers I want each thread to generate. I created a multi-threaded version: #include <iostream> #include <thread> #include <vector> #include <random> #include <chrono> using Clock = std::chrono::high_resolution_clock; namespace Vars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector<int> RandNums(NumPerThread*N); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); int sz = 0; } using namespace Vars; void AddN(int start) { static std::mutex mtx; std::lock_guard<std::mutex> lock(mtx); for (unsigned int i=start; i<start+NumPerThread; i++) { RandNums[i] = dis(gen); ++sz; } } int main() { auto start_time = Clock::now(); std::vector<std::thread> threads; threads.reserve(N); for (unsigned int i=0; i<N; i++) { threads.emplace_back(std::move(std::thread(AddN, i*NumPerThread))); } for (auto &i: threads) { i.join(); } auto end_time = Clock::now(); std::cout << "\nTime difference = " << std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n"; std::cout << "size = " << sz << '\n'; } and a single-threaded version #include <iostream> #include <thread> #include <vector> #include <random> #include <chrono> using Clock = std::chrono::high_resolution_clock; namespace Vars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector<int> RandNums(NumPerThread*N); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); int sz = 0; } using namespace Vars; void AddN() { for (unsigned int i=0; i<NumPerThread*N; i++) { RandNums[i] = dis(gen); ++sz; } } int main() { auto start_time = Clock::now(); AddN(); auto end_time = Clock::now(); std::cout << "\nTime difference = " << std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n"; std::cout << "size = " << sz << '\n'; } The execution times are more or less the same. I am assuming there is a problem with the multi-threaded version? P.S. I looked at all of the other similar questions here, I don't see how they directly apply to this task... A: Threading is not a magical salve you can rub onto any code that makes it go faster. Like any tool, you have to use it correctly. In particular, if you want performance out of threading, among the most important questions you need to ask is what data needs to be shared across threads. Your algorithm decided that the data which needs to be shared is the entire std::vector<int> result object. And since different threads cannot manipulate the object at the same time, each thread has to wait its turn to do the manipulation. Your code is the equivalent of expecting 10 chefs to cook 10 meals in the same time as 1 chef, but you only provide them a single stove. Threading works out best when nobody has to wait on anybody else to get any work done. Arrange your algorithms accordingly. For example, each thread could build its own array and return them, with the receiving code concatenating all of the arrays together. A: You can do with without any mutex. Create your vector Use a mutex just to (and technically this probably isn't ncessary) to create an iterator point at v.begin () + itsThreadIndex*NumPerThread; then each thread can freely increment that iterator and write to a part of the vector not touched by other threads. Be sure each thread has its own copy of std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); That should run much faster. UNTESTED code - but this should make my above suggestion more clear: using Clock = std::chrono::high_resolution_clock; namespace SharedVars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector<int> RandNums(NumPerThread*N); std::mutex mtx; } void PerThread_AddN(int threadNumber) { using namespace SharedVars; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); int sz = 0; vector<int>::iterator from; vector<int>::iterator to; { std::lock_guard<std::mutex> lock(mtx); // hold the lock only while accessing shared vector, not while accessing its contents from = RandNums.begin () + threadNumber*NumPerThread; to = from + NumPerThread; } for (auto i = from; i < to; ++i) { *i = dis(gen); } } int main() { auto start_time = Clock::now(); std::vector<std::thread> threads; threads.reserve(N); for (unsigned int i=0; i<N; i++) { threads.emplace_back(std::move(std::thread(PerThread_AddN, i))); } for (auto &i: threads) { i.join(); } auto end_time = Clock::now(); std::cout << "\nTime difference = " << std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n"; std::cout << "size = " << sz << '\n'; } A: Nicol Boas was right on the money. I reimplemented it using std::packaged_task, and it's around 4-5 times faster now. #include <iostream> #include <vector> #include <random> #include <future> #include <chrono> using Clock = std::chrono::high_resolution_clock; const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector<int> createVec() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); std::vector<int> x; x.reserve(NumPerThread); for (unsigned int i = 0; i < NumPerThread; i++) { x.push_back(dis(gen)); } return x; } int main() { auto start_time = Clock::now(); std::vector<int> RandNums; RandNums.reserve(N*NumPerThread); std::vector<std::future<std::vector<int>>> results; results.reserve(N); std::vector<int> crap; crap.reserve(NumPerThread); for (unsigned int i=0; i<N; i++) { std::packaged_task<std::vector<int>()> temp(createVec); results[i] = temp.get_future(); temp(); crap = std::move(results[i].get()); RandNums.insert(RandNums.begin()+(0*NumPerThread),crap.begin(),crap.end()); } auto end_time = Clock::now(); std::cout << "Time difference = " << std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n"; } But is there a way to make this one better? lewis's version is way faster than this, so there must be something else missing...
C++ multithreaded version of creating vector of random numbers slower than single-threaded version
I am trying to write a multi-threaded program to produce a vector of N*NumPerThread uniform random integers, where N is the return value of std::thread::hardware_concurrency() and NumPerThread is the amount of random numbers I want each thread to generate. I created a multi-threaded version: #include <iostream> #include <thread> #include <vector> #include <random> #include <chrono> using Clock = std::chrono::high_resolution_clock; namespace Vars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector<int> RandNums(NumPerThread*N); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); int sz = 0; } using namespace Vars; void AddN(int start) { static std::mutex mtx; std::lock_guard<std::mutex> lock(mtx); for (unsigned int i=start; i<start+NumPerThread; i++) { RandNums[i] = dis(gen); ++sz; } } int main() { auto start_time = Clock::now(); std::vector<std::thread> threads; threads.reserve(N); for (unsigned int i=0; i<N; i++) { threads.emplace_back(std::move(std::thread(AddN, i*NumPerThread))); } for (auto &i: threads) { i.join(); } auto end_time = Clock::now(); std::cout << "\nTime difference = " << std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n"; std::cout << "size = " << sz << '\n'; } and a single-threaded version #include <iostream> #include <thread> #include <vector> #include <random> #include <chrono> using Clock = std::chrono::high_resolution_clock; namespace Vars { const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread std::vector<int> RandNums(NumPerThread*N); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000); int sz = 0; } using namespace Vars; void AddN() { for (unsigned int i=0; i<NumPerThread*N; i++) { RandNums[i] = dis(gen); ++sz; } } int main() { auto start_time = Clock::now(); AddN(); auto end_time = Clock::now(); std::cout << "\nTime difference = " << std::chrono::duration<double, std::nano>(end_time - start_time).count() << " nanoseconds\n"; std::cout << "size = " << sz << '\n'; } The execution times are more or less the same. I am assuming there is a problem with the multi-threaded version? P.S. I looked at all of the other similar questions here, I don't see how they directly apply to this task...
[ "Threading is not a magical salve you can rub onto any code that makes it go faster. Like any tool, you have to use it correctly.\nIn particular, if you want performance out of threading, among the most important questions you need to ask is what data needs to be shared across threads. Your algorithm decided that the data which needs to be shared is the entire std::vector<int> result object. And since different threads cannot manipulate the object at the same time, each thread has to wait its turn to do the manipulation.\nYour code is the equivalent of expecting 10 chefs to cook 10 meals in the same time as 1 chef, but you only provide them a single stove.\nThreading works out best when nobody has to wait on anybody else to get any work done. Arrange your algorithms accordingly. For example, each thread could build its own array and return them, with the receiving code concatenating all of the arrays together.\n", "You can do with without any mutex.\n\nCreate your vector\nUse a mutex just to (and technically this probably isn't ncessary) to create an iterator point at v.begin () + itsThreadIndex*NumPerThread;\nthen each thread can freely increment that iterator and write to a part of the vector not touched by other threads.\n\nBe sure each thread has its own copy of\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(1, 1000);\n\nThat should run much faster.\nUNTESTED code - but this should make my above suggestion more clear:\nusing Clock = std::chrono::high_resolution_clock;\n\nnamespace SharedVars\n{\n const unsigned int N = std::thread::hardware_concurrency(); //number of threads on device\n const unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread\n std::vector<int> RandNums(NumPerThread*N);\n std::mutex mtx;\n}\n\nvoid PerThread_AddN(int threadNumber)\n{\n using namespace SharedVars;\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(1, 1000);\n int sz = 0;\n\n vector<int>::iterator from;\n vector<int>::iterator to;\n {\n std::lock_guard<std::mutex> lock(mtx); // hold the lock only while accessing shared vector, not while accessing its contents\n from = RandNums.begin () + threadNumber*NumPerThread;\n to = from + NumPerThread;\n }\n for (auto i = from; i < to; ++i)\n {\n *i = dis(gen);\n }\n}\n\nint main()\n{\n auto start_time = Clock::now();\n std::vector<std::thread> threads;\n threads.reserve(N);\n \n for (unsigned int i=0; i<N; i++)\n {\n threads.emplace_back(std::move(std::thread(PerThread_AddN, i)));\n }\n for (auto &i: threads)\n {\n i.join();\n }\n auto end_time = Clock::now();\n std::cout << \"\\nTime difference = \"\n << std::chrono::duration<double, std::nano>(end_time - start_time).count() << \" nanoseconds\\n\";\n std::cout << \"size = \" << sz << '\\n';\n}\n\n", "Nicol Boas was right on the money. I reimplemented it using std::packaged_task, and it's around 4-5 times faster now.\n#include <iostream>\n#include <vector>\n#include <random>\n#include <future>\n#include <chrono>\n\nusing Clock = std::chrono::high_resolution_clock;\n\nconst unsigned int N = std::thread::hardware_concurrency(); //number of threads on device\nconst unsigned int NumPerThread = 5e5; //number of random numbers to generate per thread\n\nstd::vector<int> createVec()\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(1, 1000);\n std::vector<int> x;\n x.reserve(NumPerThread);\n for (unsigned int i = 0; i < NumPerThread; i++)\n {\n x.push_back(dis(gen));\n }\n return x;\n}\n\nint main()\n{\n auto start_time = Clock::now();\n\n std::vector<int> RandNums;\n RandNums.reserve(N*NumPerThread);\n \n std::vector<std::future<std::vector<int>>> results;\n results.reserve(N);\n std::vector<int> crap;\n crap.reserve(NumPerThread);\n \n for (unsigned int i=0; i<N; i++)\n {\n std::packaged_task<std::vector<int>()> temp(createVec);\n results[i] = temp.get_future();\n temp();\n crap = std::move(results[i].get());\n RandNums.insert(RandNums.begin()+(0*NumPerThread),crap.begin(),crap.end());\n }\n\n auto end_time = Clock::now();\n std::cout << \"Time difference = \"\n << std::chrono::duration<double, std::nano>(end_time - start_time).count() << \" nanoseconds\\n\";\n}\n\n\nBut is there a way to make this one better? lewis's version is way faster than this, so there must be something else missing...\n" ]
[ 4, 0, 0 ]
[]
[]
[ "c++", "stdthread" ]
stackoverflow_0074667965_c++_stdthread.txt
Q: Rewrite a pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate0 Here is my code (btw I am new to Stackoverflow and coding in general so forgive me if I made some mistakes in formatting this question): hours = int(input('Enter hours:')) rate = int(input('Enter rate:')) pay =('Your pay this month' + str((hours + hours/2) * rate)) def computepay(hours,rate): pay =('Your pay this month' + str((hours + hours/2) * rate)) return pay print(pay) A: To take into account overtime versus regular rates of pay it seems like you will need to know how much time the employee worked in each category. With that in mind, here is a simplified example to illustrate some of the key concepts. Example: def computepay(hours, rate): return hours * rate regular_rate = float(input("Hourly rate in dollars: ")) regular_hours = float(input("Regular hours worked: ")) overtime_hours = float(input("Overtime hours worked: ")) regular_pay = computepay(regular_hours, regular_rate) overtime_pay = computepay(overtime_hours, regular_rate * 1.5) total_pay = regular_pay + overtime_pay print(f"This pay period you earned: ${total_pay:.2f}") Output: Hourly rate in dollars: 15.00 Regular hours worked: 40 Overtime hours worked: 10 This pay period you earned: $825.00 A: My teacher told me to solve it in one function, computerpay . so try this . def computepay(hours, rate): if hours > 40: reg = rate * hours otp = (hours - 40.0) * (rate * 0.5) pay = reg + otp else: pay = hours * rate return pay Then The input Output Part sh = input("enter Hours:") sr = input(" Enter rate:") fh = float(sh) fr = float(sr) xp = computepay(fh,fr) print("Pay:",xp) A: def computepay(hours, rate) : return hours * rate def invalid_input() : print("Input Numeric Value") while True : try : regular_rate = float(input("Hourly rate in dollars: ")) break except : invalid_input() continue while True : try : regular_hours = float(input("Regular Hours Worked: ")) break except : invalid_input() continue while True : try : overtime_hours = float(input("Overtime hours worked :")) break except : invalid_input() continue overtime_rate = regular_rate * 1.5 regular_pay = computepay(regular_hours, regular_rate) overtime_pay = computepay(overtime_hours, overtime_rate) total_pay = regular_pay + overtime_pay print("PAY : ", total_pay) A: hour = float(input('Enter hours: ')) rate = float(input('Enter rates: ')) def compute_pay(hours, rates): if hours <= 40: print(hours * rates) elif hours > 40: print(((hours * rate) - 40 * rate) * 1.5 + 40 * rate) compute_pay(hour, rate ) A: hour = float(input('Enter hours: ')) rate = float(input('Enter rates: ')) def compute_pay(hours, rates): if hours <= 40: pay = hours * rates return pay elif hours > 40: pay = ((hours * rate) - 40 * rate) * 1.5 + 40 * rate return pay pay = compute_pay(hour, rate) print(pay)
Rewrite a pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate0
Here is my code (btw I am new to Stackoverflow and coding in general so forgive me if I made some mistakes in formatting this question): hours = int(input('Enter hours:')) rate = int(input('Enter rate:')) pay =('Your pay this month' + str((hours + hours/2) * rate)) def computepay(hours,rate): pay =('Your pay this month' + str((hours + hours/2) * rate)) return pay print(pay)
[ "To take into account overtime versus regular rates of pay it seems like you will need to know how much time the employee worked in each category. With that in mind, here is a simplified example to illustrate some of the key concepts.\nExample:\ndef computepay(hours, rate):\n return hours * rate\n\nregular_rate = float(input(\"Hourly rate in dollars: \"))\nregular_hours = float(input(\"Regular hours worked: \"))\novertime_hours = float(input(\"Overtime hours worked: \"))\n\nregular_pay = computepay(regular_hours, regular_rate)\novertime_pay = computepay(overtime_hours, regular_rate * 1.5)\ntotal_pay = regular_pay + overtime_pay\n\nprint(f\"This pay period you earned: ${total_pay:.2f}\")\n\nOutput:\nHourly rate in dollars: 15.00\nRegular hours worked: 40\nOvertime hours worked: 10\nThis pay period you earned: $825.00\n\n", "My teacher told me to solve it in one function, computerpay . so try this .\ndef computepay(hours, rate):\nif hours > 40:\n reg = rate * hours\n otp = (hours - 40.0) * (rate * 0.5)\n pay = reg + otp\nelse:\n pay = hours * rate \nreturn pay\n\nThen The input Output Part\nsh = input(\"enter Hours:\")\nsr = input(\" Enter rate:\")\nfh = float(sh)\nfr = float(sr)\nxp = computepay(fh,fr)\nprint(\"Pay:\",xp)\n\n", "def computepay(hours, rate) :\n return hours * rate\ndef invalid_input() :\n print(\"Input Numeric Value\")\nwhile True :\n try :\n regular_rate = float(input(\"Hourly rate in dollars: \"))\n break\n except :\n invalid_input()\n continue\nwhile True :\n try :\n regular_hours = float(input(\"Regular Hours Worked: \"))\n break\n except :\n invalid_input()\n continue\nwhile True :\n try :\n overtime_hours = float(input(\"Overtime hours worked :\"))\n break\n except :\n invalid_input()\n continue\novertime_rate = regular_rate * 1.5\n\nregular_pay = computepay(regular_hours, regular_rate)\novertime_pay = computepay(overtime_hours, overtime_rate)\ntotal_pay = regular_pay + overtime_pay\n\nprint(\"PAY : \", total_pay)\n\n", "hour = float(input('Enter hours: '))\nrate = float(input('Enter rates: '))\ndef compute_pay(hours, rates):\nif hours <= 40:\n print(hours * rates)\nelif hours > 40:\n print(((hours * rate) - 40 * rate) * 1.5 + 40 * rate)\n\ncompute_pay(hour, rate )\n", "hour = float(input('Enter hours: '))\nrate = float(input('Enter rates: '))\ndef compute_pay(hours, rates):\nif hours <= 40:\n pay = hours * rates\n return pay\nelif hours > 40:\n pay = ((hours * rate) - 40 * rate) * 1.5 + 40 * rate\n return pay\n\npay = compute_pay(hour, rate)\nprint(pay)\n" ]
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "function", "parameters", "python" ]
stackoverflow_0067036969_function_parameters_python.txt
Q: async constructor functions in TypeScript? I have some setup I want during a constructor, but it seems that is not allowed Which means I can't use: How else should I do this? Currently I have something outside like this, but this is not guaranteed to run in the order I want? async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); } catch (err) { debug("err", err); } await topic.setup(); A: A constructor must return an instance of the class it 'constructs'. Therefore, it's not possible to return Promise<...> and await for it. You can: Make your public setup async. Do not call it from the constructor. Call it whenever you want to 'finalize' object construction. async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); await topic.setup(); } catch (err) { debug("err", err); } } A: Readiness design pattern Don't put the object in a promise, put a promise in the object. Readiness is a property of the object. So make it a property of the object. The awaitable initialise method described in the accepted answer has a serious limitation. Using await like this means only one block of code can be implicitly contingent on the object being ready. This is fine for code with guaranteed linear execution but in multi-threaded or event driven code it's untenable. You could capture the task/promise and await that, but how do you manage making this available to every context that depends on it? The problem is more tractable when correctly framed. The objective is not to wait on construction but to wait on readiness of the constructed object. These are two completely different things. It is even possible for something like a database connection object to be in a ready state, go back to a non-ready state, then become ready again. How can we determine readiness if it depends on activities that may not be complete when the constructor returns? Quite obviously readiness is a property of the object. Many frameworks directly express the notion of readiness. In JavaScript we have the Promise, and in C# we have the Task. Both have direct language support for object properties. Expose the construction completion promise as a property of the constructed object. When the asynchronous part of your construction finishes it should resolve the promise. It doesn't matter whether .then(...) executes before or after the promise resolves. The promise specification states that invoking then on an already resolved promised simply executes the handler immediately. class Foo { public Ready: Promise.IThenable<any>; constructor() { ... this.Ready = new Promise((resolve, reject) => { $.ajax(...).then(result => { // use result resolve(undefined); }).fail(reject); }); } } var foo = new Foo(); foo.Ready.then(() => { // do stuff that needs foo to be ready, eg apply bindings }); // keep going with other stuff that doesn't need to wait for foo // using await // code that doesn't need foo to be ready await foo.Ready; // code that needs foo to be ready Why resolve(undefined); instead of resolve();? Because ES6. Adjust as required to suit your target. Using await In a comment it has been suggested that I should have framed this solution with await to more directly address the question as asked. You can use await with the Ready property as shown in the example above. I'm not a big fan of await because it requires you to partition your code by dependency. You have to put all the dependent code after await and all the independent code before it. This can obscure the intent of the code. I encourage people to think in terms of call-backs. Mentally framing the problem like this is more compatible with languages like C. Promises are arguably descended from the pattern used for IO completion. Lack of enforcement as compared to factory pattern One punter thinks this pattern "is a bad idea because without a factory function, there's nothing to enforce the invariant of checking the readiness. It's left to the clients, which you can practically guarantee will mess up from time to time." If you take this position then how will you stop people from building factory methods that don't enforce the check? Where do you draw the line? For example, would you forbid the division operator because there's nothing stopping people from passing a zero divisor? The hard truth is you have to learn the difference between domain specific code and framework code and apply different standards, seasoned with some common sense. Antecedents This is original work by me. I devised this design pattern because I was unsatisfied with external factories and other such workarounds. Despite searching for some time, I found no prior art for my solution, so I'm claiming credit as the originator of this pattern until disputed. Nevertheless, in 2020 I discovered that in 2013 Stephen Cleary posted a very similar solution to the problem. Looking back through my own work the first vestiges of this approach appear in code I worked on around the same time. I suspect Cleary put it all together first but he didn't formalise it as a design pattern or publish it where it would be easily found by others with the problem. Moreover, Cleary deals only with construction which is only one application of the Readiness pattern (see below). Summary The pattern is put a promise in the object it describes expose it as a property named Ready always reference the promise via the Ready property (don't capture it in a client code variable) This establishes clear simple semantics and guarantees that the promise will be created and managed the promise has identical scope to the object it describes the semantics of readiness dependence are conspicuous and clear in client code if the promise is replaced (eg a connection goes unready then ready again due to network conditions) client code referring to it via thing.Ready will always use the current promise This last one is a nightmare until you use the pattern and let the object manage its own promise. It's also a very good reason to refrain from capturing the promise into a variable. Some objects have methods that temporarily put them in an invalid condition, and the pattern can serve in that scenario without modification. Code of the form obj.Ready.then(...) will always use whatever promise property is returned by the Ready property, so whenever some action is about to invalidate object state, a fresh promise can be created. Closing notes The Readiness pattern isn't specific to construction. It is easily applied to construction but it's really about ensuring that state dependencies are met. In these days of asynchronous code you need a system, and the simple declarative semantics of a promise make it straightforward to express the idea that an action should be taken ASAP, with emphasis on possible. Once you start framing things in these terms, arguments about long running methods or constructors become moot. Deferred initialisation still has its place; as I mentioned you can combine Readiness with lazy load. But if chances are that you won't use the object, then why create it early? It might be better to create on demand. Or it might not; sometimes you can't tolerate delay between the recognition of need and fulfilment. There's more than one way to skin a cat. When I write embedded software I create everything up front including resource pools. This makes leaks impossible and memory demands are known at compile time. But that's only a solution for a small closed problem space. A: Use an asynchronous factory method instead. class MyClass { private mMember: Something; constructor() { this.mMember = await SomeFunctionAsync(); // error } } Becomes: class MyClass { private mMember: Something; // make private if possible; I can't in TS 1.8 constructor() { } public static CreateAsync = async () => { const me = new MyClass(); me.mMember = await SomeFunctionAsync(); return me; }; } This will mean that you will have to await the construction of these kinds of objects, but that should already be implied by the fact that you are in the situation where you have to await something to construct them anyway. There's another thing you can do but I suspect it's not a good idea: // probably BAD class MyClass { private mMember: Something; constructor() { this.LoadAsync(); } private LoadAsync = async () => { this.mMember = await SomeFunctionAsync(); }; } This can work and I've never had an actual problem from it before, but it seems to be dangerous to me, since your object will not actually be fully initialized when you start using it. Another way to do it, which might be better than the first option in some ways, is to await the parts, and then construct your object after: export class MyClass { private constructor( private readonly mSomething: Something, private readonly mSomethingElse: SomethingElse ) { } public static CreateAsync = async () => { const something = await SomeFunctionAsync(); const somethingElse = await SomeOtherFunctionAsync(); return new MyClass(something, somethingElse); }; } A: I've found a solution that looks like export class SomeClass { private initialization; // Implement async constructor constructor() { this.initialization = this.init(); } async init() { await someAsyncCall(); } async fooMethod() { await this.initialization(); // ...some other stuff } async barMethod() { await this.initialization(); // ...some other stuff } It works because Promises that powers async/await, can be resolved multiple times with the same value. A: I know it's quite old but another option is to have a factory that will create the object and wait for its initialization: // Declare the class class A { // Declare class constructor constructor() { // We didn't finish the async job yet this.initialized = false; // Simulates async job, it takes 5 seconds to have it done setTimeout(() => { this.initialized = true; }, 5000); } // do something usefull here - thats a normal method useful() { // but only if initialization was OK if (this.initialized) { console.log("I am doing something useful here") // otherwise throw an error which will be caught by the promise catch } else { throw new Error("I am not initialized!"); } } } // factory for common, extensible class - that's the reason for the constructor parameter // it can be more sophisticated and accept also params for constructor and pass them there // also, the timeout is just an example, it will wait for about 10s (1000 x 10ms iterations function factory(construct) { // create a promise var aPromise = new Promise( function(resolve, reject) { // construct the object here var a = new construct(); // setup simple timeout var timeout = 1000; // called in 10ms intervals to check if the object is initialized function waiter() { if (a.initialized) { // if initialized, resolve the promise resolve(a); } else { // check for timeout - do another iteration after 10ms or throw exception if (timeout > 0) { timeout--; setTimeout(waiter, 10); } else { throw new Error("Timeout!"); } } } // call the waiter, it will return almost immediately waiter(); } ); // return promise of the object being created and initialized return a Promise; } // this is some async function to create object of A class and do something with it async function createObjectAndDoSomethingUseful() { // try/catch to capture exceptions during async execution try { // create object and wait until its initialized (promise resolved) var a = await factory(A); // then do something usefull a.useful(); } catch(e) { // if class instantiation failed from whatever reason, timeout occured or useful was called before the object finished its initialization console.error(e); } } // now, perform the action we want createObjectAndDoSomethingUsefull(); // spaghetti code is done here, but async probably still runs A: Use a private constructor and a static factory method FTW. It is the best way to enforce any validation logic or data enrichment, encapsulated away from a client. class Topic { public static async create(id: string): Promise<Topic> { const topic = new Topic(id); await topic.populate(); return topic; } private constructor(private id: string) { // ... } private async populate(): Promise<void> { // Do something async. Access `this.id` and any other instance fields } } // To instantiate a Topic const topic = await Topic.create(); A: Use a setup async method that returns the instance I had a similar problem in the following case: how to instanciate a 'Foo' class either with an instance of a 'FooSession' class or with a 'fooSessionParams' object, knowing that creating a fooSession from a fooSessionParams object is an async function? I wanted to instanciate either by doing: let foo = new Foo(fooSession); or let foo = await new Foo(fooSessionParams); and did'nt want a factory because the two usages would have been too different. But as we know, we can not return a promise from a constructor (and the return signature is different). I solved it this way: class Foo { private fooSession: FooSession; constructor(fooSession?: FooSession) { if (fooSession) { this.fooSession = fooSession; } } async setup(fooSessionParams: FooSessionParams): Promise<Foo> { this.fooSession = await getAFooSession(fooSessionParams); return this; } } The interesting part is where the setup async method returns the instance itself. Then if I have a 'FooSession' instance I can use it this way: let foo = new Foo(fooSession); And if I have no 'FooSession' instance I can setup 'foo' in one of these ways: let foo = await new Foo().setup(fooSessionParams); (witch is my prefered way because it is close to what I wanted first) or let foo = new Foo(); await foo.setup(fooSessionParams); As an alternative I could also add the static method: static async getASession(fooSessionParams: FooSessionParams): FooSession { let fooSession: FooSession = await getAFooSession(fooSessionParams); return fooSession; } and instanciate this way: let foo = new Foo(await Foo.getASession(fooSessionParams)); It is mainly a question of style… A: You may elect to leave the await out of the equation altogether. You can call it from the constructor if you need to. The caveat being that you need to deal with any return values in the setup/initialise function, not in the constructor. this works for me, using angular 1.6.3. import { module } from "angular"; import * as R from "ramda"; import cs = require("./checkListService"); export class CheckListController { static $inject = ["$log", "$location", "ICheckListService"]; checkListId: string; constructor( public $log: ng.ILogService, public $loc: ng.ILocationService, public checkListService: cs.ICheckListService) { this.initialise(); } /** * initialise the controller component. */ async initialise() { try { var list = await this.checkListService.loadCheckLists(); this.checkListId = R.head(list).id.toString(); this.$log.info(`set check list id to ${this.checkListId}`); } catch (error) { // deal with problems here. } } } module("app").controller("checkListController", CheckListController) A: Create holder for promise status: class MyClass { constructor(){ this.#fetchResolved = this.fetch() } #fetchResolved: Promise<void>; fetch = async (): Promise<void> => { return new Promise(resolve => resolve()) // save data to class property or simply add it by resolve() to #fetchResolved reference } isConstructorDone = async (): boolean => { await this.#fetchResolved; return true; // or any other data depending on constructor finish the job } } To use: const data = new MyClass(); const field = await data.isConstructorDone(); A: Use a factory. That's the best practice for these cases. The problem is that is tricky to define Typescript types for the factory pattern, especially with inheritance. Let's see how to properly implement it in Typescript. No inheritance If you don't need class inheritance, the pattern is this: class Person { constructor(public name: string) {} static async Create(name: string): Promise<Person> { const instance = new Person(name); /** Your async code here! **/ return instance; } } const person = await Person.Create('John'); Class inheritance If you need to extend the class, you will run into a problem. The Create method always returns the base class. In Typescript, you can fix this with Generic Classes. type PersonConstructor<T = {}> = new (...args: any[]) => T; class Person { constructor(public name: string) {} static async Create<T extends Person>( this: PersonConstructor<T>, name: string, ...args: any[] ): Promise<T> { const instance = new this(name, ...args); /** Your async code here! **/ return instance; } } class MyPerson extends Person { constructor(name: string, public lastName: string) { super(name); } } const myPerson = await MyPerson.Create('John', 'Snow'); Extending the factory You can extend the Create method too. class MyPerson extends Person { constructor(name: string, public lastName: string) { super(name); } static async Create<T extends Person>( this: PersonConstructor<T>, name: string, lastName: string, ...args: any[] ): Promise<T> { const instance = await super.Create(name, lastName, ...args); /** Your async code here! **/ return instance as T; } } const myPerson = await MyPerson.Create('John', 'Snow'); Less verbose alternative We can reduce the code verbosity by leveraging the async code to a non-static method, which won't require a Generic Class definition when extending the Create method. type PersonConstructor<T = {}> = new (...args: any[]) => T; class Person { constructor(public name: string) {} protected async init(): Promise<void> { /** Your async code here! **/ // this.name = await ... } static async Create<T extends Person>( this: PersonConstructor<T>, name: string, ...args: any[] ): Promise<T> { const instance = new this(name, ...args); await instance.init(); return instance; } } class MyPerson extends Person { constructor(name: string, public lastName: string) { super(name); } override async init(): Promise<void> { await super.init(); /** Your async code here! **/ // this.lastName = await ... } } const myPerson = await MyPerson.Create('John', 'Snow'); Aren't static methods bad practice? Yes, with one exception: factories. Why not return a promise in the constructor? You can do that, but many will consider your code a bad pattern, because a constructor: Should always return the class type (Promise<Person> is not Person); Should never run async code;
async constructor functions in TypeScript?
I have some setup I want during a constructor, but it seems that is not allowed Which means I can't use: How else should I do this? Currently I have something outside like this, but this is not guaranteed to run in the order I want? async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); } catch (err) { debug("err", err); } await topic.setup();
[ "A constructor must return an instance of the class it 'constructs'. Therefore, it's not possible to return Promise<...> and await for it.\nYou can:\n\nMake your public setup async.\n\nDo not call it from the constructor.\n\nCall it whenever you want to 'finalize' object construction.\nasync function run() \n{\n let topic;\n debug(\"new TopicsModel\");\n try \n {\n topic = new TopicsModel();\n await topic.setup();\n } \n catch (err) \n {\n debug(\"err\", err);\n }\n}\n\n\n\n", "Readiness design pattern\n\nDon't put the object in a promise, put a promise in the object.\n\nReadiness is a property of the object. So make it a property of the object.\nThe awaitable initialise method described in the accepted answer has a serious limitation. Using await like this means only one block of code can be implicitly contingent on the object being ready. This is fine for code with guaranteed linear execution but in multi-threaded or event driven code it's untenable.\nYou could capture the task/promise and await that, but how do you manage making this available to every context that depends on it?\nThe problem is more tractable when correctly framed. The objective is not to wait on construction but to wait on readiness of the constructed object. These are two completely different things. It is even possible for something like a database connection object to be in a ready state, go back to a non-ready state, then become ready again.\nHow can we determine readiness if it depends on activities that may not be complete when the constructor returns? Quite obviously readiness is a property of the object. Many frameworks directly express the notion of readiness. In JavaScript we have the Promise, and in C# we have the Task. Both have direct language support for object properties.\nExpose the construction completion promise as a property of the constructed object. When the asynchronous part of your construction finishes it should resolve the promise.\nIt doesn't matter whether .then(...) executes before or after the promise resolves. The promise specification states that invoking then on an already resolved promised simply executes the handler immediately.\nclass Foo {\n public Ready: Promise.IThenable<any>;\n constructor() {\n ...\n this.Ready = new Promise((resolve, reject) => {\n $.ajax(...).then(result => {\n // use result\n resolve(undefined);\n }).fail(reject);\n });\n }\n}\n\nvar foo = new Foo();\nfoo.Ready.then(() => {\n // do stuff that needs foo to be ready, eg apply bindings\n});\n// keep going with other stuff that doesn't need to wait for foo\n\n// using await\n// code that doesn't need foo to be ready\nawait foo.Ready;\n// code that needs foo to be ready\n\nWhy resolve(undefined); instead of resolve();? Because ES6. Adjust as required to suit your target.\nUsing await\nIn a comment it has been suggested that I should have framed this solution with await to more directly address the question as asked.\nYou can use await with the Ready property as shown in the example above. I'm not a big fan of await because it requires you to partition your code by dependency. You have to put all the dependent code after await and all the independent code before it. This can obscure the intent of the code.\nI encourage people to think in terms of call-backs. Mentally framing the problem like this is more compatible with languages like C. Promises are arguably descended from the pattern used for IO completion.\nLack of enforcement as compared to factory pattern\nOne punter thinks this pattern \"is a bad idea because without a factory function, there's nothing to enforce the invariant of checking the readiness. It's left to the clients, which you can practically guarantee will mess up from time to time.\"\nIf you take this position then how will you stop people from building factory methods that don't enforce the check? Where do you draw the line? For example, would you forbid the division operator because there's nothing stopping people from passing a zero divisor? The hard truth is you have to learn the difference between domain specific code and framework code and apply different standards, seasoned with some common sense.\n\nAntecedents\nThis is original work by me. I devised this design pattern because I was unsatisfied with external factories and other such workarounds. Despite searching for some time, I found no prior art for my solution, so I'm claiming credit as the originator of this pattern until disputed.\nNevertheless, in 2020 I discovered that in 2013 Stephen Cleary posted a very similar solution to the problem. Looking back through my own work the first vestiges of this approach appear in code I worked on around the same time. I suspect Cleary put it all together first but he didn't formalise it as a design pattern or publish it where it would be easily found by others with the problem. Moreover, Cleary deals only with construction which is only one application of the Readiness pattern (see below).\nSummary\nThe pattern is\n\nput a promise in the object it describes\nexpose it as a property named Ready\nalways reference the promise via the Ready property (don't capture it in a client code variable)\n\nThis establishes clear simple semantics and guarantees that\n\nthe promise will be created and managed\nthe promise has identical scope to the object it describes\nthe semantics of readiness dependence are conspicuous and clear in client code\nif the promise is replaced (eg a connection goes unready then ready again due to network conditions) client code referring to it via thing.Ready will always use the current promise\n\nThis last one is a nightmare until you use the pattern and let the object manage its own promise. It's also a very good reason to refrain from capturing the promise into a variable.\nSome objects have methods that temporarily put them in an invalid condition, and the pattern can serve in that scenario without modification. Code of the form obj.Ready.then(...) will always use whatever promise property is returned by the Ready property, so whenever some action is about to invalidate object state, a fresh promise can be created.\nClosing notes\nThe Readiness pattern isn't specific to construction. It is easily applied to construction but it's really about ensuring that state dependencies are met. In these days of asynchronous code you need a system, and the simple declarative semantics of a promise make it straightforward to express the idea that an action should be taken ASAP, with emphasis on possible. Once you start framing things in these terms, arguments about long running methods or constructors become moot.\nDeferred initialisation still has its place; as I mentioned you can combine Readiness with lazy load. But if chances are that you won't use the object, then why create it early? It might be better to create on demand. Or it might not; sometimes you can't tolerate delay between the recognition of need and fulfilment.\nThere's more than one way to skin a cat. When I write embedded software I create everything up front including resource pools. This makes leaks impossible and memory demands are known at compile time. But that's only a solution for a small closed problem space.\n", "Use an asynchronous factory method instead.\nclass MyClass {\n private mMember: Something;\n\n constructor() {\n this.mMember = await SomeFunctionAsync(); // error\n }\n}\n\nBecomes:\nclass MyClass {\n private mMember: Something;\n\n // make private if possible; I can't in TS 1.8\n constructor() {\n }\n\n public static CreateAsync = async () => {\n const me = new MyClass();\n \n me.mMember = await SomeFunctionAsync();\n\n return me;\n };\n}\n\nThis will mean that you will have to await the construction of these kinds of objects, but that should already be implied by the fact that you are in the situation where you have to await something to construct them anyway.\nThere's another thing you can do but I suspect it's not a good idea:\n// probably BAD\nclass MyClass {\n private mMember: Something;\n\n constructor() {\n this.LoadAsync();\n }\n\n private LoadAsync = async () => {\n this.mMember = await SomeFunctionAsync();\n };\n}\n\nThis can work and I've never had an actual problem from it before, but it seems to be dangerous to me, since your object will not actually be fully initialized when you start using it.\nAnother way to do it, which might be better than the first option in some ways, is to await the parts, and then construct your object after:\nexport class MyClass {\n private constructor(\n private readonly mSomething: Something,\n private readonly mSomethingElse: SomethingElse\n ) {\n }\n\n public static CreateAsync = async () => {\n const something = await SomeFunctionAsync();\n const somethingElse = await SomeOtherFunctionAsync();\n\n return new MyClass(something, somethingElse);\n };\n}\n\n", "I've found a solution that looks like\nexport class SomeClass {\n private initialization;\n\n // Implement async constructor\n constructor() {\n this.initialization = this.init();\n }\n\n async init() {\n await someAsyncCall();\n }\n\n async fooMethod() {\n await this.initialization();\n // ...some other stuff\n }\n\n async barMethod() {\n await this.initialization();\n // ...some other stuff\n }\n\n\nIt works because Promises that powers async/await, can be resolved multiple times with the same value.\n", "I know it's quite old but another option is to have a factory that will create the object and wait for its initialization:\n// Declare the class\nclass A {\n\n // Declare class constructor\n constructor() {\n\n // We didn't finish the async job yet\n this.initialized = false;\n\n // Simulates async job, it takes 5 seconds to have it done\n setTimeout(() => {\n this.initialized = true;\n }, 5000);\n }\n\n // do something usefull here - thats a normal method\n useful() {\n // but only if initialization was OK\n if (this.initialized) {\n console.log(\"I am doing something useful here\")\n\n // otherwise throw an error which will be caught by the promise catch\n } else {\n throw new Error(\"I am not initialized!\");\n }\n }\n\n}\n\n// factory for common, extensible class - that's the reason for the constructor parameter\n// it can be more sophisticated and accept also params for constructor and pass them there\n// also, the timeout is just an example, it will wait for about 10s (1000 x 10ms iterations\nfunction factory(construct) {\n\n // create a promise\n var aPromise = new Promise(\n function(resolve, reject) {\n\n // construct the object here\n var a = new construct();\n\n // setup simple timeout\n var timeout = 1000;\n\n // called in 10ms intervals to check if the object is initialized\n function waiter() {\n \n if (a.initialized) {\n // if initialized, resolve the promise\n resolve(a);\n } else {\n\n // check for timeout - do another iteration after 10ms or throw exception\n if (timeout > 0) { \n timeout--;\n setTimeout(waiter, 10); \n } else { \n throw new Error(\"Timeout!\"); \n }\n\n }\n }\n \n // call the waiter, it will return almost immediately\n waiter();\n }\n );\n\n // return promise of the object being created and initialized\n return a Promise;\n}\n\n\n// this is some async function to create object of A class and do something with it\nasync function createObjectAndDoSomethingUseful() {\n\n // try/catch to capture exceptions during async execution\n try {\n // create object and wait until its initialized (promise resolved)\n var a = await factory(A);\n // then do something usefull\n a.useful();\n } catch(e) {\n // if class instantiation failed from whatever reason, timeout occured or useful was called before the object finished its initialization\n console.error(e);\n }\n\n}\n\n// now, perform the action we want\ncreateObjectAndDoSomethingUsefull();\n\n// spaghetti code is done here, but async probably still runs\n\n", "Use a private constructor and a static factory method FTW. It is the best way to enforce any validation logic or data enrichment, encapsulated away from a client.\nclass Topic {\n public static async create(id: string): Promise<Topic> {\n const topic = new Topic(id);\n await topic.populate();\n return topic;\n }\n\n private constructor(private id: string) {\n // ...\n }\n\n private async populate(): Promise<void> {\n // Do something async. Access `this.id` and any other instance fields\n }\n}\n\n// To instantiate a Topic\nconst topic = await Topic.create();\n\n\n", "Use a setup async method that returns the instance\nI had a similar problem in the following case: how to instanciate a 'Foo' class either with an instance of a 'FooSession' class or with a 'fooSessionParams' object, knowing that creating a fooSession from a fooSessionParams object is an async function?\nI wanted to instanciate either by doing:\nlet foo = new Foo(fooSession);\n\nor\nlet foo = await new Foo(fooSessionParams);\n\nand did'nt want a factory because the two usages would have been too different. But as we know, we can not return a promise from a constructor (and the return signature is different). I solved it this way:\nclass Foo {\n private fooSession: FooSession;\n\n constructor(fooSession?: FooSession) {\n if (fooSession) {\n this.fooSession = fooSession;\n }\n }\n\n async setup(fooSessionParams: FooSessionParams): Promise<Foo> {\n this.fooSession = await getAFooSession(fooSessionParams);\n return this;\n }\n}\n\nThe interesting part is where the setup async method returns the instance itself.\nThen if I have a 'FooSession' instance I can use it this way:\nlet foo = new Foo(fooSession);\n\nAnd if I have no 'FooSession' instance I can setup 'foo' in one of these ways:\nlet foo = await new Foo().setup(fooSessionParams);\n\n(witch is my prefered way because it is close to what I wanted first)\nor\nlet foo = new Foo();\nawait foo.setup(fooSessionParams);\n\nAs an alternative I could also add the static method:\n static async getASession(fooSessionParams: FooSessionParams): FooSession {\n let fooSession: FooSession = await getAFooSession(fooSessionParams);\n return fooSession;\n }\n\nand instanciate this way:\nlet foo = new Foo(await Foo.getASession(fooSessionParams));\n\nIt is mainly a question of style…\n", "You may elect to leave the await out of the equation altogether. You can call it from the constructor if you need to. The caveat being that you need to deal with any return values in the setup/initialise function, not in the constructor.\nthis works for me, using angular 1.6.3.\nimport { module } from \"angular\";\nimport * as R from \"ramda\";\nimport cs = require(\"./checkListService\");\n\nexport class CheckListController {\n\n static $inject = [\"$log\", \"$location\", \"ICheckListService\"];\n checkListId: string;\n\n constructor(\n public $log: ng.ILogService,\n public $loc: ng.ILocationService,\n public checkListService: cs.ICheckListService) {\n this.initialise();\n }\n\n /**\n * initialise the controller component.\n */\n async initialise() {\n try {\n var list = await this.checkListService.loadCheckLists();\n this.checkListId = R.head(list).id.toString();\n this.$log.info(`set check list id to ${this.checkListId}`);\n } catch (error) {\n // deal with problems here.\n }\n }\n}\n\nmodule(\"app\").controller(\"checkListController\", CheckListController)\n\n", "Create holder for promise status:\nclass MyClass {\n constructor(){\n this.#fetchResolved = this.fetch()\n }\n #fetchResolved: Promise<void>;\n fetch = async (): Promise<void> => {\n return new Promise(resolve => resolve()) // save data to class property or simply add it by resolve() to #fetchResolved reference\n }\n isConstructorDone = async (): boolean => {\n await this.#fetchResolved;\n return true; // or any other data depending on constructor finish the job\n }\n}\n\nTo use:\nconst data = new MyClass();\nconst field = await data.isConstructorDone();\n\n", "Use a factory. That's the best practice for these cases.\nThe problem is that is tricky to define Typescript types for the factory pattern, especially with inheritance.\nLet's see how to properly implement it in Typescript.\nNo inheritance\nIf you don't need class inheritance, the pattern is this:\nclass Person {\n constructor(public name: string) {}\n\n static async Create(name: string): Promise<Person> {\n const instance = new Person(name);\n\n /** Your async code here! **/\n\n return instance;\n }\n}\n\nconst person = await Person.Create('John');\n\nClass inheritance\nIf you need to extend the class, you will run into a problem. The Create method always returns the base class.\nIn Typescript, you can fix this with Generic Classes.\ntype PersonConstructor<T = {}> = new (...args: any[]) => T;\n\nclass Person {\n constructor(public name: string) {}\n\n static async Create<T extends Person>(\n this: PersonConstructor<T>,\n name: string,\n ...args: any[]\n ): Promise<T> {\n const instance = new this(name, ...args);\n\n /** Your async code here! **/\n\n return instance;\n }\n}\n\nclass MyPerson extends Person {\n constructor(name: string, public lastName: string) {\n super(name);\n }\n}\n\nconst myPerson = await MyPerson.Create('John', 'Snow');\n\nExtending the factory\nYou can extend the Create method too.\nclass MyPerson extends Person {\n constructor(name: string, public lastName: string) {\n super(name);\n }\n\n static async Create<T extends Person>(\n this: PersonConstructor<T>,\n name: string,\n lastName: string,\n ...args: any[]\n ): Promise<T> {\n const instance = await super.Create(name, lastName, ...args);\n\n /** Your async code here! **/\n\n return instance as T;\n }\n}\n\nconst myPerson = await MyPerson.Create('John', 'Snow');\n\nLess verbose alternative\nWe can reduce the code verbosity by leveraging the async code to a non-static method, which won't require a Generic Class definition when extending the Create method.\ntype PersonConstructor<T = {}> = new (...args: any[]) => T;\n\nclass Person {\n constructor(public name: string) {}\n\n protected async init(): Promise<void> {\n /** Your async code here! **/\n // this.name = await ...\n }\n\n static async Create<T extends Person>(\n this: PersonConstructor<T>,\n name: string,\n ...args: any[]\n ): Promise<T> {\n const instance = new this(name, ...args);\n\n await instance.init();\n\n return instance;\n }\n}\n\nclass MyPerson extends Person {\n constructor(name: string, public lastName: string) {\n super(name);\n }\n\n override async init(): Promise<void> {\n await super.init();\n\n /** Your async code here! **/\n // this.lastName = await ...\n }\n}\n\nconst myPerson = await MyPerson.Create('John', 'Snow');\n\nAren't static methods bad practice?\nYes, with one exception: factories.\nWhy not return a promise in the constructor?\nYou can do that, but many will consider your code a bad pattern, because a constructor:\n\nShould always return the class type (Promise<Person> is not Person);\nShould never run async code;\n\n" ]
[ 85, 78, 29, 12, 10, 8, 2, 1, 0, 0 ]
[ "Or you can just stick to the true ASYNC model and not overcomplicate the setup. 9 out of 10 times this comes down to asynchronous versus synchronous design. For example I have a React component that needed this very same thing were I was initializing the state variables in a promise callback in the constructor. Turns out that all I needed to do to get around the null data exception was just setup an empty state object then set it in the async callback. For example here's a Firebase read with a returned promise and callback:\n this._firebaseService = new FirebaseService();\n this.state = {data: [], latestAuthor: '', latestComment: ''};\n\n this._firebaseService.read(\"/comments\")\n .then((data) => {\n const dataObj = data.val();\n const fetchedComments = dataObj.map((e: any) => {\n return {author: e.author, text: e.text}\n });\n\n this.state = {data: fetchedComments, latestAuthor: '', latestComment: ''};\n\n });\n\nBy taking this approach my code maintains it's AJAX behavior without compromising the component with a null exception because the state is setup with defaults (empty object and empty strings) prior to the callback. The user may see an empty list for a second but then it's quickly populated. Better yet would be to apply a spinner while the data loads up. Oftentimes I hear of individuals suggesting overly complicated work arounds as is the case in this post but the original flow should be re-examined.\n" ]
[ -1 ]
[ "async_await", "constructor", "typescript" ]
stackoverflow_0035743426_async_await_constructor_typescript.txt
Q: How to Get Apps to Show Full Screen on Chromebook? I've been making Android apps for a long time and can get them to open in full screen mode on every device except Chromebook. No matter what I do, they only open about half screen and a user has to click the "maximize" button to get them to open further. Here is the code I use to try to get the apps full screen: <item name="android:windowFullscreen">true</item> in the relevant style in themes.xml as well as getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); in MainActivity's onCreate() method. I've also tried putting android:theme="@android:style/Theme.NoTitleBar.Fullscreen" in the application block of AndroidManifest.xml. Is there something else I can do to get the apps to open full screen on Chromebook? (I'm using HP Chromebook x360, if that helps) A: So there is a section of the Android documentation for using Android on ChromeOS which makes reference to Window Management - Launch Size which seems appropriate. Quoting from the documentation: Use a launch size only in desktop environments. This helps the window manager to give you the proper bounds and orientation. To indicate a preferences when used in desktop mode, add the following meta tags inside the <activity>: <meta-data android:name="WindowManagerPreference:FreeformWindowSize" android:value="[phone|tablet|maximize]" /> <meta-data android:name="WindowManagerPreference:FreeformWindowOrientation" android:value="[portrait|landscape]" /> Use static launch bounds. Use inside the manifest entry of your activity to specify a "fixed" starting size. See this example: <layout android:defaultHeight="500dp" android:defaultWidth="600dp" android:gravity="top|end" android:minHeight="450dp" android:minWidth="300dp" /> Use dynamic launch bounds. An activity can create and use ActivityOptions.setLaunchBounds(Rect) when creating a new activity. By specifying an empty rectangle, your app can be maximized. Note: These options work only if the activity started is a root activity. You can also do this using a springboard activity to clear the activity stack in the task with a new start.
How to Get Apps to Show Full Screen on Chromebook?
I've been making Android apps for a long time and can get them to open in full screen mode on every device except Chromebook. No matter what I do, they only open about half screen and a user has to click the "maximize" button to get them to open further. Here is the code I use to try to get the apps full screen: <item name="android:windowFullscreen">true</item> in the relevant style in themes.xml as well as getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); in MainActivity's onCreate() method. I've also tried putting android:theme="@android:style/Theme.NoTitleBar.Fullscreen" in the application block of AndroidManifest.xml. Is there something else I can do to get the apps to open full screen on Chromebook? (I'm using HP Chromebook x360, if that helps)
[ "So there is a section of the Android documentation for using Android on ChromeOS which makes reference to Window Management - Launch Size which seems appropriate.\nQuoting from the documentation:\n\n\nUse a launch size only in desktop environments. This helps the window manager to give you the proper bounds and orientation. To indicate a preferences when used in desktop mode, add the following meta tags inside the <activity>:\n\n\n<meta-data android:name=\"WindowManagerPreference:FreeformWindowSize\"\n android:value=\"[phone|tablet|maximize]\" />\n<meta-data android:name=\"WindowManagerPreference:FreeformWindowOrientation\"\n android:value=\"[portrait|landscape]\" />\n\n\n\nUse static launch bounds. Use inside the manifest entry of your activity to specify a \"fixed\" starting size. See this example:\n\n\n<layout android:defaultHeight=\"500dp\"\n android:defaultWidth=\"600dp\"\n android:gravity=\"top|end\"\n android:minHeight=\"450dp\"\n android:minWidth=\"300dp\" />\n\n\n\nUse dynamic launch bounds. An activity can create and use ActivityOptions.setLaunchBounds(Rect) when creating a new activity. By specifying an empty rectangle, your app can be maximized.\n\n\n\nNote: These options work only if the activity started is a root activity. You can also do this using a springboard activity to clear the activity stack in the task with a new start.\n\n" ]
[ 0 ]
[]
[]
[ "android", "chromebook", "fullscreen" ]
stackoverflow_0074405746_android_chromebook_fullscreen.txt
Q: How to create a FILE HANDLER project in Python that can do the below given tasks: Read content from a txt file character by character. Get number of characters, words, spaces and lines in a file. Find no. of lines in the file. Find the line no. which contains a specific word. PS: Please provide a basic code so that a beginner can understand A: SpesificWord = input() #get the specific word with open('file.txt','r',encoding='utf-8') as file: #open the file for index, line in enumerate(file): #index is current no of file, line is current line print(len(line)) # prints the length of line - including space etc. print(f'Current Line: {index+1}) #prints current line if SpesificWord in line: print(f'Spesific word is in line {index+1})
How to create a FILE HANDLER project in Python that can do the below given tasks:
Read content from a txt file character by character. Get number of characters, words, spaces and lines in a file. Find no. of lines in the file. Find the line no. which contains a specific word. PS: Please provide a basic code so that a beginner can understand
[ "SpesificWord = input() #get the specific word\nwith open('file.txt','r',encoding='utf-8') as file: #open the file\n for index, line in enumerate(file): #index is current no of file, line is current line\n print(len(line)) # prints the length of line - including space etc.\n print(f'Current Line: {index+1}) #prints current line\n if SpesificWord in line:\n print(f'Spesific word is in line {index+1})\n\n" ]
[ 0 ]
[]
[]
[ "filehandler", "python" ]
stackoverflow_0074669712_filehandler_python.txt
Q: How to cancel JavaScript sleep? This function is used to wait for millis number of second. function delay(millis: number) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, millis); }); My goal is then to return the timeout out of this function? const timeout = await delay(20000); on click somewhere else, user bored of waiting clearTimeout(timeout) A: Simply extend the Promise object you'll be sending: function delay( millis ) { let timeout_id; let rejector; const prom = new Promise((resolve, reject) => { rejector = reject; timeout_id = setTimeout(() => { resolve(); }, millis); }); prom.abort = () => { clearTimeout( timeout_id ); rejector( 'aborted' ); }; return prom; } const will_abort = delay( 2000 ); const will_not_abort = delay( 2000 ); will_abort .then( () => console.log( 'will_abort ended' ) ) .catch( console.error ); will_not_abort .then( () => console.log( 'will_not_abort ended' ) ) .catch( console.error ); setTimeout( () => will_abort.abort(), 1000 ); A: You can return the resolve / reject along with the promise function delay(millis) { let reolver; return [new Promise((resolve, reject) => { resolver = resolve x = setTimeout(() => { resolve(); }, millis); }), resolver]; } const [sleep1, wake1] = delay(2000) sleep1.then((x) => console.log(x || 'wakeup 1')) // Auto wake after 2 seconds const [sleep2, wake2] = delay(2000) sleep2.then((x) => console.log(x || 'wakeup 2')) wake2('Custom Wakeup') // sleep2 cancelled will wake from wake2 call A: You can use an AbortSignal: function delay(ms, signal) { return new Promise((resolve, reject) => { function done() { resolve(); signal?.removeEventListener("abort", stop); } function stop() { reject(this.reason); clearTimeout(handle); } signal?.throwIfAborted(); const handle = setTimeout(done, ms); signal?.addEventListener("abort", stop); }); } Example: const controller = new AbortController() delay(9000, controller.signal).then(() => { console.log('Finished sleeping'); }, err => { if (!controller.signal.aborted) throw err; // alternatively: if (err.name != "AbortError") throw err; console.log('Cancelled sleep before it went over 9000') }); button.onclick => () => { controller.abort(); }; A: You can return a function which cancels the timer (cancelTimer) along with the Promise object as an array from the delay function call. Then use the cancelTimer to clear it if required and which would also reject the Promise: function delay(millis) { let cancelTimer; const promise = new Promise((resolve, reject) => { const timeoutID = setTimeout(() => { resolve("done"); }, millis); cancelTimer = () => { clearTimeout(timeoutID); reject("Promise cancelled"); }; }); return [promise, cancelTimer]; } //DEMO let [promiseCancelled, cancelTimer] = delay(20000); (async() => { try { console.log("Promise result never printed", await promiseCancelled); } catch (error) { console.error("Promise is rejected", error); } })(); cancelTimer(); const [promise, _] = delay(2000); (async() => { console.log("Promise result printed", await promise); })(); A: I recommend that you do not modify the promise by attaching an .abort method to it. Instead return two values from your delay function the delayed value a function that can be called to cancel the timeout Critically, we do not see "x" logged to the console because it was canceled - function useDelay (x = null, ms = 1000) { let t return [ new Promise(r => t = setTimeout(r, ms, x)), // 1 _ => clearTimeout(t) // 2 ] } const [x, abortX] = useDelay("x", 5000) const [y, abortY] = useDelay("y canceled x", 2000) x.then(console.log, console.error) y.then(console.log, console.error).finally(_ => abortX()) console.log("loading...") // loading... // y canceled x interactive demo Here's an interactive example that allows you to wait for a delayed value or abort it - function useDelay (x = null, ms = 1000) { let t return [ new Promise(r => t = setTimeout(r, ms, x)), // 1 _ => clearTimeout(t) // 2 ] } const [ input, output ] = document.querySelectorAll("input") const [go, abort] = document.querySelectorAll("button") let loading = false function reset () { loading = false input.value = "" go.disabled = false abort.disabled = true } function load () { loading = true go.disabled = true abort.disabled = false } go.onclick = e => { if (loading) return load() const [delayedValue, abortValue] = useDelay(input.value, 3000) abort.onclick = _ => { abortValue() reset() } delayedValue .then(v => output.value = v) .catch(e => output.value = e.message) .finally(_ => reset()) } code { color: dodgerblue; } <input placeholder="enter a value..." /> <button>GO</button> <button disabled>ABORT</button> <input disabled placeholder="waiting for output..." /> <p>Click <code>GO</code> and the value will be transferred to the output in 5 seconds.</p> <p>If you click <code>ABORT</code> the transfer will be canceled.</p> A: Just use an AbortSignal: /** * Sleep for the specified number of milliseconds, or until the abort * signal gets triggered. * * @param ms {number} * @param signal {AbortSignal|undefined} */ const sleep = (ms, signal) => new Promise<void>((ok, ng) => { /** @type {number} */ let timeout const abortHandler = () => { clearTimeout(timeout) const aborted = new Error(`sleep aborted`) aborted.name = 'AbortError' ng(aborted) } signal?.addEventListener('abort', abortHandler) timeout = setTimeout(() => { signal?.removeEventListener('abort', abortHandler) ok() }, ms) }) > const a = new AbortController() undefined > const s = sleep(900000, a.signal) undefined > a.abort() undefined > await s Uncaught AbortError: sleep aborted at AbortSignal.abortHandler at innerInvokeEventListeners at invokeEventListeners at dispatch at AbortSignal.dispatchEvent at AbortSignal.[[[signalAbort]]] at AbortController.abort at <anonymous>:2:3 > If you prefer not to fail the promise, i.e. treat the abort signal as "skip sleep", simply replace the call to ng(aborted) with a call to ok().
How to cancel JavaScript sleep?
This function is used to wait for millis number of second. function delay(millis: number) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, millis); }); My goal is then to return the timeout out of this function? const timeout = await delay(20000); on click somewhere else, user bored of waiting clearTimeout(timeout)
[ "Simply extend the Promise object you'll be sending:\n\n\nfunction delay( millis ) {\n let timeout_id;\n let rejector;\n const prom = new Promise((resolve, reject) => {\n rejector = reject;\n timeout_id = setTimeout(() => {\n resolve();\n }, millis);\n });\n prom.abort = () => {\n clearTimeout( timeout_id );\n rejector( 'aborted' );\n };\n return prom;\n}\n\nconst will_abort = delay( 2000 );\nconst will_not_abort = delay( 2000 );\n\nwill_abort\n .then( () => console.log( 'will_abort ended' ) )\n .catch( console.error );\n\nwill_not_abort\n .then( () => console.log( 'will_not_abort ended' ) )\n .catch( console.error );\n\nsetTimeout( () => will_abort.abort(), 1000 );\n\n\n\n", "You can return the resolve / reject along with the promise\n\n\nfunction delay(millis) {\r\n let reolver;\r\n return [new Promise((resolve, reject) => {\r\n resolver = resolve\r\n x = setTimeout(() => {\r\n resolve();\r\n }, millis);\r\n }), resolver];\r\n} \r\n\r\nconst [sleep1, wake1] = delay(2000)\r\nsleep1.then((x) => console.log(x || 'wakeup 1')) // Auto wake after 2 seconds\r\n\r\nconst [sleep2, wake2] = delay(2000)\r\nsleep2.then((x) => console.log(x || 'wakeup 2'))\r\nwake2('Custom Wakeup') // sleep2 cancelled will wake from wake2 call \r\n \n\n\n\n", "You can use an AbortSignal:\nfunction delay(ms, signal) {\n return new Promise((resolve, reject) => {\n function done() {\n resolve();\n signal?.removeEventListener(\"abort\", stop);\n }\n function stop() {\n reject(this.reason);\n clearTimeout(handle);\n }\n signal?.throwIfAborted();\n const handle = setTimeout(done, ms);\n signal?.addEventListener(\"abort\", stop);\n });\n}\n\nExample:\nconst controller = new AbortController()\ndelay(9000, controller.signal).then(() => {\n console.log('Finished sleeping');\n}, err => {\n if (!controller.signal.aborted) throw err;\n // alternatively:\n if (err.name != \"AbortError\") throw err;\n\n console.log('Cancelled sleep before it went over 9000')\n});\nbutton.onclick => () => {\n controller.abort();\n};\n\n", "You can return a function which cancels the timer (cancelTimer) along with the Promise object as an array from the delay function call.\nThen use the cancelTimer to clear it if required and which would also reject the Promise:\n\n\nfunction delay(millis) {\r\n let cancelTimer;\r\n const promise = new Promise((resolve, reject) => {\r\n const timeoutID = setTimeout(() => {\r\n resolve(\"done\");\r\n }, millis);\r\n cancelTimer = () => {\r\n clearTimeout(timeoutID);\r\n reject(\"Promise cancelled\");\r\n };\r\n });\r\n return [promise, cancelTimer];\r\n}\r\n\r\n//DEMO\r\nlet [promiseCancelled, cancelTimer] = delay(20000);\r\n(async() => {\r\n try {\r\n console.log(\"Promise result never printed\", await promiseCancelled);\r\n } catch (error) {\r\n console.error(\"Promise is rejected\", error);\r\n }\r\n})();\r\ncancelTimer();\r\n\r\nconst [promise, _] = delay(2000);\r\n(async() => {\r\n console.log(\"Promise result printed\", await promise);\r\n})();\n\n\n\n", "I recommend that you do not modify the promise by attaching an .abort method to it. Instead return two values from your delay function\n\nthe delayed value\na function that can be called to cancel the timeout\n\nCritically, we do not see \"x\" logged to the console because it was canceled -\n\n\nfunction useDelay (x = null, ms = 1000)\r\n{ let t\r\n return [\r\n new Promise(r => t = setTimeout(r, ms, x)), // 1\r\n _ => clearTimeout(t) // 2\r\n ]\r\n}\r\n\r\nconst [x, abortX] =\r\n useDelay(\"x\", 5000)\r\n \r\nconst [y, abortY] =\r\n useDelay(\"y canceled x\", 2000)\r\n \r\nx.then(console.log, console.error)\r\n\r\ny.then(console.log, console.error).finally(_ => abortX())\r\n\r\nconsole.log(\"loading...\")\r\n\r\n// loading...\r\n// y canceled x\n\n\n\n\ninteractive demo\nHere's an interactive example that allows you to wait for a delayed value or abort it -\n\n\nfunction useDelay (x = null, ms = 1000)\r\n{ let t\r\n return [\r\n new Promise(r => t = setTimeout(r, ms, x)), // 1\r\n _ => clearTimeout(t) // 2\r\n ]\r\n}\r\n\r\nconst [ input, output ] =\r\n document.querySelectorAll(\"input\")\r\n \r\nconst [go, abort] =\r\n document.querySelectorAll(\"button\")\r\n \r\nlet loading = false\r\n\r\nfunction reset ()\r\n{ loading = false\r\n input.value = \"\"\r\n go.disabled = false\r\n abort.disabled = true\r\n}\r\n\r\nfunction load ()\r\n{ loading = true\r\n go.disabled = true\r\n abort.disabled = false\r\n}\r\n\r\ngo.onclick = e => {\r\n if (loading) return\r\n load()\r\n \r\n const [delayedValue, abortValue] =\r\n useDelay(input.value, 3000)\r\n \r\n abort.onclick = _ => {\r\n abortValue()\r\n reset()\r\n }\r\n \r\n delayedValue\r\n .then(v => output.value = v)\r\n .catch(e => output.value = e.message)\r\n .finally(_ => reset())\r\n}\ncode { color: dodgerblue; }\n<input placeholder=\"enter a value...\" />\r\n<button>GO</button>\r\n<button disabled>ABORT</button>\r\n<input disabled placeholder=\"waiting for output...\" />\r\n\r\n<p>Click <code>GO</code> and the value will be transferred to the output in 5 seconds.</p>\r\n<p>If you click <code>ABORT</code> the transfer will be canceled.</p>\n\n\n\n", "Just use an AbortSignal:\n/**\n * Sleep for the specified number of milliseconds, or until the abort\n * signal gets triggered.\n * \n * @param ms {number}\n * @param signal {AbortSignal|undefined}\n */\nconst sleep = (ms, signal) =>\n new Promise<void>((ok, ng) => {\n /** @type {number} */\n let timeout\n\n const abortHandler = () => {\n clearTimeout(timeout)\n\n const aborted = new Error(`sleep aborted`)\n aborted.name = 'AbortError'\n\n ng(aborted)\n }\n signal?.addEventListener('abort', abortHandler)\n\n timeout = setTimeout(() => {\n signal?.removeEventListener('abort', abortHandler)\n ok()\n }, ms)\n })\n\n> const a = new AbortController()\nundefined\n> const s = sleep(900000, a.signal)\nundefined\n> a.abort()\nundefined\n> await s\nUncaught AbortError: sleep aborted\n at AbortSignal.abortHandler\n at innerInvokeEventListeners\n at invokeEventListeners\n at dispatch\n at AbortSignal.dispatchEvent\n at AbortSignal.[[[signalAbort]]]\n at AbortController.abort\n at <anonymous>:2:3\n>\n\nIf you prefer not to fail the promise, i.e. treat the abort signal as \"skip sleep\", simply replace the call to ng(aborted) with a call to ok().\n" ]
[ 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "asynchronous", "javascript", "promise" ]
stackoverflow_0061946587_asynchronous_javascript_promise.txt
Q: basic CRUD in area not working in ASP.NET Core I have several Areas in my learning/demo app. In 'MyArea/Models' I have 'MyModel.cs' When I try to add scaffolded item 'MVC controller with Views using EF' everything gets generated, I update database after that, but CRUD operations do not work when I start application. (When I add same Model but not in area everything is fine) For example, nothing happens when I click link 'create new' on Index. Can you please help me? I'm expecting that I can use scaffolding items in ASP.NET Core MVC areas. /area/partner/models ticket.cs namespace Website.Areas.Partner.Models { public class Ticket { public int Id { get; set; } public string Title { get; set; } } } /area/partner/controllers/ TicketsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Website.Areas.Partner.Models; using Website.Data; namespace Website.Areas.Partner.Controllers { [Area("Partner")] [Authorize] public class TicketsController : Controller { private readonly ApplicationDbContext _context; public TicketsController(ApplicationDbContext context) { _context = context; } // GET: Partner/Tickets public async Task<IActionResult> Index() { return _context.Ticket != null ? View(await _context.Ticket.ToListAsync()) : Problem("Entity set 'ApplicationDbContext.Ticket' is null."); } // GET: Partner/Tickets/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null || _context.Ticket == null) { return NotFound(); } var ticket = await _context.Ticket .FirstOrDefaultAsync(m => m.Id == id); if (ticket == null) { return NotFound(); } return View(ticket); } // GET: Partner/Tickets/Create public IActionResult Create() { return View(); } // POST: Partner/Tickets/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Title")] Ticket ticket) { if (ModelState.IsValid) { _context.Add(ticket); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(ticket); } // GET: Partner/Tickets/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null || _context.Ticket == null) { return NotFound(); } var ticket = await _context.Ticket.FindAsync(id); if (ticket == null) { return NotFound(); } return View(ticket); } // POST: Partner/Tickets/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Title")] Ticket ticket) { if (id != ticket.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(ticket); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TicketExists(ticket.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(ticket); } // GET: Partner/Tickets/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null || _context.Ticket == null) { return NotFound(); } var ticket = await _context.Ticket .FirstOrDefaultAsync(m => m.Id == id); if (ticket == null) { return NotFound(); } return View(ticket); } // POST: Partner/Tickets/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { if (_context.Ticket == null) { return Problem("Entity set 'ApplicationDbContext.Ticket' is null."); } var ticket = await _context.Ticket.FindAsync(id); if (ticket != null) { _context.Ticket.Remove(ticket); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool TicketExists(int id) { return (_context.Ticket?.Any(e => e.Id == id)).GetValueOrDefault(); } } } /area/partner/views/ticket index.cshtml @model IEnumerable<Website.Areas.Partner.Models.Ticket> @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> | <a asp-action="Details" asp-route- id="@item.Id">Details</a> | <a asp-action="Delete" asp-route- id="@item.Id">Delete</a> </td> </tr> } </tbody> </table> /data/ ApplicationDbContext using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Website.Models; using Website.Areas.Partner.Models; namespace Website.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>() .Property(e => e.FirstName) .HasMaxLength(20); modelBuilder.Entity<ApplicationUser>() .Property(e => e.LastName) .HasMaxLength(30); } public DbSet<LatestWork> LatestWork { get; set; } = default!; public DbSet<Website.Areas.Partner.Models.Ticket> Ticket { get; set; } = default!; } } A: I was missing Tag Helpers in views @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper *, AuthoringTagHelpers
basic CRUD in area not working in ASP.NET Core
I have several Areas in my learning/demo app. In 'MyArea/Models' I have 'MyModel.cs' When I try to add scaffolded item 'MVC controller with Views using EF' everything gets generated, I update database after that, but CRUD operations do not work when I start application. (When I add same Model but not in area everything is fine) For example, nothing happens when I click link 'create new' on Index. Can you please help me? I'm expecting that I can use scaffolding items in ASP.NET Core MVC areas. /area/partner/models ticket.cs namespace Website.Areas.Partner.Models { public class Ticket { public int Id { get; set; } public string Title { get; set; } } } /area/partner/controllers/ TicketsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Website.Areas.Partner.Models; using Website.Data; namespace Website.Areas.Partner.Controllers { [Area("Partner")] [Authorize] public class TicketsController : Controller { private readonly ApplicationDbContext _context; public TicketsController(ApplicationDbContext context) { _context = context; } // GET: Partner/Tickets public async Task<IActionResult> Index() { return _context.Ticket != null ? View(await _context.Ticket.ToListAsync()) : Problem("Entity set 'ApplicationDbContext.Ticket' is null."); } // GET: Partner/Tickets/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null || _context.Ticket == null) { return NotFound(); } var ticket = await _context.Ticket .FirstOrDefaultAsync(m => m.Id == id); if (ticket == null) { return NotFound(); } return View(ticket); } // GET: Partner/Tickets/Create public IActionResult Create() { return View(); } // POST: Partner/Tickets/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Title")] Ticket ticket) { if (ModelState.IsValid) { _context.Add(ticket); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(ticket); } // GET: Partner/Tickets/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null || _context.Ticket == null) { return NotFound(); } var ticket = await _context.Ticket.FindAsync(id); if (ticket == null) { return NotFound(); } return View(ticket); } // POST: Partner/Tickets/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Title")] Ticket ticket) { if (id != ticket.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(ticket); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TicketExists(ticket.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(ticket); } // GET: Partner/Tickets/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null || _context.Ticket == null) { return NotFound(); } var ticket = await _context.Ticket .FirstOrDefaultAsync(m => m.Id == id); if (ticket == null) { return NotFound(); } return View(ticket); } // POST: Partner/Tickets/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { if (_context.Ticket == null) { return Problem("Entity set 'ApplicationDbContext.Ticket' is null."); } var ticket = await _context.Ticket.FindAsync(id); if (ticket != null) { _context.Ticket.Remove(ticket); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool TicketExists(int id) { return (_context.Ticket?.Any(e => e.Id == id)).GetValueOrDefault(); } } } /area/partner/views/ticket index.cshtml @model IEnumerable<Website.Areas.Partner.Models.Ticket> @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Title) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> | <a asp-action="Details" asp-route- id="@item.Id">Details</a> | <a asp-action="Delete" asp-route- id="@item.Id">Delete</a> </td> </tr> } </tbody> </table> /data/ ApplicationDbContext using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Website.Models; using Website.Areas.Partner.Models; namespace Website.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>() .Property(e => e.FirstName) .HasMaxLength(20); modelBuilder.Entity<ApplicationUser>() .Property(e => e.LastName) .HasMaxLength(30); } public DbSet<LatestWork> LatestWork { get; set; } = default!; public DbSet<Website.Areas.Partner.Models.Ticket> Ticket { get; set; } = default!; } }
[ "I was missing Tag Helpers in views\n@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers\n@addTagHelper *, AuthoringTagHelpers\n\n" ]
[ 0 ]
[]
[]
[ "asp.net_core_mvc", "c#", "entity_framework" ]
stackoverflow_0074618828_asp.net_core_mvc_c#_entity_framework.txt
Q: Serialization issue with Spark and ObjectMapper in Spring Boot-based applicatuon I'm using Spark and there's one of my Spring Boot-based application beans: @Component @RequiredArgsConstructor public class SomeService implements FlatMapFunction<T, K> { private final ObjectMapper mapper; } ObjectMapper here is the standard one taken from application context. The problem is that the app fails with org.apache.spark.SparkException: Task not serializable. Here's serialization stack: Caused by: java.io.NotSerializableException: org.springframework.http.converter.json.SpringHandlerInstantiator Serialization stack: - object not serializable (class: org.springframework.http.converter.json.SpringHandlerInstantiator, value: org.springframework.http.converter.json.SpringHandlerInstantiator@6e4912db) - field (class: com.fasterxml.jackson.databind.cfg.BaseSettings, name: _handlerInstantiator, type: class com.fasterxml.jackson.databind.cfg.HandlerInstantiator) - object (class com.fasterxml.jackson.databind.cfg.BaseSettings, com.fasterxml.jackson.databind.cfg.BaseSettings@155616d8) - field (class: com.fasterxml.jackson.databind.cfg.MapperConfig, name: _base, type: class com.fasterxml.jackson.databind.cfg.BaseSettings) - object (class com.fasterxml.jackson.databind.DeserializationConfig, com.fasterxml.jackson.databind.DeserializationConfig@66e72ca2) - field (class: com.fasterxml.jackson.databind.ObjectMapper, name: _deserializationConfig, type: class com.fasterxml.jackson.databind.DeserializationConfig) - object (class com.fasterxml.jackson.databind.ObjectMapper, com.fasterxml.jackson.databind.ObjectMapper@433ef204) - field (class: com.smth.SomeService, name: mapper, type: class com.fasterxml.jackson.databind.ObjectMapper) So the problem is about non-serializable SpringHandlerInstantiator. This far I work this around by assigning mapper field in constructor manually: public SomeService() { this.mapper = new ObjectMapper(); } Is there a way to somehow solve this properly, i. e. relying on Spring's DI? I use Spring Boot 2.6.7 and Spark 2.11. A: Alternatively, try to configure ObjectMapper bean to use a different HandlerInstantiator that is serializable. This would allow you to continue using dependency injection for the ObjectMapper bean, and you would not need to create a new instance inside SomeService class. @Configuration public class MyConfiguration { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setHandlerInstantiator(new MyHandlerInstantiator()); return mapper; } } In this example, MyHandlerInstantiator is a custom class that extends HandlerInstantiator and is serializable. Implement this class to provide custom behavior for instantiating deserialization handlers (e.g. by patching code of SpringHandlerInstantiator). Once this configuration is in place, inject ObjectMapper bean into SomeService class using dependency injection, and the ObjectMapper instance will use your custom HandlerInstantiator instead of the non-serializable SpringHandlerInstantiator class. This should allow SomeService class to be serializable and be used in a distributed environment like Apache Spark.
Serialization issue with Spark and ObjectMapper in Spring Boot-based applicatuon
I'm using Spark and there's one of my Spring Boot-based application beans: @Component @RequiredArgsConstructor public class SomeService implements FlatMapFunction<T, K> { private final ObjectMapper mapper; } ObjectMapper here is the standard one taken from application context. The problem is that the app fails with org.apache.spark.SparkException: Task not serializable. Here's serialization stack: Caused by: java.io.NotSerializableException: org.springframework.http.converter.json.SpringHandlerInstantiator Serialization stack: - object not serializable (class: org.springframework.http.converter.json.SpringHandlerInstantiator, value: org.springframework.http.converter.json.SpringHandlerInstantiator@6e4912db) - field (class: com.fasterxml.jackson.databind.cfg.BaseSettings, name: _handlerInstantiator, type: class com.fasterxml.jackson.databind.cfg.HandlerInstantiator) - object (class com.fasterxml.jackson.databind.cfg.BaseSettings, com.fasterxml.jackson.databind.cfg.BaseSettings@155616d8) - field (class: com.fasterxml.jackson.databind.cfg.MapperConfig, name: _base, type: class com.fasterxml.jackson.databind.cfg.BaseSettings) - object (class com.fasterxml.jackson.databind.DeserializationConfig, com.fasterxml.jackson.databind.DeserializationConfig@66e72ca2) - field (class: com.fasterxml.jackson.databind.ObjectMapper, name: _deserializationConfig, type: class com.fasterxml.jackson.databind.DeserializationConfig) - object (class com.fasterxml.jackson.databind.ObjectMapper, com.fasterxml.jackson.databind.ObjectMapper@433ef204) - field (class: com.smth.SomeService, name: mapper, type: class com.fasterxml.jackson.databind.ObjectMapper) So the problem is about non-serializable SpringHandlerInstantiator. This far I work this around by assigning mapper field in constructor manually: public SomeService() { this.mapper = new ObjectMapper(); } Is there a way to somehow solve this properly, i. e. relying on Spring's DI? I use Spring Boot 2.6.7 and Spark 2.11.
[ "Alternatively, try to configure ObjectMapper bean to use a different HandlerInstantiator that is serializable. This would allow you to continue using dependency injection for the ObjectMapper bean, and you would not need to create a new instance inside SomeService class.\n@Configuration\npublic class MyConfiguration {\n \n @Bean\n public ObjectMapper objectMapper() {\n ObjectMapper mapper = new ObjectMapper();\n mapper.setHandlerInstantiator(new MyHandlerInstantiator());\n return mapper;\n }\n}\n\nIn this example, MyHandlerInstantiator is a custom class that extends HandlerInstantiator and is serializable. Implement this class to provide custom behavior for instantiating deserialization handlers (e.g. by patching code of SpringHandlerInstantiator).\nOnce this configuration is in place, inject ObjectMapper bean into SomeService class using dependency injection, and the ObjectMapper instance will use your custom HandlerInstantiator instead of the non-serializable SpringHandlerInstantiator class. This should allow SomeService class to be serializable and be used in a distributed environment like Apache Spark.\n" ]
[ 1 ]
[]
[]
[ "apache_spark", "jackson", "java", "objectmapper", "spring" ]
stackoverflow_0074654722_apache_spark_jackson_java_objectmapper_spring.txt
Q: Group associative array data by key prefix I have a array like this Array ( [operator_15] => 3 [fiter_15] => 4 [operator_17] => 5 [fiter_17] => 5 [operator_19] => 4 [fiter_19] => 2 ) I want to separate this array in to 2 arrays: key starting from fiter_ key starting from operator_ I used array filter and it doesn't work. any other option? $array = array_filter( $fitered_values, function($key) { return strpos($key, 'fiter_') === 0; } ); A: Just loop the array and substring what is before the _ with strpos and substr then you can filter them to a new array as this. This method will also work with new array keys, see example: $arr = array ( "operator_15" => 3, "fiter_15" => 4, "operator_17" => 5, "fiter_17" => 5, "somethingelse_12" => 99 // <--- Notice this line. ); foreach($arr as $key => $val){ $subarr = substr($key,0, strpos($key, "_")); $new[$subarr][$key] = $val; } var_dump($new); output: array(3) { ["operator"]=> array(2) { ["operator_15"]=> int(3) ["operator_17"]=> int(5) } ["fiter"]=> array(2) { ["fiter_15"]=> int(4) ["fiter_17"]=> int(5) } ["somethingelse"]=> // <-- is here now in it's own group with no code added array(1) { ["somethingelse_12"]=> int(99) } } A: Give a try with below and see if its solve your problem $array = array ( 'operator_15' => 3, 'fiter_15' => 4, 'operator_17' => 5, 'fiter_17' => 5, 'operator_19' => 4, 'fiter_19' => 2 ); $operator=array(); $filter=array(); foreach($array as $key => $value){ if (strpos($key, 'operator_') !== false) { $operator[$key] = $value; } if (strpos($key, 'fiter_') !== false) { $filter[$key] = $value; } } print_r($operator); print_r($filter); A: This is a working example: $a = array ( 'operator_15' => 3, 'fiter_15' => 4, 'operator_17' => 5, 'fiter_17' => 5, 'operator_19' => 4, 'fiter_19' => 2 ); $fiter_array = array(); $operator_array = array(); foreach($a as $key => $val) { if(strpos($key, 'fiter') !== false) { array_push($fiter_array, $a[$key]); // or if you want to maintain the key $fiter_array[$key] = $val; } else { array_push($operator_array, $a[$key]); // or if you want to maintain the key $operator_array[$key] = $val; } }; var_dump($fiter_array); var_dump($operator_array); A: While iterating your array, populate a new array with first level (grouping) keys based on the prefix (substring before the underscore), then push the original associative data into that group. Code: (Demo) $result = []; foreach ($array as $k => $v) { $result[strtok($k, '_')][$k] = $v; } var_export($result); It is suboptimal programming to declare individual variables because this removes the convenience of being able to easily iterate related data (related by structure). The above snippet will allow you to iterate $result and access all data sets or you can individually access a particular subset like $result['fiter'].
Group associative array data by key prefix
I have a array like this Array ( [operator_15] => 3 [fiter_15] => 4 [operator_17] => 5 [fiter_17] => 5 [operator_19] => 4 [fiter_19] => 2 ) I want to separate this array in to 2 arrays: key starting from fiter_ key starting from operator_ I used array filter and it doesn't work. any other option? $array = array_filter( $fitered_values, function($key) { return strpos($key, 'fiter_') === 0; } );
[ "Just loop the array and substring what is before the _ with strpos and substr then you can filter them to a new array as this.\nThis method will also work with new array keys, see example:\n$arr = array ( \"operator_15\" => 3, \n \"fiter_15\" => 4, \n \"operator_17\" => 5, \n \"fiter_17\" => 5, \n \"somethingelse_12\" => 99 // <--- Notice this line.\n );\n\nforeach($arr as $key => $val){\n $subarr = substr($key,0, strpos($key, \"_\"));\n $new[$subarr][$key] = $val;\n}\n\nvar_dump($new);\n\noutput: \narray(3) {\n[\"operator\"]=>\n array(2) {\n [\"operator_15\"]=>\n int(3)\n [\"operator_17\"]=>\n int(5)\n }\n [\"fiter\"]=>\n array(2) {\n [\"fiter_15\"]=>\n int(4)\n [\"fiter_17\"]=>\n int(5)\n }\n [\"somethingelse\"]=> // <-- is here now in it's own group with no code added\n array(1) {\n [\"somethingelse_12\"]=>\n int(99)\n }\n}\n\n", "Give a try with below and see if its solve your problem\n$array = array ( \n 'operator_15' => 3,\n 'fiter_15' => 4,\n 'operator_17' => 5,\n 'fiter_17' => 5,\n 'operator_19' => 4,\n 'fiter_19' => 2 );\n\n$operator=array();\n$filter=array();\n\nforeach($array as $key => $value){\n if (strpos($key, 'operator_') !== false) {\n $operator[$key] = $value;\n }\n\n if (strpos($key, 'fiter_') !== false) {\n $filter[$key] = $value;\n } \n}\n\nprint_r($operator);\nprint_r($filter);\n\n", "This is a working example:\n$a = array ( 'operator_15' => 3, 'fiter_15' => 4, 'operator_17' => 5, 'fiter_17' => 5, 'operator_19' => 4, 'fiter_19' => 2 );\n$fiter_array = array();\n$operator_array = array();\nforeach($a as $key => $val)\n{\n if(strpos($key, 'fiter') !== false)\n {\n array_push($fiter_array, $a[$key]);\n // or if you want to maintain the key\n $fiter_array[$key] = $val;\n }\n else\n {\n array_push($operator_array, $a[$key]);\n // or if you want to maintain the key\n $operator_array[$key] = $val;\n }\n};\nvar_dump($fiter_array);\nvar_dump($operator_array);\n\n", "While iterating your array, populate a new array with first level (grouping) keys based on the prefix (substring before the underscore), then push the original associative data into that group.\nCode: (Demo)\n$result = [];\nforeach ($array as $k => $v) {\n $result[strtok($k, '_')][$k] = $v;\n}\nvar_export($result);\n\nIt is suboptimal programming to declare individual variables because this removes the convenience of being able to easily iterate related data (related by structure).\nThe above snippet will allow you to iterate $result and access all data sets or you can individually access a particular subset like $result['fiter'].\n" ]
[ 5, 3, 0, 0 ]
[]
[]
[ "arrays", "grouping", "key", "php", "prefix" ]
stackoverflow_0051947631_arrays_grouping_key_php_prefix.txt
Q: how to filter and count a table value by month I have a database with: user_id impressions date A new record is added to the table every time an imp was received (who received, how much, and when). Question: how to filter and count unique userid's, who received less than 3 impressions during one month, but in some other (any) month of the year received more than 3 imp? (Assuming that user_id's aren't a stable number of people, but new/different users can be added any day/month) I can't wrap my head around an algorithm, and an even bigger mystery is how to write SQL for it, as I'm a newbie. I was thinking about maybe selecting all unique user_id's in general over the year and adding them to a temporary table. Then counting every user's amount of impressions month after month and checking: 1) if in one month imp were < 3; 2) and if in some other month imp > 3. And if these conditions were not met, then that user_id had to be removed from a temporary table. After that, the number of suitable users could be summed and received. It does feel like a huge over complication of things. So maybe someone knows a better/simpler/nicer way to get these results. A: I have put what I think is the start of a solution in the fiddle: SQL Fiddle Schema: CREATE TABLE usr (user_id int, Name varchar(5), Age int) ; INSERT INTO usr (user_id, Name, Age) VALUES (1, 'John', 12), (2, 'Annie', 29), (3, 'John', 44) ; CREATE TABLE impre (user_id int, imp int, datez datetime) ; INSERT INTO impre (user_id, imp, datez) VALUES (1, 5, '2012-03-12 00:00:00'), (1, 3, '2012-03-15 00:00:00'), (1, 3, '2012-04-17 00:00:00'), (1, 2, '2012-04-13 00:00:00'), (2, 2, '2012-04-15 00:00:00'), (2, 1, '2012-05-07 00:00:00'), (3, 1, '2012-05-08 00:00:00'), (3, 5, '2012-06-07 00:00:00') ; Query: select * from ( select user_id, SUM(imp) IMPRESSIONS, MONTH(datez) from impre group by MONTH(datez), user_id order by user_id ) as tb where IMPRESSIONS >= 3 What it does is that it is aggregating each user based on the amount of impressions and also by the month. The inner select is the table where the aggregation is happening, and the outer select is the filtering. I am just not sure what it really means to have less than 3 impressions in ONE month and in ANY other month have more than 3 impressions. Does it mean that we are looking for user_ids that have at least one month with total impressions less than 3, and also any other month greater than 3? Could you explain the logic programmatically?
how to filter and count a table value by month
I have a database with: user_id impressions date A new record is added to the table every time an imp was received (who received, how much, and when). Question: how to filter and count unique userid's, who received less than 3 impressions during one month, but in some other (any) month of the year received more than 3 imp? (Assuming that user_id's aren't a stable number of people, but new/different users can be added any day/month) I can't wrap my head around an algorithm, and an even bigger mystery is how to write SQL for it, as I'm a newbie. I was thinking about maybe selecting all unique user_id's in general over the year and adding them to a temporary table. Then counting every user's amount of impressions month after month and checking: 1) if in one month imp were < 3; 2) and if in some other month imp > 3. And if these conditions were not met, then that user_id had to be removed from a temporary table. After that, the number of suitable users could be summed and received. It does feel like a huge over complication of things. So maybe someone knows a better/simpler/nicer way to get these results.
[ "I have put what I think is the start of a solution in the fiddle:\nSQL Fiddle\nSchema:\nCREATE TABLE usr \n (user_id int, Name varchar(5), Age int)\n;\n \nINSERT INTO usr \n (user_id, Name, Age)\nVALUES\n (1, 'John', 12),\n (2, 'Annie', 29),\n (3, 'John', 44)\n;\n\nCREATE TABLE impre\n (user_id int, imp int, datez datetime)\n;\n \nINSERT INTO impre\n (user_id, imp, datez)\nVALUES\n (1, 5, '2012-03-12 00:00:00'),\n (1, 3, '2012-03-15 00:00:00'),\n (1, 3, '2012-04-17 00:00:00'),\n (1, 2, '2012-04-13 00:00:00'),\n (2, 2, '2012-04-15 00:00:00'),\n (2, 1, '2012-05-07 00:00:00'),\n (3, 1, '2012-05-08 00:00:00'),\n (3, 5, '2012-06-07 00:00:00')\n;\n\nQuery:\nselect * from (\n select user_id, SUM(imp) IMPRESSIONS, MONTH(datez)\n from impre\n group by MONTH(datez), user_id\n order by user_id\n ) as tb\nwhere IMPRESSIONS >= 3\n\nWhat it does is that it is aggregating each user based on the amount of impressions and also by the month. The inner select is the table where the aggregation is happening, and the outer select is the filtering.\nI am just not sure what it really means to have less than 3 impressions in ONE month and in ANY other month have more than 3 impressions. Does it mean that we are looking for user_ids that have at least one month with total impressions less than 3, and also any other month greater than 3?\nCould you explain the logic programmatically?\n" ]
[ 0 ]
[]
[]
[ "sql" ]
stackoverflow_0074670592_sql.txt
Q: Python Error Help : IndexError: list index out of range def read_file(): '''reads input file returns a list of information''' #your code here A: The error IndexError: list index out of range is raised when you try to access an index in a list that doesn't exist. For example, if you try to access the 10th element of a list that only has 3 elements, you will get this error. In your code, you are trying to access the elements in temp using the indices [0], [1], [2], and [3], but it looks like temp might not have enough elements for that. To avoid this error, you should first check that temp has enough elements before trying to access them. You can do this using an if statement and the len() function, like this: if len(temp) >= 4: students_dict[temp[0]] = [temp[1], temp[2], temp[3]] Alternatively, you can use the get() method to safely access elements in temp, like this: students_dict[temp[0]] = [temp.get(1), temp.get(2), temp.get(3)] This will set the elements in the list to None if they don't exist in temp, rather than raising an error. I hope this helps! Let me know if you have any other questions.
Python Error Help : IndexError: list index out of range
def read_file(): '''reads input file returns a list of information''' #your code here
[ "The error IndexError: list index out of range is raised when you try to access an index in a list that doesn't exist. For example, if you try to access the 10th element of a list that only has 3 elements, you will get this error.\nIn your code, you are trying to access the elements in temp using the indices [0], [1], [2], and [3], but it looks like temp might not have enough elements for that.\nTo avoid this error, you should first check that temp has enough elements before trying to access them. You can do this using an if statement and the len() function, like this:\nif len(temp) >= 4:\n students_dict[temp[0]] = [temp[1], temp[2], temp[3]]\n\nAlternatively, you can use the get() method to safely access elements in temp, like this:\nstudents_dict[temp[0]] = [temp.get(1), temp.get(2), temp.get(3)]\n\nThis will set the elements in the list to None if they don't exist in temp, rather than raising an error.\nI hope this helps! Let me know if you have any other questions.\n" ]
[ 1 ]
[]
[]
[ "index_error", "python" ]
stackoverflow_0074671322_index_error_python.txt
Q: Chrome Extension- Automate/Perform Hover Event on an element in webpage Wanted to perform hover on nav menu item which should show the sub menu. chrome.scripting.executeScript( { target: {tabId: tabId}, func: hoverFunction, args:[id] }, (injectionResults) => { // perform something post execution }); function hoverFunction(id){ let element = document.getElementById(id); element.addEventListener('mouseover', function() { console.log('Event triggered'); }); var event = new MouseEvent('mouseover', { 'view': window, 'bubbles': true, 'cancelable': true }); element.dispatchEvent(event); } Tried to simulate the mouse over event on a menu item, I see the event getting triggered as I see console log getting printed but the submenu doesn't popup on script execution.. Tried to simulate/dispatch the mouse over event on a menu item, I see the event getting triggered as I see console log getting printed but the submenu doesn't popup on script execution.. My expectation is I should be able to automate/perform hover on a element with script and get the expected events to happen..In this case , the submenu to popup or to show tooltip for the elements if any on mouseover.. A: I try to shoot blind: in my opinion there is a good chance it will work by adding world: "MAIN" inside executeScript A: It looks like you are trying to dispatch a mouseover event on an element, but this event will not automatically trigger any event handlers that are attached to the element. Instead, you will need to call the event handlers manually. Try: element.onmouseover(); A: It looks like you are trying to use a script to simulate a mouseover event on an element in the page. However, it is important to keep in mind that just dispatching a mouseover event on an element does not necessarily mean that the expected behavior (in this case, the submenu appearing) will happen. This is because the element's event listeners and associated behavior are determined by the code on the page, not by your script. One way to solve this problem would be to use the executeScript function to inject your own event listener and behavior into the page. For example, you could use executeScript to attach a mouseover event listener to the element, and within that event listener you could use executeScript again to run the code that would normally run when the element is hovered over. Here is an example of how you might do this: // First, use executeScript to attach a mouseover event listener to the element chrome.scripting.executeScript( { target: {tabId: tabId}, func: addMouseoverListener, args:[id] }, (injectionResults) => { // Perform something after the listener is attached } ); function addMouseoverListener(id) { let element = document.getElementById(id); element.addEventListener('mouseover', function() { // When the mouseover event is triggered, use executeScript again to run the code that would normally run when the element is hovered over chrome.scripting.executeScript( { target: {tabId: tabId}, code: ` // Code to run when the element is hovered over goes here console.log('Element hovered over'); ` }, (injectionResults) => { // Perform something after the code is executed } ); }); } You can then use the dispatchEvent function to trigger the mouseover event on the element, which should cause your event listener to run the code that you specified. This should allow you to simulate the hover behavior and get the expected results. Keep in mind that the exact code you will need to run when the element is hovered over will depend on the specific implementation of the page, so you may need to adjust the code to fit your needs. Additionally, you may need to handle other events, such as mouseout, in order to properly simulate the hover behavior.
Chrome Extension- Automate/Perform Hover Event on an element in webpage
Wanted to perform hover on nav menu item which should show the sub menu. chrome.scripting.executeScript( { target: {tabId: tabId}, func: hoverFunction, args:[id] }, (injectionResults) => { // perform something post execution }); function hoverFunction(id){ let element = document.getElementById(id); element.addEventListener('mouseover', function() { console.log('Event triggered'); }); var event = new MouseEvent('mouseover', { 'view': window, 'bubbles': true, 'cancelable': true }); element.dispatchEvent(event); } Tried to simulate the mouse over event on a menu item, I see the event getting triggered as I see console log getting printed but the submenu doesn't popup on script execution.. Tried to simulate/dispatch the mouse over event on a menu item, I see the event getting triggered as I see console log getting printed but the submenu doesn't popup on script execution.. My expectation is I should be able to automate/perform hover on a element with script and get the expected events to happen..In this case , the submenu to popup or to show tooltip for the elements if any on mouseover..
[ "I try to shoot blind:\nin my opinion there is a good chance it will work by adding world: \"MAIN\"\ninside executeScript\n", "It looks like you are trying to dispatch a mouseover event on an element, but this event will not automatically trigger any event handlers that are attached to the element. Instead, you will need to call the event handlers manually.\nTry:\nelement.onmouseover();\n\n", "It looks like you are trying to use a script to simulate a mouseover event on an element in the page. However, it is important to keep in mind that just dispatching a mouseover event on an element does not necessarily mean that the expected behavior (in this case, the submenu appearing) will happen. This is because the element's event listeners and associated behavior are determined by the code on the page, not by your script.\nOne way to solve this problem would be to use the executeScript function to inject your own event listener and behavior into the page. For example, you could use executeScript to attach a mouseover event listener to the element, and within that event listener you could use executeScript again to run the code that would normally run when the element is hovered over.\nHere is an example of how you might do this:\n// First, use executeScript to attach a mouseover event listener to the element\nchrome.scripting.executeScript(\n {\n target: {tabId: tabId},\n func: addMouseoverListener,\n args:[id]\n },\n (injectionResults) => {\n // Perform something after the listener is attached\n }\n);\n\nfunction addMouseoverListener(id) {\n let element = document.getElementById(id);\n element.addEventListener('mouseover', function() {\n // When the mouseover event is triggered, use executeScript again to run the code that would normally run when the element is hovered over\n chrome.scripting.executeScript(\n {\n target: {tabId: tabId},\n code: `\n // Code to run when the element is hovered over goes here\n console.log('Element hovered over');\n `\n },\n (injectionResults) => {\n // Perform something after the code is executed\n }\n );\n });\n}\n\nYou can then use the dispatchEvent function to trigger the mouseover event on the element, which should cause your event listener to run the code that you specified. This should allow you to simulate the hover behavior and get the expected results.\nKeep in mind that the exact code you will need to run when the element is hovered over will depend on the specific implementation of the page, so you may need to adjust the code to fit your needs. Additionally, you may need to handle other events, such as mouseout, in order to properly simulate the hover behavior.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "chrome_extension_manifest_v3", "google_chrome_extension", "hover", "javascript", "mouseover" ]
stackoverflow_0074562896_chrome_extension_manifest_v3_google_chrome_extension_hover_javascript_mouseover.txt
Q: Extract rows of strings between two rows of partial string matches (not inclusive of the matching string row) in R I have a file that is essentially made up of rows of strings. I am trying to extract the sections of rows into individual files between rows of strings. The file looks like this: **File Begins** "Name: XXX_2" "Description: Object 1210 , 111" "Sampling_info: statexy=1346" "Num value: 15" "32 707; 33 71; 37 11; 38 3; 40 146; " "41 64; 42 36; 43 24; 44 69; 45 324; " "46 49; 47 52; 50 11; 51 90; 52 22; " "Name: XXX_3" "Description: Object 1341 , 111" "Sampling_info: statexy=1346" "Num value: 18" "32 999; 33 4; 34 17; 39 84; 41 84; " "42 4; 44 137; 45 102; 50 13; 52 22; " "53 4; 54 4; 55 84; 58 40; 59 13; " "65 57; 66 13; 67 173; " "Name: XXX_4" "Description: Object 1561 , 111" "Sampling_info: statexy=1346" "Num value: 21" "32 925; 34 5; 40 409; 41 55; 44 43; " "45 154; 46 5; 47 5; 50 38; 52 16; " "56 99; 58 5; 59 110; 61 5; 62 55; " "63 11; 68 5; 69 38; 70 22; 73 999; " "74 49; " "Name: XXX_5" **And then the next entry begins** I want to get the numbers between "Num value: 15" and "Name: XXX_3" while excluding those two rows and put it into it's own text file. Same for the next two entries. This will be implemented into a for loop or other to extract all the independent entries in the file to their own file. I tried str_match but it returns NA: str_match(data, "Name: UNK_1\\s*(.*?)\\s*Name: UNK_2") I also tried gsub but it returned the whole file...: gsub(".*Name: UNK_1 (.+) Name: UNK_2.*", "\\1", data) Is there something wring with my implementation of str_match and gsub? Thank you in advance! A: What about something like this: library(tidyverse) # Build dataset df <- data.frame( col1 = c("Name: XXX_2" , "Description: Object 1210 , 111", "Sampling_info: statexy=1346", "Num value: 15", "32 707; 33 71; 37 11; 38 3; 40 146; " , "41 64; 42 36; 43 24; 44 69; 45 324; " , "46 49; 47 52; 50 11; 51 90; 52 22; " , "Name: XXX_3" , "Shouldn't get this number: 8675309") ) df %>% # Combine row into single string map_chr(paste, collapse = " ") %>% # Remove everything before "Num value:" str_extract(" Num value:.*") %>% # Remove numbers after "Num value: str_remove("Num value: \\d+") %>% # Remove everything after "Name:" str_extract(" .*Name:") %>% # Extract digits str_extract_all("\\d+") %>% unlist() %>% as.numeric() #[1] 32 707 33 71 37 11 38 3 40 146 41 64 42 36 43 24 44 69 45 #[20] 324 46 49 47 52 50 11 51 90 52 22 A: One approach without loops: library(dplyr) library(tidyr) df <- read.delim('path_to_input_file/your_file.txt', sep = ':', header = FALSE) df %>% separate(V1, into = c('param', 'value'), sep = ' *: *') %>% filter(param == 'Name' | grepl(';', param)) %>% fill(value, .direction = 'down') %>% filter(param != 'Name') %>% separate_rows(param, sep = ' *; *') ## follow up with blank removal, conversion to numeric as needed Output (column value contains the name from the initial name: xxx lines) # A tibble: 18 x 2 param value <chr> <chr> 1 "32 707" "XXX_2 " 2 "33 71" "XXX_2 " 3 "37 11" "XXX_2 " 4 "38 3" "XXX_2 " 5 "40 146" "XXX_2 " 6 "" "XXX_2 " You might want to partition the above pipeline and inspect the intermediate dataframes to see what's going on at which step. A: with base and for, and various notes. library(stringr) # msp_list <- scan(file='', what = character()) #paste in 1:24 above <return> # dput(msp_list) msp_list <- c("Name: XXX_2", "Description: Object 1210 , 111", "Sampling_info: statexy=1346", "Num value: 15", "32 707; 33 71; 37 11; 38 3; 40 146; ", "41 64; 42 36; 43 24; 44 69; 45 324; ", "46 49; 47 52; 50 11; 51 90; 52 22; ", "Name: XXX_3", "Description: Object 1341 , 111", "Sampling_info: statexy=1346", "Num value: 18", "32 999; 33 4; 34 17; 39 84; 41 84; ", "42 4; 44 137; 45 102; 50 13; 52 22; ", "53 4; 54 4; 55 84; 58 40; 59 13; ", "65 57; 66 13; 67 173; ", "Name: XXX_4", "Description: Object 1561 , 111", "Sampling_info: statexy=1346", "Num value: 21", "32 925; 34 5; 40 409; 41 55; 44 43; ", "45 154; 46 5; 47 5; 50 38; 52 16; ", "56 99; 58 5; 59 110; 61 5; 62 55; ", "63 11; 68 5; 69 38; 70 22; 73 999; ", "74 49; ") # get rid of trailing whitespace that will be annoying later msp_lst <- trimws(msp_list, 'r') index msp_list, for start and end of future sub dfs. I am assuming you .mps is properly formed, which is to say all are complete (I've wished away your line 25 above). msp_name_rle <- rle(str_starts(msp_list, 'Name'))$lengths msp_rle_mtx<- matrix(msp_name_rle, nrow = length(msp_name_rle)/2, ncol = 2, byrow = TRUE) msp_rowsums <-matrix(rowSums(msp_rle_mtx), ncol = 1) starts <- which(str_starts(msp_list, 'Name') == TRUE) starts [1] 1 8 16 ends <- as.vector(starts + msp_rowsums -1) ends [1] 7 15 24 # and then get names as they will be useful later > msp_names <- trimws(str_extract(msp_list[which(str_starts(msp_list, 'Name') == TRUE)], '\\s\\w+')) # a similar extract could be done on ? whatever is informative and applied to attributes later (not done here) # initialize an object to receive output from the `for` loop many_msp <- list() At this point we have what we need in the global environment to inform the operations in the for loop so it won't complain that some value isn't found. And things are sufficiently detailed to operate on one index (i.e. not nested i,j), well, at least I hope, and we'll do a bunch of data cleaning here, but hopefully return an extracted list of .msp values in a two column df each (that basically relies on the regularity of the .msp file format # first checking that the indexing is working for(i in 1:length(starts)) { many_msp[[i]] <- df3[starts[i]:ends[i], ] } many_msp[[3]] [[3]] [1] "Name: XXX_4" [2] "Description: Object 1561 , 111" [3] "Sampling_info: statexy=1346" [4] "Num value: 21" [5] "32 925; 34 5; 40 409; 41 55; 44 43; " [6] "45 154; 46 5; 47 5; 50 38; 52 16; " [7] "56 99; 58 5; 59 110; 61 5; 62 55; " [8] "63 11; 68 5; 69 38; 70 22; 73 999; " [9] "74 49; " # OK. Now, we can either make another `for`, or extend what happens within this one. Extending: for(i in 1:length(starts)) { many_msp[[i]] <- msp_list[starts[i]:ends[i]] #return only values many_msp[[i]] <- many_msp[[i]][5:lengths(many_msp)[i]] #take to vector, after a bunch of tidying up many_msp[[i]] <- as.numeric(strsplit(trimws(paste(gsub(';', '', many_msp[[i]]), collapse = ''), 'r'), ' ')[[1]]) #take to data.frame many_msp[[i]] <- data.frame(col1 = many_msp[[i]][seq(1, length(many_msp[[i]]), 2)], col2 = many_msp[[i]][seq(2, length(many_msp[[i]]), 2)]) # name the data.frames names(many_msp)[i] <- msp_names[[i]] } names(many_msp) [1] "XXX_2" "XXX_3" "XXX_4" many_msp$XXX_4 col1 col2 1 32 925 2 34 5 3 40 409 4 41 55 5 44 43 6 45 154 7 46 5 8 47 5 9 50 38 10 52 16 11 56 99 12 58 5 13 59 110 14 61 5 15 62 55 16 63 11 17 68 5 18 69 38 19 70 22 20 73 999 21 74 49 so can be done with a for loop. The accessing/addressing in this list stuff may be a little less apparent when reaching into col1, col2 values as you have many_msp$XXX_4$col1 [1] 32 34 40 41 44 45 46 47 50 52 56 58 59 61 62 63 68 69 70 73 74 which is unexpected, at first.
Extract rows of strings between two rows of partial string matches (not inclusive of the matching string row) in R
I have a file that is essentially made up of rows of strings. I am trying to extract the sections of rows into individual files between rows of strings. The file looks like this: **File Begins** "Name: XXX_2" "Description: Object 1210 , 111" "Sampling_info: statexy=1346" "Num value: 15" "32 707; 33 71; 37 11; 38 3; 40 146; " "41 64; 42 36; 43 24; 44 69; 45 324; " "46 49; 47 52; 50 11; 51 90; 52 22; " "Name: XXX_3" "Description: Object 1341 , 111" "Sampling_info: statexy=1346" "Num value: 18" "32 999; 33 4; 34 17; 39 84; 41 84; " "42 4; 44 137; 45 102; 50 13; 52 22; " "53 4; 54 4; 55 84; 58 40; 59 13; " "65 57; 66 13; 67 173; " "Name: XXX_4" "Description: Object 1561 , 111" "Sampling_info: statexy=1346" "Num value: 21" "32 925; 34 5; 40 409; 41 55; 44 43; " "45 154; 46 5; 47 5; 50 38; 52 16; " "56 99; 58 5; 59 110; 61 5; 62 55; " "63 11; 68 5; 69 38; 70 22; 73 999; " "74 49; " "Name: XXX_5" **And then the next entry begins** I want to get the numbers between "Num value: 15" and "Name: XXX_3" while excluding those two rows and put it into it's own text file. Same for the next two entries. This will be implemented into a for loop or other to extract all the independent entries in the file to their own file. I tried str_match but it returns NA: str_match(data, "Name: UNK_1\\s*(.*?)\\s*Name: UNK_2") I also tried gsub but it returned the whole file...: gsub(".*Name: UNK_1 (.+) Name: UNK_2.*", "\\1", data) Is there something wring with my implementation of str_match and gsub? Thank you in advance!
[ "What about something like this:\nlibrary(tidyverse)\n# Build dataset\ndf <- data.frame(\n col1 = c(\"Name: XXX_2\" ,\n \"Description: Object 1210 , 111\",\n \"Sampling_info: statexy=1346\",\n \"Num value: 15\",\n \"32 707; 33 71; 37 11; 38 3; 40 146; \" ,\n \"41 64; 42 36; 43 24; 44 69; 45 324; \" ,\n \"46 49; 47 52; 50 11; 51 90; 52 22; \" ,\n \"Name: XXX_3\" ,\n \"Shouldn't get this number: 8675309\")\n)\n\ndf %>%\n # Combine row into single string\n map_chr(paste, collapse = \" \") %>%\n # Remove everything before \"Num value:\"\n str_extract(\" Num value:.*\") %>%\n # Remove numbers after \"Num value:\n str_remove(\"Num value: \\\\d+\") %>%\n # Remove everything after \"Name:\"\n str_extract(\" .*Name:\") %>%\n # Extract digits\n str_extract_all(\"\\\\d+\") %>%\n unlist() %>%\n as.numeric()\n\n#[1] 32 707 33 71 37 11 38 3 40 146 41 64 42 36 43 24 44 69 45\n#[20] 324 46 49 47 52 50 11 51 90 52 22\n\n", "One approach without loops:\nlibrary(dplyr)\nlibrary(tidyr)\n\ndf <- read.delim('path_to_input_file/your_file.txt',\n sep = ':', header = FALSE)\n\ndf %>%\n separate(V1, into = c('param', 'value'), sep = ' *: *') %>%\n filter(param == 'Name' | grepl(';', param)) %>%\n fill(value, .direction = 'down') %>%\n filter(param != 'Name') %>%\n separate_rows(param, sep = ' *; *')\n\n## follow up with blank removal, conversion to numeric as needed\n\nOutput (column value contains the name from the initial name: xxx lines)\n# A tibble: 18 x 2\n param value \n <chr> <chr> \n 1 \"32 707\" \"XXX_2 \"\n 2 \"33 71\" \"XXX_2 \"\n 3 \"37 11\" \"XXX_2 \"\n 4 \"38 3\" \"XXX_2 \"\n 5 \"40 146\" \"XXX_2 \"\n 6 \"\" \"XXX_2 \"\n\nYou might want to partition the above pipeline and inspect the intermediate dataframes to see what's going on at which step.\n", "with base and for, and various notes.\nlibrary(stringr)\n# msp_list <- scan(file='', what = character()) #paste in 1:24 above <return>\n# dput(msp_list)\nmsp_list <- c(\"Name: XXX_2\", \"Description: Object 1210 , 111\", \"Sampling_info: statexy=1346\", \n\"Num value: 15\", \"32 707; 33 71; 37 11; 38 3; 40 146; \", \"41 64; 42 36; 43 24; 44 69; 45 324; \", \n\"46 49; 47 52; 50 11; 51 90; 52 22; \", \"Name: XXX_3\", \"Description: Object 1341 , 111\", \n\"Sampling_info: statexy=1346\", \"Num value: 18\", \"32 999; 33 4; 34 17; 39 84; 41 84; \", \n\"42 4; 44 137; 45 102; 50 13; 52 22; \", \"53 4; 54 4; 55 84; 58 40; 59 13; \", \n\"65 57; 66 13; 67 173; \", \"Name: XXX_4\", \"Description: Object 1561 , 111\", \n\"Sampling_info: statexy=1346\", \"Num value: 21\", \"32 925; 34 5; 40 409; 41 55; 44 43; \", \n\"45 154; 46 5; 47 5; 50 38; 52 16; \", \"56 99; 58 5; 59 110; 61 5; 62 55; \", \n\"63 11; 68 5; 69 38; 70 22; 73 999; \", \"74 49; \")\n# get rid of trailing whitespace that will be annoying later\nmsp_lst <- trimws(msp_list, 'r')\n\nindex msp_list, for start and end of future sub dfs. I am assuming you .mps is properly formed, which is to say all are complete (I've wished away your line 25 above).\nmsp_name_rle <- rle(str_starts(msp_list, 'Name'))$lengths\nmsp_rle_mtx<- matrix(msp_name_rle, nrow = length(msp_name_rle)/2, ncol = 2, byrow = TRUE)\nmsp_rowsums <-matrix(rowSums(msp_rle_mtx), ncol = 1)\nstarts <- which(str_starts(msp_list, 'Name') == TRUE)\nstarts\n[1] 1 8 16\nends <- as.vector(starts + msp_rowsums -1)\nends\n[1] 7 15 24\n\n# and then get names as they will be useful later\n> msp_names <- trimws(str_extract(msp_list[which(str_starts(msp_list, 'Name') == TRUE)], '\\\\s\\\\w+'))\n# a similar extract could be done on ? whatever is informative and applied to attributes later (not done here)\n# initialize an object to receive output from the `for` loop\nmany_msp <- list()\n\nAt this point we have what we need in the global environment to inform the operations in the for loop so it won't complain that some value isn't found. And things are sufficiently detailed to operate on one index (i.e. not nested i,j), well, at least I hope, and we'll do a bunch of data cleaning here, but hopefully return an extracted list of .msp values in a two column df each (that basically relies on the regularity of the .msp file format\n# first checking that the indexing is working\nfor(i in 1:length(starts)) {\n many_msp[[i]] <- df3[starts[i]:ends[i], ]\n}\nmany_msp[[3]]\n[[3]]\n[1] \"Name: XXX_4\" \n[2] \"Description: Object 1561 , 111\" \n[3] \"Sampling_info: statexy=1346\" \n[4] \"Num value: 21\" \n[5] \"32 925; 34 5; 40 409; 41 55; 44 43; \"\n[6] \"45 154; 46 5; 47 5; 50 38; 52 16; \" \n[7] \"56 99; 58 5; 59 110; 61 5; 62 55; \" \n[8] \"63 11; 68 5; 69 38; 70 22; 73 999; \" \n[9] \"74 49; \" \n# OK. Now, we can either make another `for`, or extend what happens within this one.\n\nExtending:\nfor(i in 1:length(starts)) {\nmany_msp[[i]] <- msp_list[starts[i]:ends[i]]\n#return only values\nmany_msp[[i]] <- many_msp[[i]][5:lengths(many_msp)[i]]\n#take to vector, after a bunch of tidying up\nmany_msp[[i]] <- as.numeric(strsplit(trimws(paste(gsub(';', '', many_msp[[i]]), collapse = ''), 'r'), ' ')[[1]])\n#take to data.frame\nmany_msp[[i]] <- data.frame(col1 = many_msp[[i]][seq(1, length(many_msp[[i]]), 2)], col2 = many_msp[[i]][seq(2, length(many_msp[[i]]), 2)])\n# name the data.frames\nnames(many_msp)[i] <- msp_names[[i]]\n}\n\nnames(many_msp)\n[1] \"XXX_2\" \"XXX_3\" \"XXX_4\"\n\n\nmany_msp$XXX_4\n col1 col2\n1 32 925\n2 34 5\n3 40 409\n4 41 55\n5 44 43\n6 45 154\n7 46 5\n8 47 5\n9 50 38\n10 52 16\n11 56 99\n12 58 5\n13 59 110\n14 61 5\n15 62 55\n16 63 11\n17 68 5\n18 69 38\n19 70 22\n20 73 999\n21 74 49\n\nso can be done with a for loop. The accessing/addressing in this list stuff may be a little less apparent when reaching into col1, col2 values as you have\nmany_msp$XXX_4$col1\n [1] 32 34 40 41 44 45 46 47 50 52 56 58 59 61 62 63 68 69 70 73 74\n\nwhich is unexpected, at first.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "r", "string", "string_matching" ]
stackoverflow_0074648363_r_string_string_matching.txt
Q: Python : How to contrast contrast data I don't know what is the term for this, but what get the closest to it is the process of contrasting an image. Basically i have a list of values going from 0 to 100. I would like that values over 50 come closer to 100 and values under 50 come closer to 0. for example : [0, 23, 50,58,100] would become something like this (roughly) : [0, 10, 50, 69, 100] is their a mathematic formula for this ? A: The following code might give you some ideas. If it doesn't meet your needs then you need to clearly explain just what those needs are. def contrast(nums): contrasted = [] for num in nums: if num < 50: contrasted.append(num//2) elif num > 50: contrasted.append((num + 100)//2) else: contrasted.append(num) return contrasted data = [0, 23, 50,58,100] print(contrast(data)) Output: [0, 11, 50, 79, 100]
Python : How to contrast contrast data
I don't know what is the term for this, but what get the closest to it is the process of contrasting an image. Basically i have a list of values going from 0 to 100. I would like that values over 50 come closer to 100 and values under 50 come closer to 0. for example : [0, 23, 50,58,100] would become something like this (roughly) : [0, 10, 50, 69, 100] is their a mathematic formula for this ?
[ "The following code might give you some ideas. If it doesn't meet your needs then you need to clearly explain just what those needs are.\ndef contrast(nums):\n contrasted = []\n for num in nums:\n if num < 50:\n contrasted.append(num//2)\n elif num > 50:\n contrasted.append((num + 100)//2)\n else:\n contrasted.append(num)\n return contrasted\n\ndata = [0, 23, 50,58,100]\nprint(contrast(data))\n\nOutput: [0, 11, 50, 79, 100]\n" ]
[ 1 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074666019_math_python.txt
Q: Making snake in c but my snake is only moving every time a key is pressed (I want continuous movement) I'm working on making the classic snake game in c. My program is working fine, other than the fact that when controlling the snake, it only moves when w/a/s/d are being pressed or held. For those who haven't played snake, the snake is supposed to move forward the whole time, and w/a/s/d simply change which direction the snake is facing. Here is my code for the method responsible for moving the snake: let me know if you have any questions or if you need to see any of my either code to help, thank you! PS. using WSL, and using gcc as compiler void snake() { makeFood(); pos head = { 10, 10 }; queue(head); while( 1 ) { int in = getch( ); if( in != ERR ) key = in; switch( key ) { case 'W': case 'w': head.y--; break; case 'A': case 'a': head.x--; break; case 'S': case 's': head.y++; break; case 'D': case 'd': head.x++; break; case 'Q': case 'q': showMenu(); break; } if( !inPlay( head ) ) gameOver( ); else moveSnake( head ); } gameOver( ); } A: Emphasize: Assuming OP looking for Unix/Posix solution - Linux, WSL, ... Answer not relevant if looking for Window only solution. Same for curses. You have two items to deal with, all related to getch running against terminal input. By default, tty input is line oriented. It means that data will not be available to your program until the user clicks "enter". stty -icanon will address this. The 'getch' will use "blocking read", which means that if there is no input, the program will block for the next character. stty -time 1 can cap the time (with 1/10 seconds precision). The standard terminal driver will echo input characters. Assuming program generating some graphic output, better to disable echo. stty -echo If you input is coming from directly from a terminal, you can use the stty to change the behavior of the terminal. Remember to reset the setting, when your program exit, otherwise, they will carry forward for other commands that will interact with the terminal ( stty -icanon -echo min 0 time 1 ; myprog ) You can achieve the effect of 'stty' progmatically, if you use ioctl with the TCGETS and TCSETS - man tty_ioctl provide with details.
Making snake in c but my snake is only moving every time a key is pressed (I want continuous movement)
I'm working on making the classic snake game in c. My program is working fine, other than the fact that when controlling the snake, it only moves when w/a/s/d are being pressed or held. For those who haven't played snake, the snake is supposed to move forward the whole time, and w/a/s/d simply change which direction the snake is facing. Here is my code for the method responsible for moving the snake: let me know if you have any questions or if you need to see any of my either code to help, thank you! PS. using WSL, and using gcc as compiler void snake() { makeFood(); pos head = { 10, 10 }; queue(head); while( 1 ) { int in = getch( ); if( in != ERR ) key = in; switch( key ) { case 'W': case 'w': head.y--; break; case 'A': case 'a': head.x--; break; case 'S': case 's': head.y++; break; case 'D': case 'd': head.x++; break; case 'Q': case 'q': showMenu(); break; } if( !inPlay( head ) ) gameOver( ); else moveSnake( head ); } gameOver( ); }
[ "Emphasize: Assuming OP looking for Unix/Posix solution - Linux, WSL, ... Answer not relevant if looking for Window only solution. Same for curses.\nYou have two items to deal with, all related to getch running against terminal input.\n\nBy default, tty input is line oriented. It means that data will not be available to your program until the user clicks \"enter\". stty -icanon will address this.\nThe 'getch' will use \"blocking read\", which means that if there is no input, the program will block for the next character. stty -time 1 can cap the time (with 1/10 seconds precision).\nThe standard terminal driver will echo input characters. Assuming program generating some graphic output, better to disable echo. stty -echo\n\nIf you input is coming from directly from a terminal, you can use the stty to change the behavior of the terminal. Remember to reset the setting, when your program exit, otherwise, they will carry forward for other commands that will interact with the terminal\n( stty -icanon -echo min 0 time 1 ; myprog )\n\nYou can achieve the effect of 'stty' progmatically, if you use ioctl with the TCGETS and TCSETS - man tty_ioctl provide with details.\n" ]
[ 0 ]
[]
[]
[ "c", "game_development" ]
stackoverflow_0074670397_c_game_development.txt
Q: How to compare two columns in DataFrame and change value of third column based on that comparison? I have following table in Pandas: index | project | category | period | update | amount 0 | 100130 | labour | 202201 | 202203 | 1000 1 | 100130 | labour | 202202 | 202203 | 1000 2 | 100130 | labour | 202203 | 202203 | 1000 3 | 100130 | labour | 202204 | 202203 | 1000 4 | 100130 | labour | 202205 | 202203 | 1000 And my final goal is to get table grouped by project and category with summary of amount column but only from month of update until now. So for example above I will get summary from 202203 until 202205 which is 3000 for project 100130 and category labour. As a first step I tried following condition: for index, row in table.iterrows(): if row["period"] < row["update"] row["amount"] = 0 But: this iteration is not working is there some simple and not so time consuming way how to do it? As my table has over 60.000 rows, so iteration not so good idea probably. A: table["amount"] = 0 if table["period"] < table["update"] else None A: I did some more research and this code seems to solve my problem: def check_update(row): if row["period"] < row["update"]: return 0 else: return row["amount"] table["amount2"] = table.apply(check_update, axis=1)
How to compare two columns in DataFrame and change value of third column based on that comparison?
I have following table in Pandas: index | project | category | period | update | amount 0 | 100130 | labour | 202201 | 202203 | 1000 1 | 100130 | labour | 202202 | 202203 | 1000 2 | 100130 | labour | 202203 | 202203 | 1000 3 | 100130 | labour | 202204 | 202203 | 1000 4 | 100130 | labour | 202205 | 202203 | 1000 And my final goal is to get table grouped by project and category with summary of amount column but only from month of update until now. So for example above I will get summary from 202203 until 202205 which is 3000 for project 100130 and category labour. As a first step I tried following condition: for index, row in table.iterrows(): if row["period"] < row["update"] row["amount"] = 0 But: this iteration is not working is there some simple and not so time consuming way how to do it? As my table has over 60.000 rows, so iteration not so good idea probably.
[ "table[\"amount\"] = 0 if table[\"period\"] < table[\"update\"] else None\n\n", "I did some more research and this code seems to solve my problem:\ndef check_update(row):\n if row[\"period\"] < row[\"update\"]:\n return 0\n else:\n return row[\"amount\"]\n\ntable[\"amount2\"] = table.apply(check_update, axis=1)\n\n" ]
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074670499_pandas_python.txt
Q: How would I go about making elements underneath a div visible? I have been trying to make a "hidden text" website of sorts. I have managed to code a circular div that follows my mouse cursor and inverts every text underneath it using background-filter in CSS and Javascript: let circle = document.getElementById('circle'); const onMouseMove = (e) => { circle.style.left = e.pageX + 'px'; circle.style.top = e.pageY + 'px'; } document.addEventListener('mousemove', onMouseMove); The CSS for the #circle element is: #circle { position: absolute; transform: translate(-50%,-50%); height: 80px; width: 80px; border-radius: 50%; box-shadow: 0px 0px 40px 10px white; pointer-events: none; backdrop-filter: invert(100%); z-index: 100; } I have tried setting the text opacity to 5% and then setting backdrop-filter: opacity(100%) but that didn't work, unfortunately. How should I go about achieving this? I am open to any and all libraries and willing to follow any tutorial. Accessibility is not an issue at the moment as this is just an experiment for myself. A: One way to achieve the effect you want is to use the mix-blend-mode property in CSS. This property allows you to blend an element's content with the content of the element behind it. To invert the text underneath the circle, you can set the mix-blend-mode of the circle to difference, which inverts the colors of the elements underneath it. Here's an example of how you might use the mix-blend-mode property: #circle { position:absolute; transform:translate(-50%,-50%); height:80px; width:80px; border-radius:50%; box-shadow: 0px 0px 40px 10px white; pointer-events: none; mix-blend-mode: difference; z-index: 100; } Note that the mix-blend-mode property is not supported by all browsers, so you may want to include a fallback for browsers that do not support it. For more information on the mix-blend-mode property and how to use it, you can check out the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode Hope this helps! A: I managed to make the effect you want using the CSS clip-path property: const content = document.getElementById("content"); const onMouseMove = (e) => { content.style.clipPath = `circle(40px at ${e.pageX}px ${e.pageY}px)`; } document.addEventListener('mousemove', onMouseMove); <div id="content"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis arcu diam, mattis vel mi sit amet, consequat dapibus sapien. Integer blandit et justo sit amet pharetra. Quisque facilisis placerat aliquet. Proin at dictum sapien. Proin ac urna quis leo vehicula semper. Pellentesque condimentum scelerisque aliquam. Nunc vitae pellentesque tortor.</p> </div> <div id="circle"></div>
How would I go about making elements underneath a div visible?
I have been trying to make a "hidden text" website of sorts. I have managed to code a circular div that follows my mouse cursor and inverts every text underneath it using background-filter in CSS and Javascript: let circle = document.getElementById('circle'); const onMouseMove = (e) => { circle.style.left = e.pageX + 'px'; circle.style.top = e.pageY + 'px'; } document.addEventListener('mousemove', onMouseMove); The CSS for the #circle element is: #circle { position: absolute; transform: translate(-50%,-50%); height: 80px; width: 80px; border-radius: 50%; box-shadow: 0px 0px 40px 10px white; pointer-events: none; backdrop-filter: invert(100%); z-index: 100; } I have tried setting the text opacity to 5% and then setting backdrop-filter: opacity(100%) but that didn't work, unfortunately. How should I go about achieving this? I am open to any and all libraries and willing to follow any tutorial. Accessibility is not an issue at the moment as this is just an experiment for myself.
[ "One way to achieve the effect you want is to use the mix-blend-mode property in CSS. This property allows you to blend an element's content with the content of the element behind it. To invert the text underneath the circle, you can set the mix-blend-mode of the circle to difference, which inverts the colors of the elements underneath it.\nHere's an example of how you might use the mix-blend-mode property:\n#circle {\n position:absolute;\n transform:translate(-50%,-50%);\n height:80px;\n width:80px;\n border-radius:50%;\n box-shadow: 0px 0px 40px 10px white;\n pointer-events: none;\n mix-blend-mode: difference;\n z-index: 100;\n}\n\n\nNote that the mix-blend-mode property is not supported by all browsers, so you may want to include a fallback for browsers that do not support it. For more information on the mix-blend-mode property and how to use it, you can check out the MDN documentation:\nhttps://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode\nHope this helps!\n", "I managed to make the effect you want using the CSS clip-path property:\n\n\nconst content = document.getElementById(\"content\");\n\nconst onMouseMove = (e) => {\n content.style.clipPath =\n `circle(40px at ${e.pageX}px ${e.pageY}px)`;\n}\n\ndocument.addEventListener('mousemove', onMouseMove);\n<div id=\"content\">\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis arcu diam, mattis vel mi sit amet, consequat dapibus sapien. Integer blandit et justo sit amet pharetra. Quisque facilisis placerat aliquet. Proin at dictum sapien. Proin ac urna quis leo\n vehicula semper. Pellentesque condimentum scelerisque aliquam. Nunc vitae pellentesque tortor.</p>\n</div>\n\n\n<div id=\"circle\"></div>\n\n\n\n" ]
[ 0, 0 ]
[]
[]
[ "css", "html", "javascript", "jquery" ]
stackoverflow_0074671069_css_html_javascript_jquery.txt
Q: How can I write a function of web scraping on R? I'm trying scrape a site with ten pages. I don't know how to do a loop to scrape all the pages, so I tried to create a function to be easier for me to just change the link. See the function: link = "https://santabarbara.siscam.com.br/Documentos/Pesquisa/74?Pesquisa=Simples&Pagina=1&Documento=117&Modulo=8&AnoInicial=2022" scraper <- function(link){ page = read_html(link) titulo = page %>% html_nodes("h4 a") %>% html_text() tipo = page %>% html_nodes("h4+ .row .col-md-4") %>% html_text() data = page %>% html_nodes("p.col-md-6") %>% html_text() protocolo = page %>% html_nodes(".row:nth-child(3) .col-md-4") %>% html_text() situacao = page %>% html_nodes(".row~ .row+ .row p.col-md-4:nth-child(1)") %>% html_text() regime = page %>% html_nodes("p.col-md-4:nth-child(2)") %>% html_text() quorum = page %>% html_nodes(".col-md-4~ .col-md-4+ .col-md-4") %>% html_text() autoria = page %>% html_nodes(".row:nth-child(5) .col-md-12") %>% html_text() assunto = page %>% html_nodes(".row:nth-child(6) .col-md-12") %>% html_text() result <- data.frame(titulo, tipo, data, protocolo, situacao, regime, quorum, autoria, assunto) } But when I run the function nothing happens. I'm trying scrape a site with ten pages. I don't know how to do a loop to scrape all the pages, so I tried to create a function to be easier for me to just change the link. A: Scraping the first 5 pages into a tibble rm(list = ls()) library(tidyverse) library(rvest) get_content <- function(page) { content <- str_c( "https://santabarbara.siscam.com.br/Documentos/Pesquisa/74?Pesquisa=Simples&Pagina=", page, "&Documento=117&Modulo=8&AnoInicial=2022" ) %>% read_html() %>% html_elements(".data-list-hover") tibble( titulo = content %>% html_nodes("h4 a") %>% html_text2(), tipo = content %>% html_nodes("h4+ .row .col-md-4") %>% html_text2(), data = content %>% html_nodes("p.col-md-6") %>% html_text2(), protocolo = content %>% html_nodes(".row:nth-child(3) .col-md-4") %>% html_text2(), situacao = content %>% html_nodes(".row~ .row+ .row p.col-md-4:nth-child(1)") %>% html_text2(), regime = content %>% html_nodes("p.col-md-4:nth-child(2)") %>% html_text2(), quorum = content %>% html_nodes(".col-md-4~ .col-md-4+ .col-md-4") %>% html_text2(), autoria = content %>% html_nodes(".row:nth-child(5) .col-md-12") %>% html_text2(), assunto = content %>% html_nodes(".row:nth-child(6) .col-md-12") %>% html_text2() ) %>% mutate(across(everything(), ~ str_remove_all(.x, "\r") %>% str_squish())) } map_dfr(1:5, get_content)
How can I write a function of web scraping on R?
I'm trying scrape a site with ten pages. I don't know how to do a loop to scrape all the pages, so I tried to create a function to be easier for me to just change the link. See the function: link = "https://santabarbara.siscam.com.br/Documentos/Pesquisa/74?Pesquisa=Simples&Pagina=1&Documento=117&Modulo=8&AnoInicial=2022" scraper <- function(link){ page = read_html(link) titulo = page %>% html_nodes("h4 a") %>% html_text() tipo = page %>% html_nodes("h4+ .row .col-md-4") %>% html_text() data = page %>% html_nodes("p.col-md-6") %>% html_text() protocolo = page %>% html_nodes(".row:nth-child(3) .col-md-4") %>% html_text() situacao = page %>% html_nodes(".row~ .row+ .row p.col-md-4:nth-child(1)") %>% html_text() regime = page %>% html_nodes("p.col-md-4:nth-child(2)") %>% html_text() quorum = page %>% html_nodes(".col-md-4~ .col-md-4+ .col-md-4") %>% html_text() autoria = page %>% html_nodes(".row:nth-child(5) .col-md-12") %>% html_text() assunto = page %>% html_nodes(".row:nth-child(6) .col-md-12") %>% html_text() result <- data.frame(titulo, tipo, data, protocolo, situacao, regime, quorum, autoria, assunto) } But when I run the function nothing happens. I'm trying scrape a site with ten pages. I don't know how to do a loop to scrape all the pages, so I tried to create a function to be easier for me to just change the link.
[ "Scraping the first 5 pages into a tibble\nrm(list = ls())\nlibrary(tidyverse)\nlibrary(rvest)\n\nget_content <- function(page) {\n content <-\n str_c(\n \"https://santabarbara.siscam.com.br/Documentos/Pesquisa/74?Pesquisa=Simples&Pagina=\",\n page,\n \"&Documento=117&Modulo=8&AnoInicial=2022\"\n ) %>%\n read_html() %>%\n html_elements(\".data-list-hover\")\n \n tibble(\n titulo = content %>% html_nodes(\"h4 a\") %>% html_text2(),\n tipo = content %>% html_nodes(\"h4+ .row .col-md-4\") %>% html_text2(),\n data = content %>% html_nodes(\"p.col-md-6\") %>% html_text2(),\n protocolo = content %>% html_nodes(\".row:nth-child(3) .col-md-4\") %>% html_text2(),\n situacao = content %>% html_nodes(\".row~ .row+ .row p.col-md-4:nth-child(1)\") %>% html_text2(),\n regime = content %>% html_nodes(\"p.col-md-4:nth-child(2)\") %>% html_text2(),\n quorum = content %>% html_nodes(\".col-md-4~ .col-md-4+ .col-md-4\") %>% html_text2(),\n autoria = content %>% html_nodes(\".row:nth-child(5) .col-md-12\") %>% html_text2(),\n assunto = content %>% html_nodes(\".row:nth-child(6) .col-md-12\") %>% html_text2()\n \n ) %>%\n mutate(across(everything(), ~ str_remove_all(.x, \"\\r\") %>%\n str_squish()))\n}\n\nmap_dfr(1:5, get_content)\n\n" ]
[ 0 ]
[]
[]
[ "function", "r", "web_scraping" ]
stackoverflow_0074645585_function_r_web_scraping.txt
Q: How to make a Java tray menu sub-menu accessible via the keyboard on a Mac? I'm creating a cross-platform Java app with options available through a system tray menu. Unfortunately, any sub-menus I put in this menu cannot be opened when navigating via keyboard on Mac. Once I get to the sub-menu and I hit the return key or space bar, the whole menu closes instead of opening the sub-menu. Via keyboard (before hitting the space bar or return key): Via mouse (after hovering over the menu): Interestingly, clicking on the sub-menu also closes the whole menu. Here's my Main.java code: import java.awt.AWTException; import java.awt.Menu; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.Toolkit; import java.awt.Image; import java.io.IOException; import java.io.UncheckedIOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.util.*; public class Main { public static void main(String[] args) { if(!SystemTray.isSupported()) { System.err.println("System tray feature is not supported"); return; } try { BufferedImage img = ImageIO.read(Main.class.getResource("tray_icon_mac.png")); TrayIcon trayIcon = new TrayIcon(img, "Test Icon", null); trayIcon.setImageAutoSize(true); final SystemTray tray = SystemTray.getSystemTray(); try { tray.add(trayIcon); PopupMenu rootMenu = new PopupMenu(); MenuItem about = new MenuItem("About"); rootMenu.add(about); Menu options = new Menu("Options"); MenuItem option1 = new MenuItem("Option 1"); options.add(option1); rootMenu.add(options); trayIcon.setPopupMenu(rootMenu); } catch (AWTException e) { System.out.println("TrayIcon could not be added."); return; } } catch(IOException e) { System.out.println(e); return; } } } Any insight on this would be greatly appreciated! Edit: I found out that you can navigate to the sub-menu using the right arrow key. However, regular sub-menus allow opening sub-menus using either the right arrow key, space bar, or return key. So while it is possible to open, there are fewer options for opening it. A: To make a Java tray menu sub-menu accessible via keyboard on Mac, try the following steps: When creating the tray menu, use JPopupMenu class to create the sub-menu. To make the sub-menu accessible via keyboard call the setFocusable method on the JPopupMenu instance and pass true as the argument. This will allow the sub-menu to receive focus when navigating via keyboard. To make the sub-menu open when the return key or space bar is pressed add a KeyListener to the JPopupMenu instance and implement the keyPressed method. In this method, you can check if the key pressed was the return key or space bar, and if it was call the setVisible method on the JPopupMenu instance and pass true as the argument to show the sub-menu. JPopupMenu subMenu = new JPopupMenu(); subMenu.setFocusable(true); subMenu.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER) { subMenu.setVisible(true); } } });
How to make a Java tray menu sub-menu accessible via the keyboard on a Mac?
I'm creating a cross-platform Java app with options available through a system tray menu. Unfortunately, any sub-menus I put in this menu cannot be opened when navigating via keyboard on Mac. Once I get to the sub-menu and I hit the return key or space bar, the whole menu closes instead of opening the sub-menu. Via keyboard (before hitting the space bar or return key): Via mouse (after hovering over the menu): Interestingly, clicking on the sub-menu also closes the whole menu. Here's my Main.java code: import java.awt.AWTException; import java.awt.Menu; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TrayIcon; import java.awt.Toolkit; import java.awt.Image; import java.io.IOException; import java.io.UncheckedIOException; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.util.*; public class Main { public static void main(String[] args) { if(!SystemTray.isSupported()) { System.err.println("System tray feature is not supported"); return; } try { BufferedImage img = ImageIO.read(Main.class.getResource("tray_icon_mac.png")); TrayIcon trayIcon = new TrayIcon(img, "Test Icon", null); trayIcon.setImageAutoSize(true); final SystemTray tray = SystemTray.getSystemTray(); try { tray.add(trayIcon); PopupMenu rootMenu = new PopupMenu(); MenuItem about = new MenuItem("About"); rootMenu.add(about); Menu options = new Menu("Options"); MenuItem option1 = new MenuItem("Option 1"); options.add(option1); rootMenu.add(options); trayIcon.setPopupMenu(rootMenu); } catch (AWTException e) { System.out.println("TrayIcon could not be added."); return; } } catch(IOException e) { System.out.println(e); return; } } } Any insight on this would be greatly appreciated! Edit: I found out that you can navigate to the sub-menu using the right arrow key. However, regular sub-menus allow opening sub-menus using either the right arrow key, space bar, or return key. So while it is possible to open, there are fewer options for opening it.
[ "To make a Java tray menu sub-menu accessible via keyboard on Mac, try the following steps:\n\nWhen creating the tray menu, use JPopupMenu class to create the sub-menu.\nTo make the sub-menu accessible via keyboard call the setFocusable method on the JPopupMenu instance and pass true as the argument. This will allow the sub-menu to receive focus when navigating via keyboard.\nTo make the sub-menu open when the return key or space bar is pressed add a KeyListener to the JPopupMenu instance and implement the keyPressed method. In this method, you can check if the key pressed was the return key or space bar, and if it was call the setVisible method on the JPopupMenu instance and pass true as the argument to show the sub-menu.\n\n\nJPopupMenu subMenu = new JPopupMenu();\nsubMenu.setFocusable(true);\nsubMenu.addKeyListener(new KeyListener() {\n @Override\n public void keyPressed(KeyEvent e) {\n if (e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER) {\n subMenu.setVisible(true);\n }\n }\n});\n\n" ]
[ 0 ]
[]
[]
[ "accessibility", "java", "macos", "trayicon" ]
stackoverflow_0074578491_accessibility_java_macos_trayicon.txt
Q: deducing operator() with std::invoke I'm wondering why std::invoke cannot infer that X below has an operator with signature below vs. having the requirement to specify the pointer to member function explicitly. The latter makes std::invoke more generally applicable but are there rules that would prevent the special case from being deduced. #include <functional> struct X { void operator()() { } }; void call(X *ptr) { // std::invoke(ptr); // Does not compile std::invoke(&X::operator(), ptr); // Works } A: In the code, you posted, std::invoke cannot infer the correct pointer to the member function because you are passing a pointer to an object of type X rather than an object of type X itself. std::invoke expects its first argument to be a callable object or a pointer to a member function, but a pointer to an object is not the same as a callable object or a pointer to a member function. In order to use std::invoke with a pointer to an object, you can first dereference the pointer to obtain a reference to the object, and then pass that reference as the first argument to std::invoke. For example: #include <functional> struct X { void operator()() { } }; void call(X *ptr) { std::invoke(*ptr); // Works } This code will compile and work as expected because std::invoke is now able to infer that a first argument is a callable object of type X, and it can therefore use the operator() of that object to call the function.
deducing operator() with std::invoke
I'm wondering why std::invoke cannot infer that X below has an operator with signature below vs. having the requirement to specify the pointer to member function explicitly. The latter makes std::invoke more generally applicable but are there rules that would prevent the special case from being deduced. #include <functional> struct X { void operator()() { } }; void call(X *ptr) { // std::invoke(ptr); // Does not compile std::invoke(&X::operator(), ptr); // Works }
[ "In the code, you posted, std::invoke cannot infer the correct pointer to the member function because you are passing a pointer to an object of type X rather than an object of type X itself. std::invoke expects its first argument to be a callable object or a pointer to a member function, but a pointer to an object is not the same as a callable object or a pointer to a member function.\nIn order to use std::invoke with a pointer to an object, you can first dereference the pointer to obtain a reference to the object, and then pass that reference as the first argument to std::invoke. For example:\n#include <functional>\nstruct X {\n void operator()() {\n }\n};\n\nvoid call(X *ptr) {\n std::invoke(*ptr); // Works\n}\n\nThis code will compile and work as expected because std::invoke is now able to infer that a first argument is a callable object of type X, and it can therefore use the operator() of that object to call the function.\n" ]
[ 2 ]
[]
[]
[ "c++17" ]
stackoverflow_0074671240_c++17.txt
Q: Dart: Retrive multiple album covers from MP3 file's ID3 tags iTunes/Apple Music allows for adding multiple cover artworks to a mp3 file. The first images is in a column named "Album Artwork" and remaining are in column "Other Artwork" as shown on the image below: I'm trying to retrieve all of these artworks in Dart but when reading the ID3 tags I can only see the first artwork. I'm certain that the other artworks are stored in the MP3 file as its file size is increasing when I add additional artworks. How can I retrieve the other artworks from a MP3 file? Below is my code and JSON showing all available ID3 tags data. import 'dart:convert'; import 'dart:io' as io; import 'package:id3/id3.dart'; void main(List<String> args) { var mp3 = io.File("./lib/song2.mp3"); MP3Instance mp3instance = MP3Instance(mp3.readAsBytesSync()); mp3instance.parseTagsSync(); Map<String, dynamic>? id3Tags = mp3instance.getMetaTags(); print(id3Tags!['APIC'].keys); print(id3Tags!['APIC']['mime']); io.File outputFile = io.File("lib/id3TagsOutput.txt"); outputFile.writeAsString(jsonEncode(id3Tags)); } Output: { "Version": "v2.3.0", "Album": "God of War (PlayStation Soundtrack)", "Accompaniment": "Bear McCreary", "Artist": "Bear McCreary", "AdditionalInfo": "WWW", "Composer": "Bear McCreary", "Year": "2018", "TPOS": "1", "Genre": "Game Soundtrack", "Conductor": "London Session Orchestra, Schola Cantorum Choir, London Voices", "Title": "God of War", "Track": "1", "Settings": "Lavf57.56.100", "APIC": { "mime": "image/png", "textEncoding": "0", "picType": "FrontCover", "description": "", "base64": "//VERY LONG BASE 64 DATA" } } A: I've found a solution to this issue. ID3 tags are stored in different frames (information blocks). Frames images are named "APIC". When a mp3 file has multiple images, APIC frame is added for each image. The package I'm using, package:id3/id3.dart, stores decoded tags information in a map. This map has a key "APIC" for storing image data. Every time it comes across "APIC" frame it overrides data from previously found image. I've amended the source code of this library to store an array in "APIC" key: MP3Instance(List<int> mp3Bytes) { this.mp3Bytes = mp3Bytes; metaTags['APIC'] = []; } and in function parseTagsSync I've changed this line: metaTags['APIC'] = apic; to metaTags['APIC'].add(apic);. This change allows the library to store all APIC data.
Dart: Retrive multiple album covers from MP3 file's ID3 tags
iTunes/Apple Music allows for adding multiple cover artworks to a mp3 file. The first images is in a column named "Album Artwork" and remaining are in column "Other Artwork" as shown on the image below: I'm trying to retrieve all of these artworks in Dart but when reading the ID3 tags I can only see the first artwork. I'm certain that the other artworks are stored in the MP3 file as its file size is increasing when I add additional artworks. How can I retrieve the other artworks from a MP3 file? Below is my code and JSON showing all available ID3 tags data. import 'dart:convert'; import 'dart:io' as io; import 'package:id3/id3.dart'; void main(List<String> args) { var mp3 = io.File("./lib/song2.mp3"); MP3Instance mp3instance = MP3Instance(mp3.readAsBytesSync()); mp3instance.parseTagsSync(); Map<String, dynamic>? id3Tags = mp3instance.getMetaTags(); print(id3Tags!['APIC'].keys); print(id3Tags!['APIC']['mime']); io.File outputFile = io.File("lib/id3TagsOutput.txt"); outputFile.writeAsString(jsonEncode(id3Tags)); } Output: { "Version": "v2.3.0", "Album": "God of War (PlayStation Soundtrack)", "Accompaniment": "Bear McCreary", "Artist": "Bear McCreary", "AdditionalInfo": "WWW", "Composer": "Bear McCreary", "Year": "2018", "TPOS": "1", "Genre": "Game Soundtrack", "Conductor": "London Session Orchestra, Schola Cantorum Choir, London Voices", "Title": "God of War", "Track": "1", "Settings": "Lavf57.56.100", "APIC": { "mime": "image/png", "textEncoding": "0", "picType": "FrontCover", "description": "", "base64": "//VERY LONG BASE 64 DATA" } }
[ "I've found a solution to this issue.\nID3 tags are stored in different frames (information blocks). Frames images are named \"APIC\". When a mp3 file has multiple images, APIC frame is added for each image.\nThe package I'm using, package:id3/id3.dart, stores decoded tags information in a map. This map has a key \"APIC\" for storing image data. Every time it comes across \"APIC\" frame it overrides data from previously found image.\nI've amended the source code of this library to store an array in \"APIC\" key:\nMP3Instance(List<int> mp3Bytes) {\n this.mp3Bytes = mp3Bytes;\n metaTags['APIC'] = [];\n }\n\nand in function parseTagsSync I've changed this line: metaTags['APIC'] = apic; to metaTags['APIC'].add(apic);. This change allows the library to store all APIC data.\n" ]
[ 0 ]
[]
[]
[ "audio_player", "dart", "id3", "mp3" ]
stackoverflow_0074666276_audio_player_dart_id3_mp3.txt
Q: How to quickly check if object attribute exists on conditional object type in Typescript? I have an example below that is an extremely simplified version of my actual code. I have a type that can either be an interface or another like so: interface ChatBase { roomId?: string type: "message" | "emoji" configs: unknown } interface ChatMessage extends ChatBase { type: "message", configs:{ text?: string } } interface ChatEmoji extends ChatBase { type: "emoji", configs: { emoji?: string } } type Chat = ChatMessage | ChatEmoji Here is a typescript playground Now in my code, when I try to simply check if "emoji" is defined in configs, it's making it super more complicated, surely there is a simpler way? const chats: Chat[] = [ { type: "message", configs: { text: "string" } }, { type: "emoji", configs: { emoji: "string" } } ] chats.map(chat=>{ if(chat.configs.emoji){ // <=== THROWS ERROR SHOWN BELOW console.log("Has an emoji") } if("emoji" in chat.configs && chat.configs.emoji){ // <= Works but ridiculously long console.log("Has an emoji") } if(chat.type === "emoji" && chat.configs.emoji){ // <= Works but sometimes I test for shared properties console.log("Has en emoji") } }) But typescript is throwing me an error Property 'emoji' does not exist on type '{ text?: string | undefined; }'. So my question is, how can I can I make if("emoji" in chat.configs && chat.configs.emoji) not ridiculously long? A: A type predicate might help to simplify things: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} { return chat.type === "emoji" && Boolean(chat.configs.emoji); } if(hasDefinedEmoji(chat)){ console.log("Has an emoji", chat.configs.emoji) // works } The drawback is you can make a mistake in the predicate function and shoot yourself in the foot. You could do this and typescript won't bat an eye: function hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} { return true; } A: Simply define a type predicate for each type (if needed) in a helper file: const isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === "emoji"; const isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === "message"; You can then do: chats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));
How to quickly check if object attribute exists on conditional object type in Typescript?
I have an example below that is an extremely simplified version of my actual code. I have a type that can either be an interface or another like so: interface ChatBase { roomId?: string type: "message" | "emoji" configs: unknown } interface ChatMessage extends ChatBase { type: "message", configs:{ text?: string } } interface ChatEmoji extends ChatBase { type: "emoji", configs: { emoji?: string } } type Chat = ChatMessage | ChatEmoji Here is a typescript playground Now in my code, when I try to simply check if "emoji" is defined in configs, it's making it super more complicated, surely there is a simpler way? const chats: Chat[] = [ { type: "message", configs: { text: "string" } }, { type: "emoji", configs: { emoji: "string" } } ] chats.map(chat=>{ if(chat.configs.emoji){ // <=== THROWS ERROR SHOWN BELOW console.log("Has an emoji") } if("emoji" in chat.configs && chat.configs.emoji){ // <= Works but ridiculously long console.log("Has an emoji") } if(chat.type === "emoji" && chat.configs.emoji){ // <= Works but sometimes I test for shared properties console.log("Has en emoji") } }) But typescript is throwing me an error Property 'emoji' does not exist on type '{ text?: string | undefined; }'. So my question is, how can I can I make if("emoji" in chat.configs && chat.configs.emoji) not ridiculously long?
[ "A type predicate might help to simplify things: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates\nfunction hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return chat.type === \"emoji\" && Boolean(chat.configs.emoji);\n}\n\nif(hasDefinedEmoji(chat)){\n console.log(\"Has an emoji\", chat.configs.emoji) // works\n}\n\nThe drawback is you can make a mistake in the predicate function and shoot yourself in the foot. You could do this and typescript won't bat an eye:\nfunction hasDefinedEmoji(chat: Chat): chat is ChatEmoji & {configs: {emoji: string}} {\n return true;\n}\n\n", "Simply define a type predicate for each type (if needed) in a helper file:\nconst isChatEmoji = (chat: ChatBase): chat is ChatEmoji => chat.type === \"emoji\";\nconst isChatMessage = (chat: ChatBase): chat is ChatMessage => chat.type === \"message\";\n\nYou can then do:\nchats.filter(isChatEmoji).forEach(chat => console.log(chat.configs.emoji));\n\n" ]
[ 1, 0 ]
[]
[]
[ "typescript" ]
stackoverflow_0074650451_typescript.txt
Q: I was configuring MSVC for Visual Studio Code and encountered an unexpected error I only changed the tasks.json to "label": "Build with MSVC", as well as the arguments to "args": [ "/Zi", "/std:c++latest", "/EHsc", "/Fe", "${fileDirname}\\main.exe", "${workspaceFolder}\\*.cpp" and did not change anything else, but when I try to run the task I get presented with cl : Command line warning D9024 : unrecognized source file type 'C:\2.4WindowsTemplateProject\.vscode\main.exe', object file assumed *.cpp c1xx: fatal error C1083: Cannot open source file: 'C:\2.4WindowsTemplateProject\*.cpp': No such file or directory My tasks.json also has GCC and Clang in it. I was unsure what to do as I have not encountered this error and am not very experienced. Is there some typo in my code or is there a larger underlying problem? A: It looks like you are trying to compile all .cpp files in the workspaceFolder directory using the *.cpp glob pattern in the args list. However, this glob pattern will not be expanded by the command line and will be passed as is to the compiler. The compiler is unable to find a file named *.cpp and reports an error. To fix this issue, you can use the find command to expand the glob pattern and pass the list of .cpp files to the compiler. The find command is available on Windows, macOS, and Linux. Here is an example of how to use the find command in the args list: "args": [ "/Zi", "/std:c++latest", "/EHsc", "/Fe", "${fileDirname}\\main.exe", "$(find ${workspaceFolder} -name '*.cpp')" ] Alternatively, you can also use the -- option to tell the compiler that the following arguments are source files and not options. This allows you to pass the glob pattern directly to the compiler without using the find command. Here is an example of how to use the -- option in the args list: "args": [ "/Zi", "/std:c++latest", "/EHsc", "/Fe", "${fileDirname}\\main.exe", "--", "${workspaceFolder}\\*.cpp" ] Both approaches should fix the error and allow you to compile all .cpp files in the workspaceFolder directory.
I was configuring MSVC for Visual Studio Code and encountered an unexpected error
I only changed the tasks.json to "label": "Build with MSVC", as well as the arguments to "args": [ "/Zi", "/std:c++latest", "/EHsc", "/Fe", "${fileDirname}\\main.exe", "${workspaceFolder}\\*.cpp" and did not change anything else, but when I try to run the task I get presented with cl : Command line warning D9024 : unrecognized source file type 'C:\2.4WindowsTemplateProject\.vscode\main.exe', object file assumed *.cpp c1xx: fatal error C1083: Cannot open source file: 'C:\2.4WindowsTemplateProject\*.cpp': No such file or directory My tasks.json also has GCC and Clang in it. I was unsure what to do as I have not encountered this error and am not very experienced. Is there some typo in my code or is there a larger underlying problem?
[ "It looks like you are trying to compile all .cpp files in the workspaceFolder directory using the *.cpp glob pattern in the args list. However, this glob pattern will not be expanded by the command line and will be passed as is to the compiler. The compiler is unable to find a file named *.cpp and reports an error.\nTo fix this issue, you can use the find command to expand the glob pattern and pass the list of .cpp files to the compiler. The find command is available on Windows, macOS, and Linux.\nHere is an example of how to use the find command in the args list:\n\"args\": [\n \"/Zi\",\n \"/std:c++latest\",\n \"/EHsc\",\n \"/Fe\",\n \"${fileDirname}\\\\main.exe\",\n \"$(find ${workspaceFolder} -name '*.cpp')\"\n]\n\nAlternatively, you can also use the -- option to tell the compiler that the following arguments are source files and not options. This allows you to pass the glob pattern directly to the compiler without using the find command.\nHere is an example of how to use the -- option in the args list:\n\"args\": [\n \"/Zi\",\n \"/std:c++latest\",\n \"/EHsc\",\n \"/Fe\",\n \"${fileDirname}\\\\main.exe\",\n \"--\",\n \"${workspaceFolder}\\\\*.cpp\"\n]\n\nBoth approaches should fix the error and allow you to compile all .cpp files in the workspaceFolder directory.\n" ]
[ 0 ]
[]
[]
[ "c++", "visual_c++", "vscode_tasks" ]
stackoverflow_0074671362_c++_visual_c++_vscode_tasks.txt
Q: How to perform calculations on a subset of a column in a pandas dataframe? With a dataset such as this: famid birth age ht 0 1 1 one 2.8 1 1 1 two 3.4 2 1 2 one 2.9 3 1 2 two 3.8 4 1 3 one 2.2 5 1 3 two 2.9 ...where we've got values for a variable ht for different categories of, for example, age , I would like to adjust a subset of the data in df['ht'] where df['age'] == 'one' only. And I would like to do it without creating a new column. I've tried: df[df['age']=='one']['ht'] = df[df['age']=='one']['ht']*10**6 But to my mild surprise the numbers don't change. Maybe because the A value is trying to be set on a copy of a slice from a DataFrame warning is triggered in the same run. I've also tried with df.mask() and df.where(). But to no avail. I'm clearly failing at something very basic here, but I'd really like to know how to do this properly. There are similarly sounding questions such as Performing calculations on subset of data frame subset in Python, but the suggested solutions here are pointing towards df.groupby(), and I don't think this necessarily is the right approach here. Thank you for any suggestions! Here's a fully reproducible dataset: import pandas as pd df = pd.DataFrame({ 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] }) df = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix=r'\w+') df.reset_index(inplace = True) A: To adjust a subset of a column in a pandas dataframe, you can use the loc method. The loc method allows you to access a subset of the dataframe by specifying the values in the rows and columns that you want. In your case, you want to adjust the values in the ht column where the age column is equal to one. You can do this with the following code: df.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6 The first argument to the loc method is a condition that specifies the rows that you want to select. In this case, the condition is df['age'] == 'one', which selects all rows where the value in the age column is one. The second argument specifies the column or columns that you want to adjust. In this case, we want to adjust the ht column, so the second argument is 'ht'. Finally, the right-hand side of the assignment operator sets the new values for the selected rows and columns. In this case, the right-hand side is df[df['age'] == 'one']['ht'] * 10**6, which multiplies the values in the ht column for rows where the age column is one by 10^6. After running this code, the values in the ht column where the age column is one will be adjusted as desired. Here's an example of how you could use this code in your case: import pandas as pd df = pd.DataFrame({ 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] }) df = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix=r'\w+') df.reset_index(inplace = True) # Adjust the values in the ht column where the age column is 'one' df.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6 # Print the updated dataframe print(df) After running this code, the dataframe will have the adjusted values in the ht column where the age column is one. A: Let's try this: df.loc[df['age'] == 'one', 'ht'] *= 10**6 Output: famid birth age ht 0 1 1 one 2800000.0 1 1 1 two 3.4 2 1 2 one 2900000.0 3 1 2 two 3.8 4 1 3 one 2200000.0 5 1 3 two 2.9 6 2 1 one 2000000.0 7 2 1 two 3.2 8 2 2 one 1800000.0 9 2 2 two 2.8 10 2 3 one 1900000.0 11 2 3 two 2.4 12 3 1 one 2200000.0 13 3 1 two 3.3 14 3 2 one 2300000.0 15 3 2 two 3.4 16 3 3 one 2100000.0 17 3 3 two 2.9 A: To perform calculations on a subset of a column in a pandas dataframe, you can use the .loc method to select the subset of the dataframe and then apply the calculation to that subset. For example, to multiply the ht values for rows where age is equal to one by 10^6, you could use the following code: df.loc[df['age']=='one', 'ht'] = df.loc[df['age']=='one', 'ht'] * 10**6 This code selects the subset of rows where age is one using df.loc[df['age']=='one'], and then applies the multiplication operation to the ht column in that subset using df.loc[df['age']=='one', 'ht'] * 10**6. You can also use the .loc method to perform calculations on multiple columns in the subset. For example, if you wanted to multiply the ht values by 10^6 and then add 1000 to the birth values for rows where age is one, you could use the following code: df.loc[df['age']=='one', ['ht', 'birth']] = df.loc[df['age']=='one', ['ht', 'birth']] A: To adjust values in a subset of a DataFrame, you can use the loc method and select the rows you want to adjust using a boolean mask. The syntax for modifying values using loc is as follows: df.loc[mask, column] = new_value where mask is a boolean array that specifies which rows to adjust, column is the name of the column to adjust, and new_value is the value to assign to the selected rows. In your case, you want to adjust the ht column for rows where the age column is equal to "one", so your mask would be df['age'] == 'one'. To modify the values in the ht column, you would use the following code: df.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6 This code will select the rows where age is equal to "one", and then set the values in the ht column to their current value times 10^6. Alternatively, you can use the isin method to create your boolean mask, which can make the code more readable. The isin method returns a boolean array where each element is True if the corresponding value in the column is in the given list of values, and False otherwise. So, to create a mask for rows where the age column is equal to "one", you can use the following code: mask = df['age'].isin(['one']) Then you can use this mask with the loc method to modify the values in the ht column: df.loc[mask, 'ht'] = df[mask]['ht'] * 10**6 I hope this helps! Let me know if you have any other questions. A: Here is a way: df.assign(ht = df['ht'].mask(df['age'].isin(['one']),df['ht'].mul(10**6))) by using isin(), more values from the age column can be added. Output: famid birth age ht 0 1 1 one 2800000.0 1 1 1 two 3.4 2 1 2 one 2900000.0 3 1 2 two 3.8 4 1 3 one 2200000.0 5 1 3 two 2.9 6 2 1 one 2000000.0 7 2 1 two 3.2 8 2 2 one 1800000.0 9 2 2 two 2.8 10 2 3 one 1900000.0 11 2 3 two 2.4 12 3 1 one 2200000.0 13 3 1 two 3.3 14 3 2 one 2300000.0 15 3 2 two 3.4 16 3 3 one 2100000.0 17 3 3 two 2.9
How to perform calculations on a subset of a column in a pandas dataframe?
With a dataset such as this: famid birth age ht 0 1 1 one 2.8 1 1 1 two 3.4 2 1 2 one 2.9 3 1 2 two 3.8 4 1 3 one 2.2 5 1 3 two 2.9 ...where we've got values for a variable ht for different categories of, for example, age , I would like to adjust a subset of the data in df['ht'] where df['age'] == 'one' only. And I would like to do it without creating a new column. I've tried: df[df['age']=='one']['ht'] = df[df['age']=='one']['ht']*10**6 But to my mild surprise the numbers don't change. Maybe because the A value is trying to be set on a copy of a slice from a DataFrame warning is triggered in the same run. I've also tried with df.mask() and df.where(). But to no avail. I'm clearly failing at something very basic here, but I'd really like to know how to do this properly. There are similarly sounding questions such as Performing calculations on subset of data frame subset in Python, but the suggested solutions here are pointing towards df.groupby(), and I don't think this necessarily is the right approach here. Thank you for any suggestions! Here's a fully reproducible dataset: import pandas as pd df = pd.DataFrame({ 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3], 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1], 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9] }) df = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age', sep='_', suffix=r'\w+') df.reset_index(inplace = True)
[ "To adjust a subset of a column in a pandas dataframe, you can use the loc method. The loc method allows you to access a subset of the dataframe by specifying the values in the rows and columns that you want. In your case, you want to adjust the values in the ht column where the age column is equal to one. You can do this with the following code:\ndf.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6\n\nThe first argument to the loc method is a condition that specifies the rows that you want to select. In this case, the condition is df['age'] == 'one', which selects all rows where the value in the age column is one. The second argument specifies the column or columns that you want to adjust. In this case, we want to adjust the ht column, so the second argument is 'ht'. Finally, the right-hand side of the assignment operator sets the new values for the selected rows and columns. In this case, the right-hand side is df[df['age'] == 'one']['ht'] * 10**6, which multiplies the values in the ht column for rows where the age column is one by 10^6.\nAfter running this code, the values in the ht column where the age column is one will be adjusted as desired. Here's an example of how you could use this code in your case:\nimport pandas as pd\n\ndf = pd.DataFrame({\n 'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],\n 'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],\n 'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n 'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]\n})\ndf = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age',\n sep='_', suffix=r'\\w+')\ndf.reset_index(inplace = True)\n\n# Adjust the values in the ht column where the age column is 'one'\ndf.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6\n\n# Print the updated dataframe\nprint(df)\n\nAfter running this code, the dataframe will have the adjusted values in the ht column where the age column is one.\n", "Let's try this:\ndf.loc[df['age'] == 'one', 'ht'] *= 10**6\n\nOutput:\n famid birth age ht\n0 1 1 one 2800000.0\n1 1 1 two 3.4\n2 1 2 one 2900000.0\n3 1 2 two 3.8\n4 1 3 one 2200000.0\n5 1 3 two 2.9\n6 2 1 one 2000000.0\n7 2 1 two 3.2\n8 2 2 one 1800000.0\n9 2 2 two 2.8\n10 2 3 one 1900000.0\n11 2 3 two 2.4\n12 3 1 one 2200000.0\n13 3 1 two 3.3\n14 3 2 one 2300000.0\n15 3 2 two 3.4\n16 3 3 one 2100000.0\n17 3 3 two 2.9\n\n", "To perform calculations on a subset of a column in a pandas dataframe, you can use the .loc method to select the subset of the dataframe and then apply the calculation to that subset. For example, to multiply the ht values for rows where age is equal to one by 10^6, you could use the following code:\ndf.loc[df['age']=='one', 'ht'] = df.loc[df['age']=='one', 'ht'] * 10**6\n\nThis code selects the subset of rows where age is one using df.loc[df['age']=='one'], and then applies the multiplication operation to the ht column in that subset using df.loc[df['age']=='one', 'ht'] * 10**6.\nYou can also use the .loc method to perform calculations on multiple columns in the subset. For example, if you wanted to multiply the ht values by 10^6 and then add 1000 to the birth values for rows where age is one, you could use the following code:\ndf.loc[df['age']=='one', ['ht', 'birth']] = df.loc[df['age']=='one', ['ht', 'birth']]\n\n", "To adjust values in a subset of a DataFrame, you can use the loc method and select the rows you want to adjust using a boolean mask. The syntax for modifying values using loc is as follows:\ndf.loc[mask, column] = new_value\n\nwhere mask is a boolean array that specifies which rows to adjust, column is the name of the column to adjust, and new_value is the value to assign to the selected rows.\nIn your case, you want to adjust the ht column for rows where the age column is equal to \"one\", so your mask would be df['age'] == 'one'. To modify the values in the ht column, you would use the following code:\ndf.loc[df['age'] == 'one', 'ht'] = df[df['age'] == 'one']['ht'] * 10**6\n\nThis code will select the rows where age is equal to \"one\", and then set the values in the ht column to their current value times 10^6.\nAlternatively, you can use the isin method to create your boolean mask, which can make the code more readable. The isin method returns a boolean array where each element is True if the corresponding value in the column is in the given list of values, and False otherwise. So, to create a mask for rows where the age column is equal to \"one\", you can use the following code:\nmask = df['age'].isin(['one'])\n\nThen you can use this mask with the loc method to modify the values in the ht column:\ndf.loc[mask, 'ht'] = df[mask]['ht'] * 10**6\n\nI hope this helps! Let me know if you have any other questions.\n", "Here is a way:\ndf.assign(ht = df['ht'].mask(df['age'].isin(['one']),df['ht'].mul(10**6)))\n\nby using isin(), more values from the age column can be added.\nOutput:\n famid birth age ht\n0 1 1 one 2800000.0\n1 1 1 two 3.4\n2 1 2 one 2900000.0\n3 1 2 two 3.8\n4 1 3 one 2200000.0\n5 1 3 two 2.9\n6 2 1 one 2000000.0\n7 2 1 two 3.2\n8 2 2 one 1800000.0\n9 2 2 two 2.8\n10 2 3 one 1900000.0\n11 2 3 two 2.4\n12 3 1 one 2200000.0\n13 3 1 two 3.3\n14 3 2 one 2300000.0\n15 3 2 two 3.4\n16 3 3 one 2100000.0\n17 3 3 two 2.9\n\n" ]
[ 2, 2, 1, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074670948_dataframe_pandas_python.txt
Q: Can g++ / minGW play nice with the Windows SDK? Is Visual Studio the only option? Can g++ and minGW on Windows XP use the Windows SDK? Specifically, why does g++ fail to compile: #include <stdio.h> #include <windows.h> int main(void) { printf("!!!Hello World!!!"); return EXIT_SUCCESS; } I have tried compiling by by running: g++ -c -Wall Test.cpp -IC:/Program\ Files/Microsoft\ Platform\ SDK/Include/ I get a litany of compile errors beginning with winnt.h:666:2: #error Must define a target architecture. I have installed the Windows Server 2003 SP1 Platform SDK Background I am working on a large real-time image processing software project that up until now has used g++, minGW and gnu make files (written by hand). For a new feature, I need to interface with a frame grabber that has an SDK which was designed for Visual Studio. The framegrabber SDK depends on header files from the Windows SDK. Do I need to learn Visual Studio or is there another way? A: I use MinGW to compile Windows programs every day, with zero problems. There must be something wrong with your installation - try the version at Twilight Dragon Media. Edit: Just re-read your post - you do not need to specify the include directory as you are doing, and probably should not do so. Also, you may (or may not) need the slightly mysterious -mwindows flag. I just compiled your program using MinGW (TDM build) g++ 4.4.1, with the command line: g++ main.cpp with absolutely no problems. More Info: Just so you know what the -mwindows flag does, the GCC docs say: This option is available for Cygwin and MinGW targets.It specifes that a GUI application is to be generated by instructing the linker to set the PE header subsystem type appropriately. Personally, I've never found it necessary, but then my Windows apps are all command line tools or servers. A: According to the discussions from the MinGW-users mailing list, you might encounter compatibility problems with the Windows SDK, and you may have to fix those problems yourself. Georgi Petrov [Dec 27, 2010; 8:33am]: Hello, I'm trying to develop a EVR (Vista/7 specific video presentation API) renderer for MPlayer on MSYS/MinGW. The problem is that I have Windows SDK v7.1 and I need evr.h from it. If I try to copy it to MinGW's include directory as well as the 12 header files it includes, the compilation is close to impossible. I have a TON of errors just by including evr.h, nothing else. I investigated and found that I can't use the Windows SDK header files directly with MinGW, because it ships with its own header files, which are sometimes very, very different. The problem is that Media Foundation/Enhanced Video Renderer header files are not part of MinGW's header files. What should I do? Windows SDK header files question: http://mingw-users.1079350.n2.nabble.com/Windows-SDK-header-files-question-td5870336.html Ross Ridge [Oct 10, 2010; 10:16pm]: For the most part the Windows SDK headers aren't incompatible with GCC. If there one particular header file you need that doesn't exist in win32api heapers or is missing something you need, then you can try just using that one header with from the Windows SDK and use win32api for the rest. It's also possible to only use Windows SDK headers, and avoid using the win32api headers entirely, but you need to fix a number of problems in key header files. I used to just modify the headers, but the Windows SDK has actually gotten a bit more compatible and now I use wrappers to fix the problems. There are some header files and libraries that are pretty much fundementally incompatible with GCC, like GDI+. If you want to use GDI+, you'll need to use a Microsoft compiler. Ross Ridge compiling against Windows SDK: http://mingw-users.1079350.n2.nabble.com/compiling-against-Windows-SDK-td5609389.html A: try adding these defines before you include those windows headers #define WINVER 0x0501 #define _WIN32_WINNT 0x0501 EDIT: my gcc compiles your script without problems (and without these defines) aswell. I am using mingw's gcc 4.40 (alpha ?!) A: Try using the latest version of MSYS2 UCRT64 with MingW64. I'm using it on Windows 11. Use 'pacman' to install 'mingw-w64-x86_64-gcc'. Try re-installing it too to insure you have the WIN32 SDK which is included in this windows-based package: $ pacman -S mingw-w64-x86_64-gcc warning: mingw-w64-x86_64-gcc-12.2.0-6 is up to date -- reinstalling resolving dependencies... looking for conflicting packages... Packages (1) mingw-w64-x86_64-gcc-12.2.0-6 Total Installed Size: 154.48 MiB Net Upgrade Size: 0.00 MiB :: Proceed with installation? [Y/n] Y (1/1) checking keys in keyring [###############################] 100% (1/1) checking package integrity [###############################] 100% (1/1) loading package files [###############################] 100% (1/1) checking for file conflicts [###############################] 100% (1/1) checking available disk space [###############################] 100% :: Processing package changes... (1/1) reinstalling mingw-w64-x86_64-gcc [###############################] 100% I discovered the windows.h is located in '/ucrt64/include' within the shell session and 'C:\Msys64\ucrt64\include' outside the shell: $ find . -name windows.h ./mingw64/include/windows.h ./ucrt64/include/windows.h Here's a link to an article from Microsoft which shows how to troubleshoot setting up gcc to work with building windows applications: https://code.visualstudio.com/docs/cpp/config-mingw You can add the directories to your build using the '-I' parameter on 'make' or 'gcc': make -I /ucrt64/include
Can g++ / minGW play nice with the Windows SDK? Is Visual Studio the only option?
Can g++ and minGW on Windows XP use the Windows SDK? Specifically, why does g++ fail to compile: #include <stdio.h> #include <windows.h> int main(void) { printf("!!!Hello World!!!"); return EXIT_SUCCESS; } I have tried compiling by by running: g++ -c -Wall Test.cpp -IC:/Program\ Files/Microsoft\ Platform\ SDK/Include/ I get a litany of compile errors beginning with winnt.h:666:2: #error Must define a target architecture. I have installed the Windows Server 2003 SP1 Platform SDK Background I am working on a large real-time image processing software project that up until now has used g++, minGW and gnu make files (written by hand). For a new feature, I need to interface with a frame grabber that has an SDK which was designed for Visual Studio. The framegrabber SDK depends on header files from the Windows SDK. Do I need to learn Visual Studio or is there another way?
[ "I use MinGW to compile Windows programs every day, with zero problems. There must be something wrong with your installation - try the version at Twilight Dragon Media.\nEdit: Just re-read your post - you do not need to specify the include directory as you are doing, and probably should not do so. Also, you may (or may not) need the slightly mysterious -mwindows flag. I just compiled your program using MinGW (TDM build) g++ 4.4.1, with the command line:\ng++ main.cpp\n\nwith absolutely no problems.\nMore Info: Just so you know what the -mwindows flag does, the GCC docs say:\n\nThis option is available for Cygwin and\n MinGW targets.It specifes that a GUI\n application is to be generated by\n instructing the linker to set the\n PE header subsystem type appropriately.\n\nPersonally, I've never found it necessary, but then my Windows apps are all command line tools or servers.\n", "According to the discussions from the MinGW-users mailing list, you might encounter compatibility problems with the Windows SDK, and you may have to fix those problems yourself.\n\nGeorgi Petrov [Dec 27, 2010; 8:33am]:\n\nHello, \nI'm trying to develop a EVR (Vista/7 specific video presentation API) \n renderer for MPlayer on MSYS/MinGW. The problem is that I have Windows\n SDK v7.1 and I need evr.h from it. If I try to copy it to MinGW's \n include directory as well as the 12 header files it includes, the \n compilation is close to impossible. I have a TON of errors just by \n including evr.h, nothing else. I investigated and found that I can't \n use the Windows SDK header files directly with MinGW, because it ships\n with its own header files, which are sometimes very, very different. \n The problem is that Media Foundation/Enhanced Video Renderer header \n files are not part of MinGW's header files. \nWhat should I do?\n\n\nWindows SDK header files question:\nhttp://mingw-users.1079350.n2.nabble.com/Windows-SDK-header-files-question-td5870336.html\n\n\nRoss Ridge [Oct 10, 2010; 10:16pm]:\n\nFor the most part the Windows SDK headers aren't incompatible with\n GCC. If there one particular header file you need that doesn't exist\n in win32api heapers or is missing something you need, then you can\n try just using that one header with from the Windows SDK and use\n win32api for the rest. \nIt's also possible to only use Windows SDK headers, and avoid using\n the win32api headers entirely, but you need to fix a number of\n problems in key header files. I used to just modify the headers, but\n the Windows SDK has actually gotten a bit more compatible and now I\n use wrappers to fix the problems. \nThere are some header files and libraries that are pretty much \n fundementally incompatible with GCC, like GDI+. If you want to use\n GDI+, you'll need to use a Microsoft compiler. \n Ross Ridge\n\n\n\ncompiling against Windows SDK:\nhttp://mingw-users.1079350.n2.nabble.com/compiling-against-Windows-SDK-td5609389.html\n\n", "try adding these defines before you include those windows headers\n#define WINVER 0x0501\n#define _WIN32_WINNT 0x0501\n\nEDIT: my gcc compiles your script without problems (and without these defines) aswell.\nI am using mingw's gcc 4.40 (alpha ?!)\n", "Try using the latest version of MSYS2 UCRT64 with MingW64. I'm using it on Windows 11.\nUse 'pacman' to install 'mingw-w64-x86_64-gcc'. Try re-installing it too to insure you have the WIN32 SDK which is included in this windows-based package:\n$ pacman -S mingw-w64-x86_64-gcc\nwarning: mingw-w64-x86_64-gcc-12.2.0-6 is up to date -- reinstalling\nresolving dependencies...\nlooking for conflicting packages...\n\nPackages (1) mingw-w64-x86_64-gcc-12.2.0-6\n\nTotal Installed Size: 154.48 MiB\nNet Upgrade Size: 0.00 MiB\n\n:: Proceed with installation? [Y/n] Y\n(1/1) checking keys in keyring [###############################] 100%\n(1/1) checking package integrity [###############################] 100%\n(1/1) loading package files [###############################] 100%\n(1/1) checking for file conflicts [###############################] 100%\n(1/1) checking available disk space [###############################] 100%\n:: Processing package changes...\n(1/1) reinstalling mingw-w64-x86_64-gcc [###############################] 100%\n\nI discovered the windows.h is located in '/ucrt64/include' within the shell session and 'C:\\Msys64\\ucrt64\\include' outside the shell:\n$ find . -name windows.h\n./mingw64/include/windows.h\n./ucrt64/include/windows.h\n\nHere's a link to an article from Microsoft which shows how to troubleshoot setting up gcc to work with building windows applications:\nhttps://code.visualstudio.com/docs/cpp/config-mingw\nYou can add the directories to your build using the '-I' parameter on 'make' or 'gcc':\nmake -I /ucrt64/include\n\n" ]
[ 15, 4, 0, 0 ]
[]
[]
[ "c++", "g++", "mingw", "visual_studio", "windows" ]
stackoverflow_0002022112_c++_g++_mingw_visual_studio_windows.txt
Q: how to check if a number is even or not in python I am attempting to make a collatz conjecture program, but I can't figure out how to check for even numbers this is my current code for it elif (original_collatz % 2) == 0: new_collatz = collatz/2 anyone have an idea how to check i tried it with modulo but could figure out how it works, and my program just ignores this line, whole program: ` #collatz program import time collatz = 7 original_collatz = collatz new_collatz = collatz while True: if original_collatz % 2 == 1: new_collatz = (collatz * 3) + 1 elif (original_collatz % 2) == 0: new_collatz = collatz/2 collatz = new_collatz print(collatz) if collatz == 1: print('woo hoo') original_collatz += 1 time.sleep(1) A: The problem is not that "your program ignore the lines", it's that you test the parity of original_collatz which doesn't change. You need to check the parity of collatz You need to use integer division (//) when dividing by two or collatz will become a float. You don't really need to use new_collatz as an intermediate, you could just overwrite collatz directly. Here is a fixed sample: # collatz program import time collatz = 7 original_collatz = collatz new_collatz = collatz while True: if collatz % 2 == 1: new_collatz = (collatz * 3) + 1 else: new_collatz = collatz // 2 collatz = new_collatz print(collatz) if collatz == 1: print('woo hoo') original_collatz += 1 collatz = original_collatz time.sleep(1) A: Working example: import time collatz_init = 7 collatz = collatz_init while True: if collatz % 2 == 1: collatz = (collatz * 3) + 1 else: collatz //= 2 print(collatz) if collatz == 1: print('woo hoo') collatz_init += 1 collatz = collatz_init time.sleep(1)
how to check if a number is even or not in python
I am attempting to make a collatz conjecture program, but I can't figure out how to check for even numbers this is my current code for it elif (original_collatz % 2) == 0: new_collatz = collatz/2 anyone have an idea how to check i tried it with modulo but could figure out how it works, and my program just ignores this line, whole program: ` #collatz program import time collatz = 7 original_collatz = collatz new_collatz = collatz while True: if original_collatz % 2 == 1: new_collatz = (collatz * 3) + 1 elif (original_collatz % 2) == 0: new_collatz = collatz/2 collatz = new_collatz print(collatz) if collatz == 1: print('woo hoo') original_collatz += 1 time.sleep(1)
[ "The problem is not that \"your program ignore the lines\", it's that you test the parity of original_collatz which doesn't change.\n\nYou need to check the parity of collatz\nYou need to use integer division (//) when dividing by two or collatz will become a float.\nYou don't really need to use new_collatz as an intermediate, you could just overwrite collatz directly.\n\nHere is a fixed sample:\n# collatz program\nimport time\n\ncollatz = 7\noriginal_collatz = collatz\nnew_collatz = collatz\n\nwhile True:\n if collatz % 2 == 1:\n new_collatz = (collatz * 3) + 1\n\n else:\n new_collatz = collatz // 2\n\n collatz = new_collatz\n\n print(collatz)\n\n if collatz == 1:\n print('woo hoo')\n original_collatz += 1\n collatz = original_collatz\n\n time.sleep(1)\n\n", "Working example:\nimport time\n\ncollatz_init = 7\ncollatz = collatz_init\n\nwhile True:\n if collatz % 2 == 1:\n collatz = (collatz * 3) + 1\n else:\n collatz //= 2\n\n print(collatz)\n\n if collatz == 1:\n print('woo hoo')\n collatz_init += 1\n collatz = collatz_init\n\n time.sleep(1)\n\n" ]
[ 1, 1 ]
[]
[]
[ "collatz", "integer", "modulo", "python" ]
stackoverflow_0074671339_collatz_integer_modulo_python.txt
Q: Unable to install yfinance The package will not install. In the command prompt I entered, 'pip install yfinance' C:\Users\gam19\AppData\Local\Temp\xmlXPathInitw4g8q0z6.c(1): fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x86\\cl.exe' failed with exit code 2 ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> lxml note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure. A: You can download the wheel from https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml and install it (E.g. pip install lxml‑4.9.0‑cp311‑cp311‑win_amd64.whl). Trying 'pip install yfinance' might work after that.
Unable to install yfinance
The package will not install. In the command prompt I entered, 'pip install yfinance' C:\Users\gam19\AppData\Local\Temp\xmlXPathInitw4g8q0z6.c(1): fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x86\\cl.exe' failed with exit code 2 ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> lxml note: This is an issue with the package mentioned above, not pip. hint: See above for output from the failure.
[ "You can download the wheel from https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml and install it (E.g. pip install lxml‑4.9.0‑cp311‑cp311‑win_amd64.whl). Trying 'pip install yfinance' might work after that.\n" ]
[ 0 ]
[]
[]
[ "libxml2", "yfinance" ]
stackoverflow_0074549570_libxml2_yfinance.txt
Q: Prevent a function which executes itself after 1 second from being executed every 1 second one by one in a for loop I have a function which makes players die after 1 second. But if I have 2 players, first player will die after 1 second and then the second will die in 1 second. I want them both to die in the same time in the first second (together) dieAfter1Second() { for (int players = 0; players < maxPlayers; players ++) { dieAfter1Second(); // executes itself after 1 second } } How can i execute dieAfter1Second() for all players? A: One way to execute the function for all players in the same time would be to use a timer, such as std::chrono::steady_clock. This would allow you to wait for 1 second before calling the function for each player. Here is an example of how you could do this: #include <chrono> // for std::chrono::steady_clock #include <iostream> // for std::cout // Function to make a player die after 1 second void dieAfter1Second() { std::cout << "Player died" << std::endl; } int main() { // Set the number of maximum players const int maxPlayers = 2; // Wait for 1 second before calling the function for each player std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); while (std::chrono::duration_caststd::chrono::seconds(std::chrono::steady_clock::now() - start).count() < 1) { } for (int players = 0; players < maxPlayers; players ++) { dieAfter1Second(); } return 0; } This code will wait for 1 second before calling the dieAfter1Second() function for each player. It will print "Player died" for each player, and they will all die in the same time in the first second. Note: This code uses the C++11 standard. If you are using an older version of C++, you may need to use a different timer, such as std::clock_t or std::time().
Prevent a function which executes itself after 1 second from being executed every 1 second one by one in a for loop
I have a function which makes players die after 1 second. But if I have 2 players, first player will die after 1 second and then the second will die in 1 second. I want them both to die in the same time in the first second (together) dieAfter1Second() { for (int players = 0; players < maxPlayers; players ++) { dieAfter1Second(); // executes itself after 1 second } } How can i execute dieAfter1Second() for all players?
[ "One way to execute the function for all players in the same time would be to use a timer, such as std::chrono::steady_clock. This would allow you to wait for 1 second before calling the function for each player.\nHere is an example of how you could do this:\n#include <chrono> // for std::chrono::steady_clock\n#include <iostream> // for std::cout\n\n// Function to make a player die after 1 second\nvoid dieAfter1Second() {\nstd::cout << \"Player died\" << std::endl;\n}\n\nint main() {\n// Set the number of maximum players\nconst int maxPlayers = 2;\n\n// Wait for 1 second before calling the function for each player\nstd::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();\nwhile (std::chrono::duration_caststd::chrono::seconds(std::chrono::steady_clock::now() - start).count() < 1) { }\nfor (int players = 0; players < maxPlayers; players ++) {\ndieAfter1Second();\n}\n\nreturn 0;\n}\n\nThis code will wait for 1 second before calling the dieAfter1Second() function for each player. It will print \"Player died\" for each player, and they will all die in the same time in the first second.\nNote: This code uses the C++11 standard. If you are using an older version of C++, you may need to use a different timer, such as std::clock_t or std::time().\n" ]
[ -1 ]
[]
[]
[ "c++" ]
stackoverflow_0074671392_c++.txt
Q: How to solve heap buffer overflow I am having hard time solving problem with my program. It seems to be running as it should. But when I compile it with adress sanitizer I get heap buffer overflow. The function gets a 2d array containg a word to look for - replace [a][0] and a word next to it, which will be later used to replace it. const char * findInArray(const char * (*replace)[2], char * start) // function goes through a array 'start' and searches if the word is also in 'replace' { char * copy = (char *) malloc (strlen(start)+1); // I made a copy of a field, so I do not modify the one I passed to function char * total = (char *) malloc (strlen(start)+2); // Here I will add words from copy one by one memmove(copy,start,strlen(start)+1); // I fill the copy array char * tokens = strtok (copy," "); // I split copy array while (tokens != NULL) { printf("%lu ",strlen(total)); memmove(total+strlen(total)+1,tokens,strlen(tokens)); // I add words to a new array one by one memmove (total + strlen(total)," ",1); // at the end of each word I add space for (int i = 0 ; replace[i][0] != NULL; i++) // I search if word is in array or not, if yes I return its adress {const char *ptr = strstr(total,replace[i][0]); if (ptr != NULL) // If there is match - I return pointer to a word that will be replaced { free (total); return replace[i][0]; } } //printf("%s\n",tokens); tokens = strtok(NULL, " "); } free (total); return NULL; } The problem if I understand it correctly is that I read values to total array, when It already has been allocated - which does not make a lot of sense to me. Here is the error message: ==58229==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x000104d00bbb at pc 0x000102c7468c bp 0x00016d562b20 sp 0x00016d5622d8 READ of size 44 at 0x000104d00bbb thread T0 #0 0x102c74688 in wrap_strlen+0x164 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x14688) #1 0x10289e4dc in findInArray test 4.c:39 // the line of moving memory to total #2 0x10289ee14 in newSpeak test 4.c:129 #3 0x10289f880 in main test 4.c:186 #4 0x1b4df7e4c (<unknown module>) 0x000104d00bbb is located 0 bytes to the right of 43-byte region [0x000104d00b90,0x000104d00bbb) allocated by thread T0 here: #0 0x102c9eca8 in wrap_malloc+0x94 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x3eca8) #1 0x10289e480 in findInArray test 4.c:31 // the line of allocating total array #2 0x10289ee14 in newSpeak test 4.c:129 #3 0x10289f880 in main test 4.c:186 #4 0x1b4df7e4c (<unknown module>) Thank you for any help. A: It looks like the issue is with how you are allocating memory for the total array. In the line char * total = (char *) malloc (strlen(start)+2);, you are allocating memory for total by adding 2 to the length of start. However, in the line memmove(total+strlen(total)+1,tokens,strlen(tokens));, you are adding a word to total by adding 1 to its length. This means that total will not have enough allocated memory to store the added word, and you will get a heap buffer overflow error. To fix this, you can either add 2 to the length of total when adding a new word, or simply allocate enough memory for total to store the entire start string plus the added word. For example: char * total = (char *) malloc (strlen(start)+strlen(tokens)+1); // Allocate enough memory for 'total' // Add the word to 'total' memmove(total+strlen(total),tokens,strlen(tokens)+1); // Add the word to 'total' memmove (total + strlen(total)," ",1); // Add a space at the end This should fix the heap buffer overflow error and allow your program to run correctly. Note that you may also want to check the return value of malloc to make sure it is not NULL before using the allocated memory, to avoid further issues.
How to solve heap buffer overflow
I am having hard time solving problem with my program. It seems to be running as it should. But when I compile it with adress sanitizer I get heap buffer overflow. The function gets a 2d array containg a word to look for - replace [a][0] and a word next to it, which will be later used to replace it. const char * findInArray(const char * (*replace)[2], char * start) // function goes through a array 'start' and searches if the word is also in 'replace' { char * copy = (char *) malloc (strlen(start)+1); // I made a copy of a field, so I do not modify the one I passed to function char * total = (char *) malloc (strlen(start)+2); // Here I will add words from copy one by one memmove(copy,start,strlen(start)+1); // I fill the copy array char * tokens = strtok (copy," "); // I split copy array while (tokens != NULL) { printf("%lu ",strlen(total)); memmove(total+strlen(total)+1,tokens,strlen(tokens)); // I add words to a new array one by one memmove (total + strlen(total)," ",1); // at the end of each word I add space for (int i = 0 ; replace[i][0] != NULL; i++) // I search if word is in array or not, if yes I return its adress {const char *ptr = strstr(total,replace[i][0]); if (ptr != NULL) // If there is match - I return pointer to a word that will be replaced { free (total); return replace[i][0]; } } //printf("%s\n",tokens); tokens = strtok(NULL, " "); } free (total); return NULL; } The problem if I understand it correctly is that I read values to total array, when It already has been allocated - which does not make a lot of sense to me. Here is the error message: ==58229==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x000104d00bbb at pc 0x000102c7468c bp 0x00016d562b20 sp 0x00016d5622d8 READ of size 44 at 0x000104d00bbb thread T0 #0 0x102c74688 in wrap_strlen+0x164 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x14688) #1 0x10289e4dc in findInArray test 4.c:39 // the line of moving memory to total #2 0x10289ee14 in newSpeak test 4.c:129 #3 0x10289f880 in main test 4.c:186 #4 0x1b4df7e4c (<unknown module>) 0x000104d00bbb is located 0 bytes to the right of 43-byte region [0x000104d00b90,0x000104d00bbb) allocated by thread T0 here: #0 0x102c9eca8 in wrap_malloc+0x94 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x3eca8) #1 0x10289e480 in findInArray test 4.c:31 // the line of allocating total array #2 0x10289ee14 in newSpeak test 4.c:129 #3 0x10289f880 in main test 4.c:186 #4 0x1b4df7e4c (<unknown module>) Thank you for any help.
[ "It looks like the issue is with how you are allocating memory for the total array. In the line char * total = (char *) malloc (strlen(start)+2);, you are allocating memory for total by adding 2 to the length of start. However, in the line memmove(total+strlen(total)+1,tokens,strlen(tokens));, you are adding a word to total by adding 1 to its length. This means that total will not have enough allocated memory to store the added word, and you will get a heap buffer overflow error.\nTo fix this, you can either add 2 to the length of total when adding a new word, or simply allocate enough memory for total to store the entire start string plus the added word. For example:\nchar * total = (char *) malloc (strlen(start)+strlen(tokens)+1); // Allocate enough memory for 'total'\n\n// Add the word to 'total'\nmemmove(total+strlen(total),tokens,strlen(tokens)+1); // Add the word to 'total'\nmemmove (total + strlen(total),\" \",1); // Add a space at the end\n\nThis should fix the heap buffer overflow error and allow your program to run correctly. Note that you may also want to check the return value of malloc to make sure it is not NULL before using the allocated memory, to avoid further issues.\n" ]
[ 0 ]
[]
[]
[ "buffer_overflow", "c" ]
stackoverflow_0074669054_buffer_overflow_c.txt
Q: R magick `image_annotate()` produces `NonconformingDrawingPrimitiveDefinition text` error When trying to add text to an image with the image_annotate() function from the magick package in R on macOS, I now get an error complaining of NonconformingDrawingPrimitiveDefinition text. I have run brew install ghostscript and brew install imagemagick, both of which report the current versions are installed. What might be causing this error? library(magick) #> Linking to ImageMagick 6.9.12.3 #> Enabled features: cairo, fontconfig, freetype, heic, lcms, pango, raw, rsvg, webp #> Disabled features: fftw, ghostscript, x11 # Load a test image frink <- image_read("https://jeroen.github.io/images/frink.png") # Attempt to annotate with some text image_annotate(frink, "frink") #> Error in magick_image_annotate(image, text, gravity, location, degrees, : R: NonconformingDrawingPrimitiveDefinition `text' @ error/draw.c/RenderMVGContent/4405 # magick package configuration str(magick_config()) #> List of 24 #> $ version :Class 'numeric_version' hidden list of 1 #> ..$ : int [1:4] 6 9 12 3 #> $ modules : logi FALSE #> $ cairo : logi TRUE #> $ fontconfig : logi TRUE #> $ freetype : logi TRUE #> $ fftw : logi FALSE #> $ ghostscript : logi FALSE #> $ heic : logi TRUE #> $ jpeg : logi TRUE #> $ lcms : logi TRUE #> $ libopenjp2 : logi TRUE #> $ lzma : logi TRUE #> $ pangocairo : logi TRUE #> $ pango : logi TRUE #> $ png : logi TRUE #> $ raw : logi TRUE #> $ rsvg : logi TRUE #> $ tiff : logi TRUE #> $ webp : logi TRUE #> $ wmf : logi FALSE #> $ x11 : logi FALSE #> $ xml : logi TRUE #> $ zero-configuration: logi TRUE #> $ threads : int 1 Created on 2022-04-18 by the reprex package (v2.0.1) Session info sessioninfo::session_info() #> ─ Session info ─────────────────────────────────────────────────────────────── #> setting value #> version R version 4.1.2 (2021-11-01) #> os macOS Monterey 12.3 #> system aarch64, darwin20 #> ui X11 #> language (EN) #> collate en_GB.UTF-8 #> ctype en_GB.UTF-8 #> tz Europe/London #> date 2022-04-18 #> pandoc 2.14.0.3 @ /Applications/RStudio.app/Contents/MacOS/pandoc/ (via rmarkdown) #> #> ─ Packages ─────────────────────────────────────────────────────────────────── #> package * version date (UTC) lib source #> cli 3.2.0 2022-02-14 [1] CRAN (R 4.1.1) #> crayon 1.5.1 2022-03-26 [1] CRAN (R 4.1.1) #> curl 4.3.2 2021-06-23 [1] CRAN (R 4.1.0) #> digest 0.6.29 2021-12-01 [1] CRAN (R 4.1.1) #> ellipsis 0.3.2 2021-04-29 [1] CRAN (R 4.1.0) #> evaluate 0.15 2022-02-18 [1] CRAN (R 4.1.1) #> fansi 1.0.3 2022-03-24 [1] CRAN (R 4.1.1) #> fastmap 1.1.0 2021-01-25 [1] CRAN (R 4.1.0) #> fs 1.5.2 2021-12-08 [1] CRAN (R 4.1.1) #> glue 1.6.2 2022-02-24 [1] CRAN (R 4.1.1) #> highr 0.9 2021-04-16 [1] CRAN (R 4.1.0) #> htmltools 0.5.2 2021-08-25 [1] CRAN (R 4.1.1) #> knitr 1.38 2022-03-25 [1] CRAN (R 4.1.1) #> lifecycle 1.0.1 2021-09-24 [1] CRAN (R 4.1.1) #> magick * 2.7.3 2021-08-18 [1] CRAN (R 4.1.1) #> magrittr 2.0.3 2022-03-30 [1] CRAN (R 4.1.1) #> pillar 1.7.0 2022-02-01 [1] CRAN (R 4.1.1) #> pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 4.1.0) #> purrr 0.3.4 2020-04-17 [1] CRAN (R 4.1.0) #> R.cache 0.15.0 2021-04-30 [1] CRAN (R 4.1.0) #> R.methodsS3 1.8.1 2020-08-26 [1] CRAN (R 4.1.0) #> R.oo 1.24.0 2020-08-26 [1] CRAN (R 4.1.0) #> R.utils 2.11.0 2021-09-26 [1] CRAN (R 4.1.1) #> Rcpp 1.0.8.3 2022-03-17 [1] CRAN (R 4.1.1) #> reprex 2.0.1 2021-08-05 [1] CRAN (R 4.1.1) #> rlang 1.0.2 2022-03-04 [1] CRAN (R 4.1.1) #> rmarkdown 2.13 2022-03-10 [1] CRAN (R 4.1.1) #> rstudioapi 0.13 2020-11-12 [1] CRAN (R 4.1.0) #> sessioninfo 1.2.2 2021-12-06 [1] CRAN (R 4.1.1) #> stringi 1.7.6 2021-11-29 [1] CRAN (R 4.1.1) #> stringr 1.4.0 2019-02-10 [1] CRAN (R 4.1.0) #> styler 1.7.0 2022-03-13 [1] CRAN (R 4.1.1) #> tibble 3.1.6 2021-11-07 [1] CRAN (R 4.1.1) #> utf8 1.2.2 2021-07-24 [1] CRAN (R 4.1.0) #> vctrs 0.4.1 2022-04-13 [1] CRAN (R 4.1.1) #> withr 2.5.0 2022-03-03 [1] CRAN (R 4.1.1) #> xfun 0.30 2022-03-02 [1] CRAN (R 4.1.1) #> yaml 2.3.5 2022-02-21 [1] CRAN (R 4.1.1) #> #> [1] /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/library #> #> ────────────────────────────────────────────────────────────────────────────── A: I opened an issue about this on the package GitHub because I was getting the same error. The package author suggested installing xQuartz, and that solved it for me.
R magick `image_annotate()` produces `NonconformingDrawingPrimitiveDefinition text` error
When trying to add text to an image with the image_annotate() function from the magick package in R on macOS, I now get an error complaining of NonconformingDrawingPrimitiveDefinition text. I have run brew install ghostscript and brew install imagemagick, both of which report the current versions are installed. What might be causing this error? library(magick) #> Linking to ImageMagick 6.9.12.3 #> Enabled features: cairo, fontconfig, freetype, heic, lcms, pango, raw, rsvg, webp #> Disabled features: fftw, ghostscript, x11 # Load a test image frink <- image_read("https://jeroen.github.io/images/frink.png") # Attempt to annotate with some text image_annotate(frink, "frink") #> Error in magick_image_annotate(image, text, gravity, location, degrees, : R: NonconformingDrawingPrimitiveDefinition `text' @ error/draw.c/RenderMVGContent/4405 # magick package configuration str(magick_config()) #> List of 24 #> $ version :Class 'numeric_version' hidden list of 1 #> ..$ : int [1:4] 6 9 12 3 #> $ modules : logi FALSE #> $ cairo : logi TRUE #> $ fontconfig : logi TRUE #> $ freetype : logi TRUE #> $ fftw : logi FALSE #> $ ghostscript : logi FALSE #> $ heic : logi TRUE #> $ jpeg : logi TRUE #> $ lcms : logi TRUE #> $ libopenjp2 : logi TRUE #> $ lzma : logi TRUE #> $ pangocairo : logi TRUE #> $ pango : logi TRUE #> $ png : logi TRUE #> $ raw : logi TRUE #> $ rsvg : logi TRUE #> $ tiff : logi TRUE #> $ webp : logi TRUE #> $ wmf : logi FALSE #> $ x11 : logi FALSE #> $ xml : logi TRUE #> $ zero-configuration: logi TRUE #> $ threads : int 1 Created on 2022-04-18 by the reprex package (v2.0.1) Session info sessioninfo::session_info() #> ─ Session info ─────────────────────────────────────────────────────────────── #> setting value #> version R version 4.1.2 (2021-11-01) #> os macOS Monterey 12.3 #> system aarch64, darwin20 #> ui X11 #> language (EN) #> collate en_GB.UTF-8 #> ctype en_GB.UTF-8 #> tz Europe/London #> date 2022-04-18 #> pandoc 2.14.0.3 @ /Applications/RStudio.app/Contents/MacOS/pandoc/ (via rmarkdown) #> #> ─ Packages ─────────────────────────────────────────────────────────────────── #> package * version date (UTC) lib source #> cli 3.2.0 2022-02-14 [1] CRAN (R 4.1.1) #> crayon 1.5.1 2022-03-26 [1] CRAN (R 4.1.1) #> curl 4.3.2 2021-06-23 [1] CRAN (R 4.1.0) #> digest 0.6.29 2021-12-01 [1] CRAN (R 4.1.1) #> ellipsis 0.3.2 2021-04-29 [1] CRAN (R 4.1.0) #> evaluate 0.15 2022-02-18 [1] CRAN (R 4.1.1) #> fansi 1.0.3 2022-03-24 [1] CRAN (R 4.1.1) #> fastmap 1.1.0 2021-01-25 [1] CRAN (R 4.1.0) #> fs 1.5.2 2021-12-08 [1] CRAN (R 4.1.1) #> glue 1.6.2 2022-02-24 [1] CRAN (R 4.1.1) #> highr 0.9 2021-04-16 [1] CRAN (R 4.1.0) #> htmltools 0.5.2 2021-08-25 [1] CRAN (R 4.1.1) #> knitr 1.38 2022-03-25 [1] CRAN (R 4.1.1) #> lifecycle 1.0.1 2021-09-24 [1] CRAN (R 4.1.1) #> magick * 2.7.3 2021-08-18 [1] CRAN (R 4.1.1) #> magrittr 2.0.3 2022-03-30 [1] CRAN (R 4.1.1) #> pillar 1.7.0 2022-02-01 [1] CRAN (R 4.1.1) #> pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 4.1.0) #> purrr 0.3.4 2020-04-17 [1] CRAN (R 4.1.0) #> R.cache 0.15.0 2021-04-30 [1] CRAN (R 4.1.0) #> R.methodsS3 1.8.1 2020-08-26 [1] CRAN (R 4.1.0) #> R.oo 1.24.0 2020-08-26 [1] CRAN (R 4.1.0) #> R.utils 2.11.0 2021-09-26 [1] CRAN (R 4.1.1) #> Rcpp 1.0.8.3 2022-03-17 [1] CRAN (R 4.1.1) #> reprex 2.0.1 2021-08-05 [1] CRAN (R 4.1.1) #> rlang 1.0.2 2022-03-04 [1] CRAN (R 4.1.1) #> rmarkdown 2.13 2022-03-10 [1] CRAN (R 4.1.1) #> rstudioapi 0.13 2020-11-12 [1] CRAN (R 4.1.0) #> sessioninfo 1.2.2 2021-12-06 [1] CRAN (R 4.1.1) #> stringi 1.7.6 2021-11-29 [1] CRAN (R 4.1.1) #> stringr 1.4.0 2019-02-10 [1] CRAN (R 4.1.0) #> styler 1.7.0 2022-03-13 [1] CRAN (R 4.1.1) #> tibble 3.1.6 2021-11-07 [1] CRAN (R 4.1.1) #> utf8 1.2.2 2021-07-24 [1] CRAN (R 4.1.0) #> vctrs 0.4.1 2022-04-13 [1] CRAN (R 4.1.1) #> withr 2.5.0 2022-03-03 [1] CRAN (R 4.1.1) #> xfun 0.30 2022-03-02 [1] CRAN (R 4.1.1) #> yaml 2.3.5 2022-02-21 [1] CRAN (R 4.1.1) #> #> [1] /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/library #> #> ──────────────────────────────────────────────────────────────────────────────
[ "I opened an issue about this on the package GitHub because I was getting the same error. The package author suggested installing xQuartz, and that solved it for me.\n" ]
[ 0 ]
[]
[]
[ "imagemagick", "macos", "r" ]
stackoverflow_0071917630_imagemagick_macos_r.txt
Q: image not appearing in SwiftUI Hello I am new in SwiftUI, I am working with the tag Image("my image"), my image is on the directory Assets.xcassets everything okay when I am editing but when I am testing with my cell or my simulator in my mac the image not appear and I don´t understand why my code is so simple , and if can tell me who show the complete screen beacuse if I am using some Text or TextField in my screen not appear all the screen and I dont know how move the screen to down. really thanyou for help me. I am Using iOS 13.4 whit a iPhone 7 var body: some View { VStack { ZStack{ Image("icon-logo") .resizable() .scaledToFit() .clipShape(Circle()) .overlay(Circle().stroke(Color(red: 39 / 255, green: 113 / 255, blue: 233 / 255), lineWidth: 5)) .shadow(radius: 20) } Text("Datos de Usuario") VStack{ Text("Nombre") .offset(x: -140, y: 0) TextField("--Nombre--", text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/) .offset(x: 20, y: 0) .padding(15) .background(Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255)) Text("Apellido") .offset(x: -140, y: 0) TextField("--Apellido--", text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/) .offset(x: 20, y: 0) .padding(15) .background(Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255)) } } struct TercerIUView_Previews: PreviewProvider { static var previews: some View { TercerIUView() } } A: It is not clear where do you use that code, but try to add rendering mode explicitly, Image("icon-logo") .renderingMode(.original) // << here !! .resizable() A: The reason why the image might not be showing is because the name is not matching the name of the asset in the catalog. I would suggest that you double check the name of the image in Assets.xcassets and make sure that is icon-logo This is how it should look: As for the second question, it looks like the keyboard is covering the textfields, the has been solved here: Move TextField up when the keyboard has appeared in SwiftUI A: I think is because my Iphone 7 in the symulator and physical is old for swiftUI, I was running the symulator with iphone 11 and the image appear very well is a shame for me only I have my old iphone 7 to run my apps A: Don't forget to insert images in the Assets of the App!
image not appearing in SwiftUI
Hello I am new in SwiftUI, I am working with the tag Image("my image"), my image is on the directory Assets.xcassets everything okay when I am editing but when I am testing with my cell or my simulator in my mac the image not appear and I don´t understand why my code is so simple , and if can tell me who show the complete screen beacuse if I am using some Text or TextField in my screen not appear all the screen and I dont know how move the screen to down. really thanyou for help me. I am Using iOS 13.4 whit a iPhone 7 var body: some View { VStack { ZStack{ Image("icon-logo") .resizable() .scaledToFit() .clipShape(Circle()) .overlay(Circle().stroke(Color(red: 39 / 255, green: 113 / 255, blue: 233 / 255), lineWidth: 5)) .shadow(radius: 20) } Text("Datos de Usuario") VStack{ Text("Nombre") .offset(x: -140, y: 0) TextField("--Nombre--", text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/) .offset(x: 20, y: 0) .padding(15) .background(Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255)) Text("Apellido") .offset(x: -140, y: 0) TextField("--Apellido--", text: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant("")/*@END_MENU_TOKEN@*/) .offset(x: 20, y: 0) .padding(15) .background(Color(red: 242 / 255, green: 242 / 255, blue: 242 / 255)) } } struct TercerIUView_Previews: PreviewProvider { static var previews: some View { TercerIUView() } }
[ "It is not clear where do you use that code, but try to add rendering mode explicitly,\nImage(\"icon-logo\")\n .renderingMode(.original) // << here !!\n .resizable()\n\n", "The reason why the image might not be showing is because the name is not matching the name of the asset in the catalog.\nI would suggest that you double check the name of the image in Assets.xcassets and make sure that is icon-logo\nThis is how it should look:\n\nAs for the second question, it looks like the keyboard is covering the textfields, the has been solved here: Move TextField up when the keyboard has appeared in SwiftUI\n", "I think is because my Iphone 7 in the symulator and physical is old for swiftUI, I was running the symulator with iphone 11 and the image appear very well is a shame for me only I have my old iphone 7 to run my apps\n", "Don't forget to insert images in the Assets of the App!\n" ]
[ 7, 0, 0, 0 ]
[]
[]
[ "image", "swiftui" ]
stackoverflow_0062524113_image_swiftui.txt
Q: International Phone picker in Angular 14 so i'm building a registration page with angular14 reactive forms and bootstrap for Css. the phone number input i want it to be a select dropdown with international phone codes and flags alongside the regular input. this is the basic input i want the phonedropdown stackblitz i have tried so many youtube videos of downloading a intl-tel-input.js and adding its css and js and doing -("allowJs" : true,"checkjs": false) on the tsconfig file. everything was in vain. i can't find a propper way to do it A: I would suggest to use the npm-library ngx-intl-tel-input instead: https://www.npmjs.com/package/ngx-intl-tel-input The library is compatible with Angular 14, although its npm page still says "Angular 13" (I checked the library's package.json on Github and it refers to the Angular 14 packages).
International Phone picker in Angular 14
so i'm building a registration page with angular14 reactive forms and bootstrap for Css. the phone number input i want it to be a select dropdown with international phone codes and flags alongside the regular input. this is the basic input i want the phonedropdown stackblitz i have tried so many youtube videos of downloading a intl-tel-input.js and adding its css and js and doing -("allowJs" : true,"checkjs": false) on the tsconfig file. everything was in vain. i can't find a propper way to do it
[ "I would suggest to use the npm-library ngx-intl-tel-input instead:\nhttps://www.npmjs.com/package/ngx-intl-tel-input\nThe library is compatible with Angular 14, although its npm page still says \"Angular 13\" (I checked the library's package.json on Github and it refers to the Angular 14 packages).\n" ]
[ 0 ]
[]
[]
[ "angular", "bootstrap_5" ]
stackoverflow_0074665223_angular_bootstrap_5.txt
Q: How do I send text from TextView to 'Export to PDF'? I'm new to GTK4, an open source toolkit for C++ binding. I want to send text from current TextView buffer (from a saved file) to a PDF file using GTK libraries (gtkmm4), but couldn't get anything printed out. This is the code I have started from reading the documentation: void MainWindow:export_note() { auto op = Gtk::PrintOperation::create(); // setup op cout << save_file_path << endl; string content = editor.get_buffer()->get_text(); ofstream out(work_dir + save_file_path); out << content; out.close(); curr_state = edit_file; op->set_export_filename("test.pdf"); auto res = op->run(Gtk::PrintOperation::Action::EXPORT); return; } This only exports to a blank PDF, but I'm expecting text to show up on PDF. A: It looks like you are not using any binary application to attempt conversion from text to text/pdf or more commonly binary application/pdf. You cannot simply stuff text data into a container called Test.pdf There are simple means to convert Text to PDF, traditionally by using PostScript Printer files, but more commonly recently using a PDF printer driver direct so start at the most basic level Hello World needs a file something like this, where the body is built up from stacked vectors or font labelled strings at X&Y co-ordinates. Test.pdf %PDF-1.1 %âãÏÓ 1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids [3 0 R]/Count 1/MediaBox [0 0 594 792]>>endobj 3 0 obj<</Type/Page/Parent 2 0 R/Resources<</Font<</F1<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>>>>>/Contents 4 0 R>>endobj 4 0 obj<</Length 81 >> stream BT /F1 18 Tf 036 740 Td (Hello) Tj ET BT /F1 18 Tf 036 720 Td (World!) Tj ET endstream endobj xref 0 5 0000000000 65535 f 0000000019 00000 n 0000000063 00000 n 0000000137 00000 n 0000000267 00000 n trailer<</Root 1 0 R /Size 5>>startxref 399 %%EOF
How do I send text from TextView to 'Export to PDF'?
I'm new to GTK4, an open source toolkit for C++ binding. I want to send text from current TextView buffer (from a saved file) to a PDF file using GTK libraries (gtkmm4), but couldn't get anything printed out. This is the code I have started from reading the documentation: void MainWindow:export_note() { auto op = Gtk::PrintOperation::create(); // setup op cout << save_file_path << endl; string content = editor.get_buffer()->get_text(); ofstream out(work_dir + save_file_path); out << content; out.close(); curr_state = edit_file; op->set_export_filename("test.pdf"); auto res = op->run(Gtk::PrintOperation::Action::EXPORT); return; } This only exports to a blank PDF, but I'm expecting text to show up on PDF.
[ "It looks like you are not using any binary application to attempt conversion from text to text/pdf or more commonly binary application/pdf. You cannot simply stuff text data into a container called Test.pdf\nThere are simple means to convert Text to PDF, traditionally by using PostScript Printer files, but more commonly recently using a PDF printer driver direct\nso start at the most basic level Hello World needs a file something like this, where the body is built up from stacked vectors or font labelled strings at X&Y co-ordinates.\nTest.pdf\n%PDF-1.1\n%âãÏÓ\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids [3 0 R]/Count 1/MediaBox [0 0 594 792]>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/Resources<</Font<</F1<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>>>>>/Contents 4 0 R>>endobj\n4 0 obj<</Length 81\n>>\nstream\n\nBT /F1 18 Tf 036 740 Td (Hello) Tj ET\nBT /F1 18 Tf 036 720 Td (World!) Tj ET\n\nendstream \nendobj xref\n0 5 \n0000000000 65535 f\n0000000019 00000 n\n0000000063 00000 n\n0000000137 00000 n\n0000000267 00000 n\ntrailer<</Root 1 0 R /Size 5>>startxref\n399 %%EOF\n\n\n" ]
[ 0 ]
[]
[]
[ "c++", "gtk", "gtkmm4", "user_interface" ]
stackoverflow_0074670515_c++_gtk_gtkmm4_user_interface.txt
Q: Question regarding general Spring Boot application architecture There are two external APIs that I have to consume in my app, parse the data and serve it to front-end. The APIs have different response and request objects and one handles XML and the other one handles JSON and front-end has the possibility to see the data coming from both external APIs. My question is what would be the best approach to do build this app? How should I structure the code, bearing in mind that another APIs could be added in the future, so I would like to make it modular as possible, but I'm not sure how to achieve this. Should I go for microservices architecture, where I have the main app and it communicates through Feign, where API1 is one service with the models and services etc and API2 is the other microservice and front end is hitting those microservices separately? Or should I have one monolith where I have both API1 and API2 service layers, controllers, models etc and front end is hitting the monolith where the business logic determines which API service/model/controller to use? So something like this.. ** API1 Microservice/** API1 model API1 service .. ** API2 Microservice/** API2 model API2 service .. **Monolith**: Services/ (Feign implementations, other business logic etc) API1 service API2 service Model/ API1request API1response API2request API2response Controller/ API1controller API2 controller I'm able to actually build the app and write the code but would love some input as to how I should organise the actual app and possible make it as modular as possible. Thanks. A: One approach you could take is to use a microservices architecture, where each API is its own microservice. This would allow you to develop and deploy each API independently, and make it easier to add new APIs in the future. In this architecture, your main app would communicate with the API microservices using a client library like Feign. Each microservice would have its own models, services, and controllers for handling requests and responses. Alternatively, you could use a monolithic architecture, where all of the API logic is contained within a single application. In this case, you would have one set of services, models, and controllers that handle requests and responses for both APIs. The business logic would determine which API to use based on the request received. Both of these approaches have their own pros and cons, and the best option for your application will depend on your specific requirements and goals. It's always a good idea to carefully consider your options and choose the architecture that will best support the needs of your app and your team.
Question regarding general Spring Boot application architecture
There are two external APIs that I have to consume in my app, parse the data and serve it to front-end. The APIs have different response and request objects and one handles XML and the other one handles JSON and front-end has the possibility to see the data coming from both external APIs. My question is what would be the best approach to do build this app? How should I structure the code, bearing in mind that another APIs could be added in the future, so I would like to make it modular as possible, but I'm not sure how to achieve this. Should I go for microservices architecture, where I have the main app and it communicates through Feign, where API1 is one service with the models and services etc and API2 is the other microservice and front end is hitting those microservices separately? Or should I have one monolith where I have both API1 and API2 service layers, controllers, models etc and front end is hitting the monolith where the business logic determines which API service/model/controller to use? So something like this.. ** API1 Microservice/** API1 model API1 service .. ** API2 Microservice/** API2 model API2 service .. **Monolith**: Services/ (Feign implementations, other business logic etc) API1 service API2 service Model/ API1request API1response API2request API2response Controller/ API1controller API2 controller I'm able to actually build the app and write the code but would love some input as to how I should organise the actual app and possible make it as modular as possible. Thanks.
[ "One approach you could take is to use a microservices architecture, where each API is its own microservice. This would allow you to develop and deploy each API independently, and make it easier to add new APIs in the future.\nIn this architecture, your main app would communicate with the API microservices using a client library like Feign. Each microservice would have its own models, services, and controllers for handling requests and responses.\nAlternatively, you could use a monolithic architecture, where all of the API logic is contained within a single application. In this case, you would have one set of services, models, and controllers that handle requests and responses for both APIs. The business logic would determine which API to use based on the request received.\nBoth of these approaches have their own pros and cons, and the best option for your application will depend on your specific requirements and goals. It's always a good idea to carefully consider your options and choose the architecture that will best support the needs of your app and your team.\n" ]
[ 0 ]
[]
[]
[ "architecture", "design_patterns", "java", "microservices", "spring" ]
stackoverflow_0074671386_architecture_design_patterns_java_microservices_spring.txt
Q: How can I catch all errors from a create.sql just like SQLite gives? I have a create.sql (and a populate.sql) that create a SQLite3 database (and populate it with some dummy data). I then save the resulting database and make some further analysis. I use Python to automate this process for several pairs of sql files. db_mem = sqlite3.connect(":memory:") cur = db_mem.cursor() try: with open(row['path']+'/' + 'create.sql') as fp: cur.executescript(fp.read()) except: creates.append('C-error') continue else: creates.append('Ok') try: with open(row['path']+'/' + 'populate.sql') as fp: cur.executescript(fp.read()) except sqlite3.Error as x: populates.append('P-error') else: populates.append('Ok') db_disk = sqlite3.connect(f'./SQL_Final/{index}_out.db') db_mem.backup(db_disk) However, i can only catch 1 error at creation, instead of several errors that are outputed when I do .read create.sql from sqlite. My question is how can I catch all errors? For reproducibility issues, here is a dummy create.sql (that generates errors): DROP TABLE IF EXISTS Comp; CREATE TABLE Comp ( idComp INTEGER PRIMARY KEY, nomeComp TEXT, dataInicio TEXT, dataFim TEXT ); DROP TABLE IF EXISTS Game; DROP TABLE IF EXISTS Stade; DROP TABLE IF EXISTS Club; DROP TABLE IF EXISTS Squad; CREATE TABLE Game ( idGame INTEGER PRIMARY KEY, golosFora INTEGER, golosCasa INTEGER, data DATE, jornada INTEGER, duração TIME, nomeComp TEXT REFERENCES Comp, nomeStade TEXT REFERENCES Stade, nomeSquadFora TEXT REFERENCES Squad, nomeSquadCasa TEXT REFERENCES Squad, CONSTRAINT CHECK_Game_golosFora CHECK (Game_golosFora >= 0), CONSTRAINT CHECK_Game_golosCasa CHECK (Game_golosCasa >= 0), CONSTRAINT CHECK_Game_jornada CHECK (jornada > 0) ); CREATE TABLE Stade ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); CREATE TABLE Club ( nomeClub TEXT PRIMARY KEY, país TEXT NOT NULL ); CREATE TABLE Squad ( nomeSquad TEXT PRIMARY Key, nomeClub TEXT REFERENCES Club ); If I read this file from SQLIte (with .read create.sql) I get the following errors: Error: near line 2: in prepare, table "Comp" has more than one primary key (1) Error: near line 13: in prepare, no such column: Game_golosFora (1) However, if I automate from Python, I get only a single error: Error: table "Comp" has more than one primary key Is there any way I can fix this? A: The executescript() will run the whole sql file but will raise exception when an error occurs. Since you want to continue the DB schema creation regardless of errors, you could switch from using executescript() to looping over the sql statements list by calling the execute() on each of them. This example will demonstrate that the processing continues when an error occurs. We will try to create a table that already exists to simulate sqlite error. create.sql: CREATE TABLE Stade ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); CREATE TABLE Stade ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); CREATE TABLE Stade2 ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); CREATE TABLE Stade2 ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); CREATE TABLE Stade3 ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); python: import traceback import sqlite3 db_mem = sqlite3.connect(":memory:") cur = db_mem.cursor() all_errors = [] try: with open('create.sql', 'r') as fp: text = fp.read().split(';') for sql in text: try: cur.execute(sql) except: # print("exception at sql: {}, details: {}".format(sql, traceback.format_exc())) all_errors.append(traceback.format_exc()) except: print("exception, details: {}".format(traceback.format_exc())) else: db_disk = sqlite3.connect('db.sqlite') db_mem.backup(db_disk) for i, error in enumerate(all_errors): print("Error #{}: {}".format(i, error) running it, we can see 2 error messages, and inspecting the db.sqlite we can see the 3rd table as well, i.e. the processing reached the last sql.
How can I catch all errors from a create.sql just like SQLite gives?
I have a create.sql (and a populate.sql) that create a SQLite3 database (and populate it with some dummy data). I then save the resulting database and make some further analysis. I use Python to automate this process for several pairs of sql files. db_mem = sqlite3.connect(":memory:") cur = db_mem.cursor() try: with open(row['path']+'/' + 'create.sql') as fp: cur.executescript(fp.read()) except: creates.append('C-error') continue else: creates.append('Ok') try: with open(row['path']+'/' + 'populate.sql') as fp: cur.executescript(fp.read()) except sqlite3.Error as x: populates.append('P-error') else: populates.append('Ok') db_disk = sqlite3.connect(f'./SQL_Final/{index}_out.db') db_mem.backup(db_disk) However, i can only catch 1 error at creation, instead of several errors that are outputed when I do .read create.sql from sqlite. My question is how can I catch all errors? For reproducibility issues, here is a dummy create.sql (that generates errors): DROP TABLE IF EXISTS Comp; CREATE TABLE Comp ( idComp INTEGER PRIMARY KEY, nomeComp TEXT, dataInicio TEXT, dataFim TEXT ); DROP TABLE IF EXISTS Game; DROP TABLE IF EXISTS Stade; DROP TABLE IF EXISTS Club; DROP TABLE IF EXISTS Squad; CREATE TABLE Game ( idGame INTEGER PRIMARY KEY, golosFora INTEGER, golosCasa INTEGER, data DATE, jornada INTEGER, duração TIME, nomeComp TEXT REFERENCES Comp, nomeStade TEXT REFERENCES Stade, nomeSquadFora TEXT REFERENCES Squad, nomeSquadCasa TEXT REFERENCES Squad, CONSTRAINT CHECK_Game_golosFora CHECK (Game_golosFora >= 0), CONSTRAINT CHECK_Game_golosCasa CHECK (Game_golosCasa >= 0), CONSTRAINT CHECK_Game_jornada CHECK (jornada > 0) ); CREATE TABLE Stade ( nomeStade TEXT PRIMARY KEY, local TEXT NOT NULL, idGame INTEGER REFERENCES Game ); CREATE TABLE Club ( nomeClub TEXT PRIMARY KEY, país TEXT NOT NULL ); CREATE TABLE Squad ( nomeSquad TEXT PRIMARY Key, nomeClub TEXT REFERENCES Club ); If I read this file from SQLIte (with .read create.sql) I get the following errors: Error: near line 2: in prepare, table "Comp" has more than one primary key (1) Error: near line 13: in prepare, no such column: Game_golosFora (1) However, if I automate from Python, I get only a single error: Error: table "Comp" has more than one primary key Is there any way I can fix this?
[ "The executescript() will run the whole sql file but will raise exception when an error occurs.\nSince you want to continue the DB schema creation regardless of errors, you could switch from using executescript() to looping over the sql statements list by calling the execute() on each of them.\nThis example will demonstrate that the processing continues when an error occurs. We will try to create a table that already exists to simulate sqlite error.\ncreate.sql:\nCREATE TABLE Stade (\n nomeStade TEXT PRIMARY KEY,\n local TEXT NOT NULL,\n idGame INTEGER REFERENCES Game\n);\n\nCREATE TABLE Stade (\n nomeStade TEXT PRIMARY KEY,\n local TEXT NOT NULL,\n idGame INTEGER REFERENCES Game\n);\n\nCREATE TABLE Stade2 (\n nomeStade TEXT PRIMARY KEY,\n local TEXT NOT NULL,\n idGame INTEGER REFERENCES Game\n);\n\nCREATE TABLE Stade2 (\n nomeStade TEXT PRIMARY KEY,\n local TEXT NOT NULL,\n idGame INTEGER REFERENCES Game\n);\n\nCREATE TABLE Stade3 (\n nomeStade TEXT PRIMARY KEY,\n local TEXT NOT NULL,\n idGame INTEGER REFERENCES Game\n);\n\npython:\nimport traceback\nimport sqlite3\ndb_mem = sqlite3.connect(\":memory:\")\ncur = db_mem.cursor()\nall_errors = []\ntry:\n with open('create.sql', 'r') as fp:\n text = fp.read().split(';')\n for sql in text:\n try:\n cur.execute(sql)\n except:\n # print(\"exception at sql: {}, details: {}\".format(sql, traceback.format_exc()))\n all_errors.append(traceback.format_exc())\nexcept:\n print(\"exception, details: {}\".format(traceback.format_exc()))\n \nelse:\n db_disk = sqlite3.connect('db.sqlite')\n db_mem.backup(db_disk)\n\nfor i, error in enumerate(all_errors):\n print(\"Error #{}: {}\".format(i, error)\n\nrunning it, we can see 2 error messages, and inspecting the db.sqlite we can see the 3rd table as well, i.e. the processing reached the last sql.\n" ]
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074671110_python_sqlite.txt
Q: Can Content Negotiation values be sent out of order? I'm determining a user's language/locale from the Accept-Language header, and was wondering if they could ever be passed out of order. I've written a php sort function to make sure they are in descending order, but if it's unnecessary, I'd like to remove it. Example of proper order: Accept-Language: fr-ca, fr; q=0.8, en-ca; q=0.6, en-us; q=0.4, en; q=0.2 Example of improper order: Accept-Language: fr-ca, en; q=0.2, en-ca; q=0.6, en-us; q=0.4, fr; q=0.8 A: Yes, content negotiation values can be sent out of order. HTTP/1.1 Specification doesn't define anything about ordering of values in Accept-* headers. So the order doesn't have any meaning for client's preference. A: The sections about Accept-Language in RFC 2068 (from 1997) and RFC 2616 (from 1999) both said nothing whatsoever about the order in which languages should be listed. The more recent RFC 7231 (from 2014) had a paragraph of commentary on the matter, and that same paragraph is preserved in the even more recent RFC 9110 (from 2022). Section 12.5.4. Accept-Language says: Note that some recipients treat the order in which language tags are listed as an indication of descending priority, particularly for tags that are assigned equal quality values (no value is the same as q=1). However, this behavior cannot be relied upon. For consistency and to maximize interoperability, many user agents assign each language tag a unique quality value while also listing them in order of decreasing quality. Additional discussion of language priority lists can be found in Section 2.3 of [RFC4647]. Some of the qualifiers included here (note: "particularly for tags that are assigned equal quality" and "many user agents") are eyebrow-raising. Their inclusion heavily implies that the 2014 authors were aware of servers that assumed languages were listed in descending order of priority regardless of priority values, and also of clients that did not send languages in descending order of priority. That seems unfortunate, since those two behaviours are of course not compatible with each other! The RFC makes no comment on how clients should order these lists, perhaps not wanting to dictate how clients behave on the basis of a few aberrant servers. But what servers should do is very clear: you should sort the languages received by their priority values, and not rely on the client having sent them to you in descending order, because the spec does not require them to do so.
Can Content Negotiation values be sent out of order?
I'm determining a user's language/locale from the Accept-Language header, and was wondering if they could ever be passed out of order. I've written a php sort function to make sure they are in descending order, but if it's unnecessary, I'd like to remove it. Example of proper order: Accept-Language: fr-ca, fr; q=0.8, en-ca; q=0.6, en-us; q=0.4, en; q=0.2 Example of improper order: Accept-Language: fr-ca, en; q=0.2, en-ca; q=0.6, en-us; q=0.4, fr; q=0.8
[ "Yes, content negotiation values can be sent out of order.\nHTTP/1.1 Specification doesn't define anything about ordering of values in Accept-* headers. So the order doesn't have any meaning for client's preference.\n", "The sections about Accept-Language in RFC 2068 (from 1997) and RFC 2616 (from 1999) both said nothing whatsoever about the order in which languages should be listed.\nThe more recent RFC 7231 (from 2014) had a paragraph of commentary on the matter, and that same paragraph is preserved in the even more recent RFC 9110 (from 2022). Section 12.5.4. Accept-Language says:\n\nNote that some recipients treat the order in which language tags are listed as an indication of descending priority, particularly for tags that are assigned equal quality values (no value is the same as q=1). However, this behavior cannot be relied upon. For consistency and to maximize interoperability, many user agents assign each language tag a unique quality value while also listing them in order of decreasing quality. Additional discussion of language priority lists can be found in Section 2.3 of [RFC4647].\n\nSome of the qualifiers included here (note: \"particularly for tags that are assigned equal quality\" and \"many user agents\") are eyebrow-raising. Their inclusion heavily implies that the 2014 authors were aware of servers that assumed languages were listed in descending order of priority regardless of priority values, and also of clients that did not send languages in descending order of priority. That seems unfortunate, since those two behaviours are of course not compatible with each other!\nThe RFC makes no comment on how clients should order these lists, perhaps not wanting to dictate how clients behave on the basis of a few aberrant servers. But what servers should do is very clear: you should sort the languages received by their priority values, and not rely on the client having sent them to you in descending order, because the spec does not require them to do so.\n" ]
[ 0, 0 ]
[]
[]
[ "content_negotiation", "http_accept_language", "http_headers", "php" ]
stackoverflow_0021026522_content_negotiation_http_accept_language_http_headers_php.txt
Q: Is there an attribute in C++ to throw a fatal compiler error upon ignored return type? I am looking for a harsher version of [[nodiscard]] that throws an fatal error instead of a warning when a return value is ignored. So for example: [[harshnodiscard]] int getSize() { return 0; } Any code that ignores the return value of getSize should not compile. Is there any functionality for this?
Is there an attribute in C++ to throw a fatal compiler error upon ignored return type?
I am looking for a harsher version of [[nodiscard]] that throws an fatal error instead of a warning when a return value is ignored. So for example: [[harshnodiscard]] int getSize() { return 0; } Any code that ignores the return value of getSize should not compile. Is there any functionality for this?
[]
[]
[ "Yes, there is a feature in C++17 called [[nodiscard(\"message\")]] that allows you to specify an error message that will be thrown when a return value is ignored. Here is an example:\n [[nodiscard(\"Error: return value must not be ignored\")]]\nint foo() {\n // Some code here\n return 5;\n}\n\nIn this code, if the return value of the foo function is ignored, the compiler will throw an error with the message \"Error: return value must not be ignored\".\n", "There is no built-in attribute in C++ to throw a fatal compiler error when a return value is ignored. However, you could potentially achieve this by using a combination of the [[nodiscard]] attribute and a static_assert statement.\nFor example:\n[[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() was ignored\");\nreturn 0;\n}\n\nThis will cause the compiler to throw an error when the return value of getSize() is ignored. You could also add a custom error message to the static_assert statement to make the error more informative.\nFor example:\n[[nodiscard]] int getSize() {\nstatic_assert(false, \"return value of getSize() must not be ignored\");\nreturn 0;\n}\n\nThis will cause the compiler to throw an error with the message \"return value of getSize() must not be ignored\" when the return value of getSize() is ignored. Note that this approach will not work if the return value is ignored in a conditional statement that is never executed.\nFor example:\nif (false) {\ngetSize(); // return value will be ignored, but no error will be thrown\n}\n\nIn this case, the static_assert statement will not be executed because the if statement is never executed, so no error will be thrown.\n" ]
[ -1, -3 ]
[ "attributes", "c++" ]
stackoverflow_0074671307_attributes_c++.txt
Q: Choosing random value from list based on it's percentage that keeps changing so I am working on a project where I need to guess the historical period an author is in. The authors are selected randomly. I was thinking of making a dictionary which would contain all the historical periods, and then put a list with values as the key. I want to do it so everytime I get him right, a counter for that author will go up. After that, he should be less likely to be picked. Example: dictionary- periodOne: List(Author1, Author2), periodTwo: List(Author3, Author4) Author1 gets picked. I guess correctly. The author will have a number assigned to him somehow and this number will be increased by one now. Next author is being picked. Author1 was already picked so he has smaller chance of being picked, however he can still be picked. I was thinking of making maybe dictionary with the number values and then putting this dictionary into it as the value (Don't know if that is even possible) Any ideas on how to do this effectively? A: This is a logic question, so I'll show you the logic. We're assuming you create a Map with the author name (or author index) as the key and a count as the value. Each time the author is selected, the count goes up by 1. You need to keep or calculate two values. The total count for all authors plus the total number of authors and the largest count for any author. The total count is used to get a random integer between 0 and (total count - 1). You would use the Random class to get this int. Now, you iterate through the Map, using the Iterator class. For each author, you calculate the selection value. selection value = maximum count - author count + 1; Next, you sum the selection value. Next, you compare the summed selection value with your random number. As soon as the summed selection value is greater than the random number, you back up one author. That author is the randomly selected author. The higher an author count gets, the less likely that author will be selected. But, it's still possible. Since it's random, the same author can be selected twice or more times in a row. Not likely, but possible.
Choosing random value from list based on it's percentage that keeps changing
so I am working on a project where I need to guess the historical period an author is in. The authors are selected randomly. I was thinking of making a dictionary which would contain all the historical periods, and then put a list with values as the key. I want to do it so everytime I get him right, a counter for that author will go up. After that, he should be less likely to be picked. Example: dictionary- periodOne: List(Author1, Author2), periodTwo: List(Author3, Author4) Author1 gets picked. I guess correctly. The author will have a number assigned to him somehow and this number will be increased by one now. Next author is being picked. Author1 was already picked so he has smaller chance of being picked, however he can still be picked. I was thinking of making maybe dictionary with the number values and then putting this dictionary into it as the value (Don't know if that is even possible) Any ideas on how to do this effectively?
[ "This is a logic question, so I'll show you the logic.\nWe're assuming you create a Map with the author name (or author index) as the key and a count as the value. Each time the author is selected, the count goes up by 1.\nYou need to keep or calculate two values. The total count for all authors plus the total number of authors and the largest count for any author.\nThe total count is used to get a random integer between 0 and (total count - 1). You would use the Random class to get this int.\nNow, you iterate through the Map, using the Iterator class. For each author, you calculate the selection value.\nselection value = maximum count - author count + 1;\n\nNext, you sum the selection value.\nNext, you compare the summed selection value with your random number. As soon as the summed selection value is greater than the random number, you back up one author. That author is the randomly selected author.\nThe higher an author count gets, the less likely that author will be selected. But, it's still possible. Since it's random, the same author can be selected twice or more times in a row. Not likely, but possible.\n" ]
[ 0 ]
[]
[]
[ "dictionary", "java" ]
stackoverflow_0074671207_dictionary_java.txt
Q: Facing Import Error when importing esda and libpysal libraries Even though I have installed both the libraries several times using different orders in different virtual environments, I'm still facing an issue where I'm not able to import and use certain geospatial libraries like esda and libpysal. The following error shows up: ImportError Traceback (most recent call last) C:\Users\SLAADM~1\AppData\Local\Temp/ipykernel_35328/2667884714.py in <module> 3 import numpy as np 4 import matplotlib.pyplot as plt ----> 5 import esda 6 import libpysal as lps 7 import pysal c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\esda\__init__.py in <module> 5 6 """ ----> 7 from . import adbscan 8 from .gamma import Gamma 9 from .geary import Geary c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\esda\adbscan.py in <module> 8 import pandas 9 import numpy as np ---> 10 from libpysal.cg.alpha_shapes import alpha_shape_auto 11 from scipy.spatial import cKDTree 12 from collections import Counter c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\libpysal\__init__.py in <module> 25 Tools for creating and manipulating weights 26 """ ---> 27 from . import cg 28 from . import io 29 from . import weights c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\libpysal\cg\__init__.py in <module> 9 from .sphere import * 10 from .voronoi import * ---> 11 from .alpha_shapes import * c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\libpysal\cg\alpha_shapes.py in <module> 22 23 try: ---> 24 import pygeos 25 26 HAS_PYGEOS = True c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\pygeos\__init__.py in <module> ----> 1 from .lib import GEOSException # NOQA 2 from .lib import Geometry # NOQA 3 from .lib import geos_version, geos_version_string # NOQA 4 from .lib import geos_capi_version, geos_capi_version_string # NOQA 5 from .decorators import UnsupportedGEOSOperation # NOQA ImportError: DLL load failed while importing lib: The specified procedure could not be found. Would really appreciate any help in making this work. Please throw any suggestions you might have at me. A: install pygeos i.e conda install pygeos it worked for me A: I found same issue when running example code from a couple of years ago. The pysal API has changed. Import libpysal first then import the esda libraries eg import libpysal from esda.moran import Moran from esda.smaup import Smaup see https://pysal.org/esda/generated/esda.Moran.html
Facing Import Error when importing esda and libpysal libraries
Even though I have installed both the libraries several times using different orders in different virtual environments, I'm still facing an issue where I'm not able to import and use certain geospatial libraries like esda and libpysal. The following error shows up: ImportError Traceback (most recent call last) C:\Users\SLAADM~1\AppData\Local\Temp/ipykernel_35328/2667884714.py in <module> 3 import numpy as np 4 import matplotlib.pyplot as plt ----> 5 import esda 6 import libpysal as lps 7 import pysal c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\esda\__init__.py in <module> 5 6 """ ----> 7 from . import adbscan 8 from .gamma import Gamma 9 from .geary import Geary c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\esda\adbscan.py in <module> 8 import pandas 9 import numpy as np ---> 10 from libpysal.cg.alpha_shapes import alpha_shape_auto 11 from scipy.spatial import cKDTree 12 from collections import Counter c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\libpysal\__init__.py in <module> 25 Tools for creating and manipulating weights 26 """ ---> 27 from . import cg 28 from . import io 29 from . import weights c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\libpysal\cg\__init__.py in <module> 9 from .sphere import * 10 from .voronoi import * ---> 11 from .alpha_shapes import * c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\libpysal\cg\alpha_shapes.py in <module> 22 23 try: ---> 24 import pygeos 25 26 HAS_PYGEOS = True c:\users\sla admin\appdata\local\programs\python\python39\lib\site-packages\pygeos\__init__.py in <module> ----> 1 from .lib import GEOSException # NOQA 2 from .lib import Geometry # NOQA 3 from .lib import geos_version, geos_version_string # NOQA 4 from .lib import geos_capi_version, geos_capi_version_string # NOQA 5 from .decorators import UnsupportedGEOSOperation # NOQA ImportError: DLL load failed while importing lib: The specified procedure could not be found. Would really appreciate any help in making this work. Please throw any suggestions you might have at me.
[ "install pygeos i.e conda install pygeos\nit worked for me\n", "I found same issue when running example code from a couple of years ago. The pysal API has changed.\nImport libpysal first then import the esda libraries eg\nimport libpysal\nfrom esda.moran import Moran\nfrom esda.smaup import Smaup\n\nsee\nhttps://pysal.org/esda/generated/esda.Moran.html\n" ]
[ 0, 0 ]
[]
[]
[ "geospatial", "gis", "import", "jupyter_notebook", "python" ]
stackoverflow_0068841646_geospatial_gis_import_jupyter_notebook_python.txt
Q: OpenGL instancing displays strange shapes I'm making a simple game in OpenGL where there is one player and multiple bubbles, all being spheres. Unfortunately, instancing doesn't work as expected and causes some strange effects. I'm new to instancing and can't see what may be causing a problem. Draw method in player class: void Player::draw(glm::mat4 ViewMat, GLfloat aspect, glm::vec3 light, GLfloat zoom) { bindProgram(); bindBuffers(); glm::mat4 Projection = glm::perspective(zoom, aspect, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); glm::mat4 MVP = Projection * ViewMat * Model; glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "MVP"), 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "M"), 1, GL_FALSE, &Model[0][0]); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "V"), 1, GL_FALSE, &ViewMat[0][0]); glUniform3f(glGetUniformLocation(shaderProgram, "origin"), origin.x, origin.y, origin.z); glUniform3f(glGetUniformLocation(shaderProgram, "lightPosWorld"), light.x, light.y, light.z); glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size() / 3); } Static draw method in bubble class: void Bubble::drawAll(glm::mat4 ViewMat, GLfloat aspect, glm::vec3 light, GLfloat zoom, std::vector<Bubble *> allInstances) { std::vector<float> origins; uint count = 0; for (auto b : allInstances) { origins.push_back(b->origin.x); origins.push_back(b->origin.y); origins.push_back(b->origin.z); count++; } allInstances[0]->bindProgram(); allInstances[0]->bindBuffers(); glBufferData(GL_ARRAY_BUFFER, origins.size() * sizeof(origins), origins.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, originsBuffer); glVertexAttribPointer(1, // attribute. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *)0 // array buffer offset ); glm::mat4 Projection = glm::perspective(zoom, aspect, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); glm::mat4 MVP = Projection * ViewMat * Model; GLuint programID = allInstances[0]->shaderProgram; glVertexAttribDivisor(0, 0); glVertexAttribDivisor(1, 1); glUniformMatrix4fv(glGetUniformLocation(programID, "MVP"), 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(glGetUniformLocation(programID, "M"), 1, GL_FALSE, &Model[0][0]); glUniformMatrix4fv(glGetUniformLocation(programID, "V"), 1, GL_FALSE, &ViewMat[0][0]); glUniform3f(glGetUniformLocation(programID, "lightPosWorld"), light.x, light.y, light.z); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, allInstances[0]->vertices.size() / 3, count); } Player vertex shader: #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; uniform mat4 MVP; uniform mat4 M; uniform mat4 V; uniform vec3 origin; uniform vec3 lightPosWorld; uniform vec3 cameraPos; out vec3 vertexPosWorld; out vec3 vertexNormal; out vec3 eyeDirectionCamera; out vec3 lightDirectionCamera; void main() { gl_Position = MVP * vec4(vertexPosition_modelspace + origin,1); vertexPosWorld = (M * vec4(vertexPosition_modelspace + origin,1)).xyz; vertexNormal = normalize(vertexPosWorld - origin); } Bubble vertex shader: #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; layout(location = 1) in vec3 origin; uniform mat4 MVP; uniform mat4 M; uniform mat4 V; uniform vec3 lightPosWorld; uniform vec3 cameraPos; out vec3 vertexPosWorld; out vec3 vertexNormal; out vec3 eyeDirectionCamera; out vec3 lightDirectionCamera; void main() { gl_Position = MVP * vec4(vertexPosition_modelspace + origin,1); vertexPosWorld = (M * vec4(vertexPosition_modelspace + origin,1)).xyz; vertexNormal = normalize(vertexPosWorld - origin); } This is what I get: Effect But I wanted to get two bubbles that look exactly like the player (which draws correctly). A: There are 2 issues in the code: sizeof(origins) is a byte size of std::vector but not its underlying type. It should be sizeof(float). glBindBuffer should be called before modifying the buffer’s data and properties. It should help: glBindBuffer(GL_ARRAY_BUFFER, originsBuffer); glBufferData(GL_ARRAY_BUFFER, origins.size() * sizeof(float), origins.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, // attribute. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *)0 // array buffer offset );
OpenGL instancing displays strange shapes
I'm making a simple game in OpenGL where there is one player and multiple bubbles, all being spheres. Unfortunately, instancing doesn't work as expected and causes some strange effects. I'm new to instancing and can't see what may be causing a problem. Draw method in player class: void Player::draw(glm::mat4 ViewMat, GLfloat aspect, glm::vec3 light, GLfloat zoom) { bindProgram(); bindBuffers(); glm::mat4 Projection = glm::perspective(zoom, aspect, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); glm::mat4 MVP = Projection * ViewMat * Model; glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "MVP"), 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "M"), 1, GL_FALSE, &Model[0][0]); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "V"), 1, GL_FALSE, &ViewMat[0][0]); glUniform3f(glGetUniformLocation(shaderProgram, "origin"), origin.x, origin.y, origin.z); glUniform3f(glGetUniformLocation(shaderProgram, "lightPosWorld"), light.x, light.y, light.z); glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.size() / 3); } Static draw method in bubble class: void Bubble::drawAll(glm::mat4 ViewMat, GLfloat aspect, glm::vec3 light, GLfloat zoom, std::vector<Bubble *> allInstances) { std::vector<float> origins; uint count = 0; for (auto b : allInstances) { origins.push_back(b->origin.x); origins.push_back(b->origin.y); origins.push_back(b->origin.z); count++; } allInstances[0]->bindProgram(); allInstances[0]->bindBuffers(); glBufferData(GL_ARRAY_BUFFER, origins.size() * sizeof(origins), origins.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, originsBuffer); glVertexAttribPointer(1, // attribute. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void *)0 // array buffer offset ); glm::mat4 Projection = glm::perspective(zoom, aspect, 0.1f, 100.0f); glm::mat4 Model = glm::mat4(1.0f); glm::mat4 MVP = Projection * ViewMat * Model; GLuint programID = allInstances[0]->shaderProgram; glVertexAttribDivisor(0, 0); glVertexAttribDivisor(1, 1); glUniformMatrix4fv(glGetUniformLocation(programID, "MVP"), 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(glGetUniformLocation(programID, "M"), 1, GL_FALSE, &Model[0][0]); glUniformMatrix4fv(glGetUniformLocation(programID, "V"), 1, GL_FALSE, &ViewMat[0][0]); glUniform3f(glGetUniformLocation(programID, "lightPosWorld"), light.x, light.y, light.z); glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, allInstances[0]->vertices.size() / 3, count); } Player vertex shader: #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; uniform mat4 MVP; uniform mat4 M; uniform mat4 V; uniform vec3 origin; uniform vec3 lightPosWorld; uniform vec3 cameraPos; out vec3 vertexPosWorld; out vec3 vertexNormal; out vec3 eyeDirectionCamera; out vec3 lightDirectionCamera; void main() { gl_Position = MVP * vec4(vertexPosition_modelspace + origin,1); vertexPosWorld = (M * vec4(vertexPosition_modelspace + origin,1)).xyz; vertexNormal = normalize(vertexPosWorld - origin); } Bubble vertex shader: #version 330 core layout(location = 0) in vec3 vertexPosition_modelspace; layout(location = 1) in vec3 origin; uniform mat4 MVP; uniform mat4 M; uniform mat4 V; uniform vec3 lightPosWorld; uniform vec3 cameraPos; out vec3 vertexPosWorld; out vec3 vertexNormal; out vec3 eyeDirectionCamera; out vec3 lightDirectionCamera; void main() { gl_Position = MVP * vec4(vertexPosition_modelspace + origin,1); vertexPosWorld = (M * vec4(vertexPosition_modelspace + origin,1)).xyz; vertexNormal = normalize(vertexPosWorld - origin); } This is what I get: Effect But I wanted to get two bubbles that look exactly like the player (which draws correctly).
[ "There are 2 issues in the code:\n\nsizeof(origins) is a byte size of std::vector but not its underlying type. It should be sizeof(float).\nglBindBuffer should be called before modifying the buffer’s data and properties.\n\nIt should help:\n glBindBuffer(GL_ARRAY_BUFFER, originsBuffer);\n glBufferData(GL_ARRAY_BUFFER, origins.size() * sizeof(float), origins.data(), GL_STATIC_DRAW);\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(1, // attribute. No particular reason for 0, but must match the layout in the shader.\n 3, // size\n GL_FLOAT, // type\n GL_FALSE, // normalized?\n 0, // stride\n (void *)0 // array buffer offset\n );\n\n" ]
[ 0 ]
[]
[]
[ "c++", "graphics", "opengl" ]
stackoverflow_0074669643_c++_graphics_opengl.txt
Q: Power Automate Desktop - Copy Specific Columns Hi there and thank you in advance. I am trying to copy specific columns of data that are not next to each other from an Excel file including their headers and eventually write them into a csv. What is the best approach? I have seen suggestions for variables, loops and lists. A: You could use SQL to get your desired result. You can use an excel spreadsheet like a Ace SQL table (Access Database) see Run Sql Queries in Power Automate Desktop Copy the 'code' below and paste it into power automate desktop. You will have to fix the errors that show up related to file paths. SET Excel_File_Path TO $'''H:\\Temp\\SOAnswer.xlsx''' SET csvFilePath TO $'''H:\\Temp\\SOAnswer.csv''' Database.Connect ConnectionString: $'''Provider=Microsoft.ACE.OLEDB.12.0;Data Source=%Excel_File_Path%;Extended Properties=\"Excel 12.0 Xml;HDR=YES\";''' Connection=> SQLConnection Database.ExecuteSqlStatement.ConnectAndExecute ConnectionString: SQLConnection Statement: $'''SELECT [Value] & \', \' & [Check] & \', \' & [Additional Data] as CSV FROM [List1$]''' Timeout: 30 Result=> QueryResult Database.Close Connection: SQLConnection Variables.CreateNewList List=> HeadersList Variables.AddItemToList Item: $'''Value, Check, Additional Data''' List: HeadersList File.WriteToCSVFile.WriteCSV VariableToWrite: HeadersList CSVFile: csvFilePath CsvFileEncoding: File.CSVEncoding.UTF8 IncludeColumnNames: False IfFileExists: File.IfFileExists.Append ColumnsSeparator: File.CSVColumnsSeparator.SystemDefault File.WriteToCSVFile.WriteCSV VariableToWrite: QueryResult CSVFile: csvFilePath CsvFileEncoding: File.CSVEncoding.UTF8 IncludeColumnNames: False IfFileExists: File.IfFileExists.Append ColumnsSeparator: File.CSVColumnsSeparator.SystemDefault # Clean up the "" at the beginning and end of each line File.ReadTextFromFile.ReadText File: csvFilePath Encoding: File.TextFileEncoding.UTF8 Content=> csvFileContents Text.Replace Text: csvFileContents TextToFind: $'''\"''' IsRegEx: False IgnoreCase: False ReplaceWith: $'''%''%''' ActivateEscapeSequences: False Result=> csvFileContents File.WriteText File: csvFilePath TextToWrite: csvFileContents AppendNewLine: True IfFileExists: File.IfFileExists.Overwrite Encoding: File.FileEncoding.Unicode it should end up looking something like this. the dummy data from excel looked like this. The result. Keep in mind that the SQL used for this is Access SQL flavour, so you won't have all the functionality of MS SQL Server queries, but it sure beats having to run several list extractions and looping through them.
Power Automate Desktop - Copy Specific Columns
Hi there and thank you in advance. I am trying to copy specific columns of data that are not next to each other from an Excel file including their headers and eventually write them into a csv. What is the best approach? I have seen suggestions for variables, loops and lists.
[ "You could use SQL to get your desired result.\nYou can use an excel spreadsheet like a Ace SQL table (Access Database)\nsee Run Sql Queries in Power Automate Desktop\nCopy the 'code' below and paste it into power automate desktop.\nYou will have to fix the errors that show up related to file paths.\nSET Excel_File_Path TO $'''H:\\\\Temp\\\\SOAnswer.xlsx'''\n\nSET csvFilePath TO $'''H:\\\\Temp\\\\SOAnswer.csv'''\n\nDatabase.Connect ConnectionString: $'''Provider=Microsoft.ACE.OLEDB.12.0;Data Source=%Excel_File_Path%;Extended Properties=\\\"Excel 12.0 Xml;HDR=YES\\\";''' Connection=> SQLConnection\n\nDatabase.ExecuteSqlStatement.ConnectAndExecute ConnectionString: SQLConnection Statement: $'''SELECT [Value] & \\', \\' & [Check] & \\', \\' & [Additional Data] as CSV\nFROM [List1$]''' Timeout: 30 Result=> QueryResult\n\nDatabase.Close Connection: SQLConnection\n\nVariables.CreateNewList List=> HeadersList\n\nVariables.AddItemToList Item: $'''Value, Check, Additional Data''' List: HeadersList\n\nFile.WriteToCSVFile.WriteCSV VariableToWrite: HeadersList CSVFile: csvFilePath CsvFileEncoding: File.CSVEncoding.UTF8 IncludeColumnNames: False IfFileExists: File.IfFileExists.Append ColumnsSeparator: File.CSVColumnsSeparator.SystemDefault\n\nFile.WriteToCSVFile.WriteCSV VariableToWrite: QueryResult CSVFile: csvFilePath CsvFileEncoding: File.CSVEncoding.UTF8 IncludeColumnNames: False IfFileExists: File.IfFileExists.Append ColumnsSeparator: File.CSVColumnsSeparator.SystemDefault\n\n# Clean up the \"\" at the beginning and end of each line\nFile.ReadTextFromFile.ReadText File: csvFilePath Encoding: File.TextFileEncoding.UTF8 Content=> csvFileContents\n\nText.Replace Text: csvFileContents TextToFind: $'''\\\"''' IsRegEx: False IgnoreCase: False ReplaceWith: $'''%''%''' ActivateEscapeSequences: False Result=> csvFileContents\n\nFile.WriteText File: csvFilePath TextToWrite: csvFileContents AppendNewLine: True IfFileExists: File.IfFileExists.Overwrite Encoding: File.FileEncoding.Unicode\n\nit should end up looking something like this.\n\nthe dummy data from excel looked like this.\n\nThe result.\n\nKeep in mind that the SQL used for this is Access SQL flavour, so you won't have all the functionality of MS SQL Server queries, but it sure beats having to run several list extractions and looping through them.\n" ]
[ 0 ]
[]
[]
[ "power_automate_desktop" ]
stackoverflow_0074182981_power_automate_desktop.txt
Q: Compile investigated C++ code with QT 5.15.3 - Serial communication, focus: receive data (1) Are this samples of warnings from the compiling relevant for my compile result? (2) What are these moc*.-files? For which purpose are this files in my finished compile result? I would like to have an executable file for my terminal application in QT. You see the steps in attachement 1 - I have the serial.cpp, the serial.h and the 3.pro (project file). Now I ran qmake and make, but I expected an executable file. The external investigated code: serial.cpp #include "serial.h" #include <stdio.h> #include <QtCore/QCoreApplication> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> #include <QMutex> #include <QTime> #include <QThread> Serial::Serial(QObject *parent) : QObject(parent) { qDebug() << "Serial::Serial()" << "thread: " << QThread::currentThread(); this->port = new QSerialPort(this); } Serial::~Serial() { qDebug() << "Serial::~Serial() - Begin" << "thread: " << QThread::currentThread(); close(); delete this->port; qDebug() << "Serial::~Serial() - End" << "thread: " << QThread::currentThread(); } //Open the specified port with the specified baud rate. Returns true if successful, false otherwise. bool Serial::open(QString portName, qint32 baudRate){ //QSerialPort port; this->port->setPortName(portName); //Set the baud rate to 9600 before opening to grease the wheels for Mac this->setBaudRate(9600); if(this->port->open(QIODevice::ReadWrite)) { //Update to the actual desired baud rate this->port->setBaudRate(baudRate); return true; } else { return false; } } //Open the specified port with the specified baud rate. Returns true if successful, false otherwise. bool Serial::open(QSerialPortInfo portInfo, qint32 baudRate){ //QSerialPort port; this->port->setPort(portInfo); //Set the baud rate to 9600 before opening to grease the wheels for Mac this->setBaudRate(9600); if(this->port->open(QIODevice::ReadWrite)) { //Update to the actual desired baud rate this->port->setBaudRate(baudRate); return true; } else { qDebug() << "Failed to open" << portInfo.portName() << " : " << this->port->error(); return false; } } //Returns true if the serial port is open bool Serial::isOpen() { return this->port->isOpen(); } //Write data to the port. Returns true if numBytes were successfully written to the port, false otherwise. bool Serial::write(const char *data, int numBytes) { if(!this->port->isOpen()) { return false; } else { if(this->port->write(data, numBytes) != numBytes) { return false; } return true; } } //Write data to the port. Returns true if all bytes were successfully written, false otherwise. bool Serial::write(QByteArray data) { if(!this->port->isOpen()) { return false; } else { if(this->port->write(data) == data.length()) { return true; } return false; } } //Write the specified data to the serial port. Read response data until the number of ms specified in timeout ellaspes between response bytes, then return response data. QByteArray Serial::writeRead(QByteArray data, int timeout){ return writeRead(data, timeout, timeout); } //Write the specified data to the serial port. Delay up to the specified delay ms for the first response byte, //then read response data until the number of ms specified in timeout ellaspes between response bytes, then return response data. QByteArray Serial::writeRead(QByteArray data, int delay, int timeout) { QByteArray resp; this->write(data); if(waitForBytesAvailable(1, delay)){ //Read first incoming data resp.append(this->port->readAll()); //Continue reading until timout expires while(waitForBytesAvailable(1, timeout)) { resp.append(this->port->readAll()); } return resp; } return resp; } //Write the specified data to the serial port. Wait up to delay ms for the first byte to be returned. Return an empty array if delay expires. //While data is being returned wait up to timeout ms for the inoming byte. Return data if timeout expires. //Return data immediatly if a complete JSON object or complete chunked transfer is detected. QByteArray Serial::fastWriteRead(QByteArray data, int delay, int timeout) { QMutex mutex; mutex.lock(); qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Send:" << data; QByteArray resp; QTime stopWatch; stopWatch.start(); //Clear incoming buffer before writing new command QByteArray flushedData = this->port->readAll(); qDebug() << "Flushed " << flushedData.length() << "in" << stopWatch.elapsed() << "ms"; //Write Command this->write(data); //Wait for resposne to start stopWatch.restart(); if(waitForBytesAvailable(1, delay)){ qDebug() << "Waited" << stopWatch.elapsed() << "ms for first byte"; //Read first incoming data stopWatch.restart(); resp.append(this->port->readAll()); qDebug() << "Took" << stopWatch.elapsed() << "ms to read first burst"; //Checking if incoming data is a JSON object, OSJB, or other. stopWatch.restart(); if(resp[0] == '{') { //---------- JSON ---------- qDebug() <<"Incoming Data Looks Like JSON"; int openBracketCount = 0; //Process initial data for(int i=0; i< resp.length(); i++) { if(resp[i] == '{') { openBracketCount++; } else if(resp[i] == '}') { openBracketCount--; } if(openBracketCount <= 0) { qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Found the end in " << stopWatch.elapsed() << "- Response:" << resp; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } } //Continue reading until timeout expires stopWatch.restart(); while(waitForBytesAvailable(1, timeout)) { qDebug() << "waiting for timeout for" << stopWatch.elapsed() << "ms"; while(this->port->bytesAvailable() > 0) { char respByte = this->port->read(1)[0]; resp.append(respByte); if(respByte == '{') { openBracketCount++; } else if(respByte == '}') { openBracketCount--; } if(openBracketCount <= 0) { qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Response:" << resp; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } } } } else { //---------- OTHER - Assume Chunked---------- //Clear any leading, non-chunked data while((resp.length()) > 0 && (!(resp[0] >= '0' && resp[0] <= '9') && !(resp[0] >= 'a' && resp[0] <= 'f') && !(resp[0] >= 'A' && resp[0] <= 'F'))) { qDebug() << "Trimming " << resp[0] << " from start of response"; resp = resp.mid(1); } //Continue reading until timeout expires stopWatch.restart(); while(waitForBytesAvailable(1, timeout)) { qDebug() << "waiting for timeout for" << stopWatch.elapsed() << "ms"; while(this->port->bytesAvailable() > 0) { char respByte = this->port->read(1)[0]; resp.append(respByte); //Check if chunk is done if(respByte == '\n') { if(validChunkedData(resp)) { qDebug() << "----------Chunked Transfer Complete----------"; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } } } } } } qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Timeout - Response:" << resp; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } //Returns the chunk size if the specified input is in valid chunk format or -1 otherwise int Serial::getChunkSize(QString data) { int endIndex = data.indexOf("\r\n"); if(endIndex > 0) { bool ok = false; unsigned int chunkSize = data.left(endIndex).toUInt(&ok, 16); if(ok){ return chunkSize; } else { return -1; } } else { return -1; } } //Returns the number of bytes available at the port or -1 if the port is not open int Serial::bytesAvailable() { QTime stopWatch; if(!this->port->isOpen()) { return -1; } else{ stopWatch.restart(); //This is required on Mac for bytes to be readable. Do not change. #if defined(TARGET_OS_MAC) this->port->waitForReadyRead(0); #else this->port->waitForReadyRead(1); #endif int numBytes = this->port->bytesAvailable(); //qDebug() << "Took" << stopWatch.elapsed() << "ms" << "and found" << numBytes << "bytes"; return this->port->bytesAvailable(); } } //Wait for the specified number of bytes to be avialable or timeout. Returns true if the specified number of bytes are available, false otherwise. bool Serial::waitForBytesAvailable(int numBytes, int timeout) { QTime startTime = QTime::currentTime(); QTime doneTime = startTime.addMSecs(timeout); while(QTime::currentTime() < doneTime) { if(bytesAvailable() >= numBytes) { return true; } } return false; } /* //Read the specified number of bytes from the port into the provided buffer. This function returns true if numBytes were succesfully read and false otherwise. bool Serial::read(char* rxBuffer, int numBytes) { this->port.waitForReadyRead(0); if(!this->port.isOpen()) { //Port not open return false; } else if(this->port.bytesAvailable() < numBytes) { //Not enough bytes available return false; } else { if(this->port.read(rxBuffer, numBytes) < 0){ return false; } return true; } } */ //Read the specified number of bytes from the serial buffer. Data is returned as a byte array. QByteArray Serial::read(qint64 numBytes) { //This is required on Mac for bytes to be readable. Do not change. #if defined(TARGET_OS_MAC) this->port->waitForReadyRead(0); #else this->port->waitForReadyRead(1); #endif return this->port->read(numBytes); } //Read all available bytes from the serial buffer. Data is returned as a byte array. QByteArray Serial::read() { if(!this->port->isOpen()) { return NULL; } QTime stopWatch; stopWatch.restart(); //This is required on Mac for bytes to be readable. Do not change. #if defined(TARGET_OS_MAC) this->port->waitForReadyRead(0); #else this->port->waitForReadyRead(1); #endif if(stopWatch.elapsed() > 2){ qDebug() << "Read took took long" << stopWatch.elapsed(); } return this->port->readAll(); } //Close the serial port. void Serial::close() { qDebug() << "Serial::close()" << "thread: " << QThread::currentThread(); //Set the baud rate back to 9600 before closing to grease the wheels for Mac this->setBaudRate(9600); if(port->isOpen()) { this->port->close(); } } //Refresh the system serial port info and return it. QList<QSerialPortInfo> Serial::getSerialPortInfo() { return QSerialPortInfo::availablePorts(); } //Assert a reset by setting RTS and DTR high for 100ms, DTR low for 50ms then DTR high for 100ms. Returns true on success false otherwise. bool Serial::assertReset() { //Set RTS and DTR if(this->port->setRequestToSend(true) && this->port->setDataTerminalReady(true)){ delay(100); if(!this->port->setDataTerminalReady(false)) { return false; } else { delay(50); if(!this->port->setDataTerminalReady(true)) { return false; } else { delay(100); return true; } } } else { return false; } } //Delay the specified number of ms. void Serial::delay(int ms){ QTime stopWatch; stopWatch.start(); QTime startTime = QTime::currentTime(); QTime doneTime = startTime.addMSecs(ms); while (QTime::currentTime() < doneTime) { QCoreApplication::processEvents(QEventLoop::AllEvents, 1); } } int Serial::getBaudRate() { return this->port->baudRate(); } //Set the serial port baud rate. Returns true on success, false otherwise. bool Serial::setBaudRate(int baudRate) { return this->port->setBaudRate(baudRate); } //Return the current port name; QString Serial::getName(){ return this->port->portName(); } //Clear all bytes from the UART input buffer and return the number of bytes returned int Serial::flushInputBuffer(){ qDebug() << "Serial::flushInputBuffer() Begin"; //Byte are not available until waitForReadyRead() is called if(this->port != 0) { QTime stopWatch; stopWatch.start(); this->port->waitForReadyRead(1); qDebug() << "waitForReadyRead() took " << stopWatch.elapsed(); stopWatch.restart(); int flushCount = this->port->readAll().length(); qDebug() << "readAll() took " << stopWatch.elapsed(); qDebug() << "Serial::flushInputBuffer()" << flushCount; return flushCount; }else { return 0; } } //Soft reset the serial port. This funciton closes and reopens the serial port with the same settings. bool Serial::softReset(){ QString name = this->getName(); int baudRate = this->getBaudRate(); this->close(); bool success = this->open(name, baudRate); emit softResetResponse(success); return success; } bool Serial::validChunkedData(QByteArray data) { while(getChunkSize(data) >= 0) { int chunkSize = getChunkSize(data); int startOfChunk = data.indexOf("\r\n") + 2; //Return false if chunk is not complete if(data.length() < startOfChunk + chunkSize + 2) { qDebug() << "Incomplete Chunk"; return false; } //If chunk size is 0 and the chunk is complete we're at the end if(chunkSize == 0) { qDebug() << "Found Valid End Of Chunked Transfer"; return true; } QByteArray chunk = data.mid(startOfChunk, chunkSize); //qDebug() << "Valid" << chunkSize << "Byte Chunk:" << chunk; //qDebug() << "Remaining Data" << data.mid(startOfChunk + chunkSize + 2).length() << "Bytes" << data.mid(startOfChunk + chunkSize + 2); data = data.mid(startOfChunk + chunkSize + 2); } return false; } serial.h #ifndef SERIAL_H #define SERIAL_H #include <QDebug> #include <QList> #include <QObject> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> #include <QString> class Serial : public QObject { Q_OBJECT public: explicit Serial(QObject *parent = 0); ~Serial(); //Open bool open(QString portName, qint32 baudRate); bool open(QSerialPortInfo portInfo, qint32 baudRate); //Write bool write(const char *data, int numBytes); bool write(QByteArray data); QByteArray writeRead(QByteArray data, int timeout); QByteArray writeRead(QByteArray data, int delay, int timeout); //Read QByteArray read(qint64 numBytes); QByteArray read(); int bytesAvailable(); bool waitForBytesAvailable(int numBytes, int timeout); //Close void close(); //Utility bool assertReset(); int getBaudRate(); QString getName(); bool isOpen(); bool setBaudRate(int baudRate); int flushInputBuffer(); int getChunkSize(QString data); bool validChunkedData(QByteArray data); static QList<QSerialPortInfo> getSerialPortInfo(); static void delay(int ms); signals: QByteArray fastWriteReadResponse(QByteArray response); bool softResetResponse(bool status); public slots: QByteArray fastWriteRead(QByteArray data, int delay, int timeout); bool softReset(); private: QSerialPort* port; }; #endif // SERIAL_H 3.pro ###################################################################### # Automatically generated by qmake (3.1) Sat Dec 3 19:58:33 2022 ###################################################################### QT += serialport TEMPLATE = app TARGET = 3 INCLUDEPATH += . # You can make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # Please consult the documentation of the deprecated API in order to know # how to port your code away from it. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 # Input HEADERS += serial.h SOURCES += serial.cpp A: Compiler Output: g++ -c -pipe -O2 -Wall -Wextra -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_SERIALPORT_LIB -DQT_CORE_LIB -I. -I. -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtSerialPort -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o serial.o serial.cpp serial.cpp: In member function ‘QByteArray Serial::fastWriteRead(QByteArray, int, int)’: serial.cpp:131:20: warning: ‘void QTime::start()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 131 | stopWatch.start(); | ~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:235:55: note: declared here 235 | QT_DEPRECATED_X("Use QElapsedTimer instead") void start(); | ^~~~~ serial.cpp:136:80: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 136 | qDebug() << "Flushed " << flushedData.length() << "in" << stopWatch.elapsed() << "ms"; | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:142:22: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 142 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:144:50: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 144 | qDebug() << "Waited" << stopWatch.elapsed() << "ms for first byte"; | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:146:26: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 146 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:148:48: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 148 | qDebug() << "Took" << stopWatch.elapsed() << "ms to read first burst"; | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:151:27: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 151 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:166:144: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 166 | qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Found the end in " << stopWatch.elapsed() << "- Response:" << resp; | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:174:30: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 174 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:177:75: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 177 | qDebug() << "waiting for timeout for" << stopWatch.elapsed() << "ms"; | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:208:30: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 208 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:211:75: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 211 | qDebug() << "waiting for timeout for" << stopWatch.elapsed() << "ms"; | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp: In member function ‘int Serial::bytesAvailable()’: serial.cpp:261:26: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 261 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:268:13: warning: unused variable ‘numBytes’ [-Wunused-variable] 268 | int numBytes = this->port->bytesAvailable(); | ^~~~~~~~ serial.cpp: In member function ‘QByteArray Serial::read()’: serial.cpp:327:22: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 327 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:334:25: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 334 | if(stopWatch.elapsed() > 2){ | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:335:63: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 335 | qDebug() << "Read took took long" << stopWatch.elapsed(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp: In static member function ‘static void Serial::delay(int)’: serial.cpp:380:20: warning: ‘void QTime::start()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 380 | stopWatch.start(); | ~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:235:55: note: declared here 235 | QT_DEPRECATED_X("Use QElapsedTimer instead") void start(); | ^~~~~ serial.cpp: In member function ‘int Serial::flushInputBuffer()’: serial.cpp:410:24: warning: ‘void QTime::start()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 410 | stopWatch.start(); | ~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:235:55: note: declared here 235 | QT_DEPRECATED_X("Use QElapsedTimer instead") void start(); | ^~~~~ serial.cpp:412:68: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 412 | qDebug() << "waitForReadyRead() took " << stopWatch.elapsed(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ serial.cpp:413:26: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 413 | stopWatch.restart(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here 236 | QT_DEPRECATED_X("Use QElapsedTimer instead") int restart(); | ^~~~~~~ serial.cpp:415:59: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations] 415 | qDebug() << "readAll() took " << stopWatch.elapsed(); | ~~~~~~~~~~~~~~~~~^~ In file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1, from serial.cpp:9: /usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here 237 | QT_DEPRECATED_X("Use QElapsedTimer instead") int elapsed() const; | ^~~~~~~ g++ -c -pipe -O2 -Wall -Wextra -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_SERIALPORT_LIB -DQT_CORE_LIB -I. -I. -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtSerialPort -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o moc_serial.o moc_serial.cpp g++ -Wl,-O1 -o 3 serial.o moc_serial.o /usr/lib/x86_64-linux-gnu/libQt5Gui.so /usr/lib/x86_64-linux-gnu/libQt5SerialPort.so /usr/lib/x86_64-linux-gnu/libQt5Core.so -lGL -lpthread /usr/bin/ld: moc_serial.o: in function `Serial::metaObject() const': moc_serial.cpp:(.text+0x0): multiple definition of `Serial::metaObject() const'; serial.o:serial.cpp:(.text+0x0): first defined here /usr/bin/ld: moc_serial.o:(.data.rel.ro+0x0): multiple definition of `Serial::staticMetaObject'; serial.o:(.data.rel.ro+0x0): first defined here /usr/bin/ld: moc_serial.o: in function `Serial::softResetResponse(bool)': moc_serial.cpp:(.text+0x20): multiple definition of `Serial::softResetResponse(bool)'; serial.o:serial.cpp:(.text+0x20): first defined here /usr/bin/ld: moc_serial.o: in function `Serial::fastWriteReadResponse(QByteArray)': moc_serial.cpp:(.text+0x90): multiple definition of `Serial::fastWriteReadResponse(QByteArray)'; serial.o:serial.cpp:(.text+0x90): first defined here /usr/bin/ld: moc_serial.o: in function `Serial::qt_static_metacall(QObject*, QMetaObject::Call, int, void**)': moc_serial.cpp:(.text+0x100): multiple definition of `Serial::qt_static_metacall(QObject*, QMetaObject::Call, int, void**)'; serial.o:serial.cpp:(.text+0x4320): first defined here /usr/bin/ld: moc_serial.o: in function `Serial::qt_metacast(char const*)': moc_serial.cpp:(.text+0x340): multiple definition of `Serial::qt_metacast(char const*)'; serial.o:serial.cpp:(.text+0x4560): first defined here /usr/bin/ld: moc_serial.o: in function `Serial::qt_metacall(QMetaObject::Call, int, void**)': moc_serial.cpp:(.text+0x3a0): multiple definition of `Serial::qt_metacall(QMetaObject::Call, int, void**)'; serial.o:serial.cpp:(.text+0x45c0): first defined here /usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o: in function `_start': (.text+0x1b): undefined reference to `main' collect2: error: ld returned 1 exit status make: *** [Makefile:145: 3] Error 1
Compile investigated C++ code with QT 5.15.3 - Serial communication, focus: receive data
(1) Are this samples of warnings from the compiling relevant for my compile result? (2) What are these moc*.-files? For which purpose are this files in my finished compile result? I would like to have an executable file for my terminal application in QT. You see the steps in attachement 1 - I have the serial.cpp, the serial.h and the 3.pro (project file). Now I ran qmake and make, but I expected an executable file. The external investigated code: serial.cpp #include "serial.h" #include <stdio.h> #include <QtCore/QCoreApplication> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> #include <QMutex> #include <QTime> #include <QThread> Serial::Serial(QObject *parent) : QObject(parent) { qDebug() << "Serial::Serial()" << "thread: " << QThread::currentThread(); this->port = new QSerialPort(this); } Serial::~Serial() { qDebug() << "Serial::~Serial() - Begin" << "thread: " << QThread::currentThread(); close(); delete this->port; qDebug() << "Serial::~Serial() - End" << "thread: " << QThread::currentThread(); } //Open the specified port with the specified baud rate. Returns true if successful, false otherwise. bool Serial::open(QString portName, qint32 baudRate){ //QSerialPort port; this->port->setPortName(portName); //Set the baud rate to 9600 before opening to grease the wheels for Mac this->setBaudRate(9600); if(this->port->open(QIODevice::ReadWrite)) { //Update to the actual desired baud rate this->port->setBaudRate(baudRate); return true; } else { return false; } } //Open the specified port with the specified baud rate. Returns true if successful, false otherwise. bool Serial::open(QSerialPortInfo portInfo, qint32 baudRate){ //QSerialPort port; this->port->setPort(portInfo); //Set the baud rate to 9600 before opening to grease the wheels for Mac this->setBaudRate(9600); if(this->port->open(QIODevice::ReadWrite)) { //Update to the actual desired baud rate this->port->setBaudRate(baudRate); return true; } else { qDebug() << "Failed to open" << portInfo.portName() << " : " << this->port->error(); return false; } } //Returns true if the serial port is open bool Serial::isOpen() { return this->port->isOpen(); } //Write data to the port. Returns true if numBytes were successfully written to the port, false otherwise. bool Serial::write(const char *data, int numBytes) { if(!this->port->isOpen()) { return false; } else { if(this->port->write(data, numBytes) != numBytes) { return false; } return true; } } //Write data to the port. Returns true if all bytes were successfully written, false otherwise. bool Serial::write(QByteArray data) { if(!this->port->isOpen()) { return false; } else { if(this->port->write(data) == data.length()) { return true; } return false; } } //Write the specified data to the serial port. Read response data until the number of ms specified in timeout ellaspes between response bytes, then return response data. QByteArray Serial::writeRead(QByteArray data, int timeout){ return writeRead(data, timeout, timeout); } //Write the specified data to the serial port. Delay up to the specified delay ms for the first response byte, //then read response data until the number of ms specified in timeout ellaspes between response bytes, then return response data. QByteArray Serial::writeRead(QByteArray data, int delay, int timeout) { QByteArray resp; this->write(data); if(waitForBytesAvailable(1, delay)){ //Read first incoming data resp.append(this->port->readAll()); //Continue reading until timout expires while(waitForBytesAvailable(1, timeout)) { resp.append(this->port->readAll()); } return resp; } return resp; } //Write the specified data to the serial port. Wait up to delay ms for the first byte to be returned. Return an empty array if delay expires. //While data is being returned wait up to timeout ms for the inoming byte. Return data if timeout expires. //Return data immediatly if a complete JSON object or complete chunked transfer is detected. QByteArray Serial::fastWriteRead(QByteArray data, int delay, int timeout) { QMutex mutex; mutex.lock(); qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Send:" << data; QByteArray resp; QTime stopWatch; stopWatch.start(); //Clear incoming buffer before writing new command QByteArray flushedData = this->port->readAll(); qDebug() << "Flushed " << flushedData.length() << "in" << stopWatch.elapsed() << "ms"; //Write Command this->write(data); //Wait for resposne to start stopWatch.restart(); if(waitForBytesAvailable(1, delay)){ qDebug() << "Waited" << stopWatch.elapsed() << "ms for first byte"; //Read first incoming data stopWatch.restart(); resp.append(this->port->readAll()); qDebug() << "Took" << stopWatch.elapsed() << "ms to read first burst"; //Checking if incoming data is a JSON object, OSJB, or other. stopWatch.restart(); if(resp[0] == '{') { //---------- JSON ---------- qDebug() <<"Incoming Data Looks Like JSON"; int openBracketCount = 0; //Process initial data for(int i=0; i< resp.length(); i++) { if(resp[i] == '{') { openBracketCount++; } else if(resp[i] == '}') { openBracketCount--; } if(openBracketCount <= 0) { qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Found the end in " << stopWatch.elapsed() << "- Response:" << resp; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } } //Continue reading until timeout expires stopWatch.restart(); while(waitForBytesAvailable(1, timeout)) { qDebug() << "waiting for timeout for" << stopWatch.elapsed() << "ms"; while(this->port->bytesAvailable() > 0) { char respByte = this->port->read(1)[0]; resp.append(respByte); if(respByte == '{') { openBracketCount++; } else if(respByte == '}') { openBracketCount--; } if(openBracketCount <= 0) { qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Response:" << resp; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } } } } else { //---------- OTHER - Assume Chunked---------- //Clear any leading, non-chunked data while((resp.length()) > 0 && (!(resp[0] >= '0' && resp[0] <= '9') && !(resp[0] >= 'a' && resp[0] <= 'f') && !(resp[0] >= 'A' && resp[0] <= 'F'))) { qDebug() << "Trimming " << resp[0] << " from start of response"; resp = resp.mid(1); } //Continue reading until timeout expires stopWatch.restart(); while(waitForBytesAvailable(1, timeout)) { qDebug() << "waiting for timeout for" << stopWatch.elapsed() << "ms"; while(this->port->bytesAvailable() > 0) { char respByte = this->port->read(1)[0]; resp.append(respByte); //Check if chunk is done if(respByte == '\n') { if(validChunkedData(resp)) { qDebug() << "----------Chunked Transfer Complete----------"; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } } } } } } qDebug() << "Serial::fastWriteRead()" << "thread: " << QThread::currentThread() << "Timeout - Response:" << resp; emit fastWriteReadResponse(resp); mutex.unlock(); return resp; } //Returns the chunk size if the specified input is in valid chunk format or -1 otherwise int Serial::getChunkSize(QString data) { int endIndex = data.indexOf("\r\n"); if(endIndex > 0) { bool ok = false; unsigned int chunkSize = data.left(endIndex).toUInt(&ok, 16); if(ok){ return chunkSize; } else { return -1; } } else { return -1; } } //Returns the number of bytes available at the port or -1 if the port is not open int Serial::bytesAvailable() { QTime stopWatch; if(!this->port->isOpen()) { return -1; } else{ stopWatch.restart(); //This is required on Mac for bytes to be readable. Do not change. #if defined(TARGET_OS_MAC) this->port->waitForReadyRead(0); #else this->port->waitForReadyRead(1); #endif int numBytes = this->port->bytesAvailable(); //qDebug() << "Took" << stopWatch.elapsed() << "ms" << "and found" << numBytes << "bytes"; return this->port->bytesAvailable(); } } //Wait for the specified number of bytes to be avialable or timeout. Returns true if the specified number of bytes are available, false otherwise. bool Serial::waitForBytesAvailable(int numBytes, int timeout) { QTime startTime = QTime::currentTime(); QTime doneTime = startTime.addMSecs(timeout); while(QTime::currentTime() < doneTime) { if(bytesAvailable() >= numBytes) { return true; } } return false; } /* //Read the specified number of bytes from the port into the provided buffer. This function returns true if numBytes were succesfully read and false otherwise. bool Serial::read(char* rxBuffer, int numBytes) { this->port.waitForReadyRead(0); if(!this->port.isOpen()) { //Port not open return false; } else if(this->port.bytesAvailable() < numBytes) { //Not enough bytes available return false; } else { if(this->port.read(rxBuffer, numBytes) < 0){ return false; } return true; } } */ //Read the specified number of bytes from the serial buffer. Data is returned as a byte array. QByteArray Serial::read(qint64 numBytes) { //This is required on Mac for bytes to be readable. Do not change. #if defined(TARGET_OS_MAC) this->port->waitForReadyRead(0); #else this->port->waitForReadyRead(1); #endif return this->port->read(numBytes); } //Read all available bytes from the serial buffer. Data is returned as a byte array. QByteArray Serial::read() { if(!this->port->isOpen()) { return NULL; } QTime stopWatch; stopWatch.restart(); //This is required on Mac for bytes to be readable. Do not change. #if defined(TARGET_OS_MAC) this->port->waitForReadyRead(0); #else this->port->waitForReadyRead(1); #endif if(stopWatch.elapsed() > 2){ qDebug() << "Read took took long" << stopWatch.elapsed(); } return this->port->readAll(); } //Close the serial port. void Serial::close() { qDebug() << "Serial::close()" << "thread: " << QThread::currentThread(); //Set the baud rate back to 9600 before closing to grease the wheels for Mac this->setBaudRate(9600); if(port->isOpen()) { this->port->close(); } } //Refresh the system serial port info and return it. QList<QSerialPortInfo> Serial::getSerialPortInfo() { return QSerialPortInfo::availablePorts(); } //Assert a reset by setting RTS and DTR high for 100ms, DTR low for 50ms then DTR high for 100ms. Returns true on success false otherwise. bool Serial::assertReset() { //Set RTS and DTR if(this->port->setRequestToSend(true) && this->port->setDataTerminalReady(true)){ delay(100); if(!this->port->setDataTerminalReady(false)) { return false; } else { delay(50); if(!this->port->setDataTerminalReady(true)) { return false; } else { delay(100); return true; } } } else { return false; } } //Delay the specified number of ms. void Serial::delay(int ms){ QTime stopWatch; stopWatch.start(); QTime startTime = QTime::currentTime(); QTime doneTime = startTime.addMSecs(ms); while (QTime::currentTime() < doneTime) { QCoreApplication::processEvents(QEventLoop::AllEvents, 1); } } int Serial::getBaudRate() { return this->port->baudRate(); } //Set the serial port baud rate. Returns true on success, false otherwise. bool Serial::setBaudRate(int baudRate) { return this->port->setBaudRate(baudRate); } //Return the current port name; QString Serial::getName(){ return this->port->portName(); } //Clear all bytes from the UART input buffer and return the number of bytes returned int Serial::flushInputBuffer(){ qDebug() << "Serial::flushInputBuffer() Begin"; //Byte are not available until waitForReadyRead() is called if(this->port != 0) { QTime stopWatch; stopWatch.start(); this->port->waitForReadyRead(1); qDebug() << "waitForReadyRead() took " << stopWatch.elapsed(); stopWatch.restart(); int flushCount = this->port->readAll().length(); qDebug() << "readAll() took " << stopWatch.elapsed(); qDebug() << "Serial::flushInputBuffer()" << flushCount; return flushCount; }else { return 0; } } //Soft reset the serial port. This funciton closes and reopens the serial port with the same settings. bool Serial::softReset(){ QString name = this->getName(); int baudRate = this->getBaudRate(); this->close(); bool success = this->open(name, baudRate); emit softResetResponse(success); return success; } bool Serial::validChunkedData(QByteArray data) { while(getChunkSize(data) >= 0) { int chunkSize = getChunkSize(data); int startOfChunk = data.indexOf("\r\n") + 2; //Return false if chunk is not complete if(data.length() < startOfChunk + chunkSize + 2) { qDebug() << "Incomplete Chunk"; return false; } //If chunk size is 0 and the chunk is complete we're at the end if(chunkSize == 0) { qDebug() << "Found Valid End Of Chunked Transfer"; return true; } QByteArray chunk = data.mid(startOfChunk, chunkSize); //qDebug() << "Valid" << chunkSize << "Byte Chunk:" << chunk; //qDebug() << "Remaining Data" << data.mid(startOfChunk + chunkSize + 2).length() << "Bytes" << data.mid(startOfChunk + chunkSize + 2); data = data.mid(startOfChunk + chunkSize + 2); } return false; } serial.h #ifndef SERIAL_H #define SERIAL_H #include <QDebug> #include <QList> #include <QObject> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> #include <QString> class Serial : public QObject { Q_OBJECT public: explicit Serial(QObject *parent = 0); ~Serial(); //Open bool open(QString portName, qint32 baudRate); bool open(QSerialPortInfo portInfo, qint32 baudRate); //Write bool write(const char *data, int numBytes); bool write(QByteArray data); QByteArray writeRead(QByteArray data, int timeout); QByteArray writeRead(QByteArray data, int delay, int timeout); //Read QByteArray read(qint64 numBytes); QByteArray read(); int bytesAvailable(); bool waitForBytesAvailable(int numBytes, int timeout); //Close void close(); //Utility bool assertReset(); int getBaudRate(); QString getName(); bool isOpen(); bool setBaudRate(int baudRate); int flushInputBuffer(); int getChunkSize(QString data); bool validChunkedData(QByteArray data); static QList<QSerialPortInfo> getSerialPortInfo(); static void delay(int ms); signals: QByteArray fastWriteReadResponse(QByteArray response); bool softResetResponse(bool status); public slots: QByteArray fastWriteRead(QByteArray data, int delay, int timeout); bool softReset(); private: QSerialPort* port; }; #endif // SERIAL_H 3.pro ###################################################################### # Automatically generated by qmake (3.1) Sat Dec 3 19:58:33 2022 ###################################################################### QT += serialport TEMPLATE = app TARGET = 3 INCLUDEPATH += . # You can make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # Please consult the documentation of the deprecated API in order to know # how to port your code away from it. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 # Input HEADERS += serial.h SOURCES += serial.cpp
[ "Compiler Output:\n\n\ng++ -c -pipe -O2 -Wall -Wextra -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_SERIALPORT_LIB -DQT_CORE_LIB -I. -I. -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtSerialPort -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o serial.o serial.cpp\nserial.cpp: In member function ‘QByteArray Serial::fastWriteRead(QByteArray, int, int)’:\nserial.cpp:131:20: warning: ‘void QTime::start()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 131 | stopWatch.start();\n | ~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:235:55: note: declared here\n 235 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") void start();\n | ^~~~~\nserial.cpp:136:80: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 136 | qDebug() << \"Flushed \" << flushedData.length() << \"in\" << stopWatch.elapsed() << \"ms\";\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:142:22: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 142 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:144:50: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 144 | qDebug() << \"Waited\" << stopWatch.elapsed() << \"ms for first byte\";\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:146:26: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 146 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:148:48: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 148 | qDebug() << \"Took\" << stopWatch.elapsed() << \"ms to read first burst\";\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:151:27: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 151 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:166:144: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 166 | qDebug() << \"Serial::fastWriteRead()\" << \"thread: \" << QThread::currentThread() << \"Found the end in \" << stopWatch.elapsed() << \"- Response:\" << resp;\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:174:30: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 174 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:177:75: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 177 | qDebug() << \"waiting for timeout for\" << stopWatch.elapsed() << \"ms\";\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:208:30: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 208 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:211:75: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 211 | qDebug() << \"waiting for timeout for\" << stopWatch.elapsed() << \"ms\";\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp: In member function ‘int Serial::bytesAvailable()’:\nserial.cpp:261:26: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 261 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:268:13: warning: unused variable ‘numBytes’ [-Wunused-variable]\n 268 | int numBytes = this->port->bytesAvailable();\n | ^~~~~~~~\nserial.cpp: In member function ‘QByteArray Serial::read()’:\nserial.cpp:327:22: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 327 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:334:25: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 334 | if(stopWatch.elapsed() > 2){\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:335:63: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 335 | qDebug() << \"Read took took long\" << stopWatch.elapsed();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp: In static member function ‘static void Serial::delay(int)’:\nserial.cpp:380:20: warning: ‘void QTime::start()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 380 | stopWatch.start();\n | ~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:235:55: note: declared here\n 235 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") void start();\n | ^~~~~\nserial.cpp: In member function ‘int Serial::flushInputBuffer()’:\nserial.cpp:410:24: warning: ‘void QTime::start()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 410 | stopWatch.start();\n | ~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:235:55: note: declared here\n 235 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") void start();\n | ^~~~~\nserial.cpp:412:68: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 412 | qDebug() << \"waitForReadyRead() took \" << stopWatch.elapsed();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\nserial.cpp:413:26: warning: ‘int QTime::restart()’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 413 | stopWatch.restart();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:236:54: note: declared here\n 236 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int restart();\n | ^~~~~~~\nserial.cpp:415:59: warning: ‘int QTime::elapsed() const’ is deprecated: Use QElapsedTimer instead [-Wdeprecated-declarations]\n 415 | qDebug() << \"readAll() took \" << stopWatch.elapsed();\n | ~~~~~~~~~~~~~~~~~^~\nIn file included from /usr/include/x86_64-linux-gnu/qt5/QtCore/QTime:1,\n from serial.cpp:9:\n/usr/include/x86_64-linux-gnu/qt5/QtCore/qdatetime.h:237:54: note: declared here\n 237 | QT_DEPRECATED_X(\"Use QElapsedTimer instead\") int elapsed() const;\n | ^~~~~~~\ng++ -c -pipe -O2 -Wall -Wextra -D_REENTRANT -fPIC -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_SERIALPORT_LIB -DQT_CORE_LIB -I. -I. -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtSerialPort -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o moc_serial.o moc_serial.cpp\ng++ -Wl,-O1 -o 3 serial.o moc_serial.o /usr/lib/x86_64-linux-gnu/libQt5Gui.so /usr/lib/x86_64-linux-gnu/libQt5SerialPort.so /usr/lib/x86_64-linux-gnu/libQt5Core.so -lGL -lpthread \n/usr/bin/ld: moc_serial.o: in function `Serial::metaObject() const':\nmoc_serial.cpp:(.text+0x0): multiple definition of `Serial::metaObject() const'; serial.o:serial.cpp:(.text+0x0): first defined here\n/usr/bin/ld: moc_serial.o:(.data.rel.ro+0x0): multiple definition of `Serial::staticMetaObject'; serial.o:(.data.rel.ro+0x0): first defined here\n/usr/bin/ld: moc_serial.o: in function `Serial::softResetResponse(bool)':\nmoc_serial.cpp:(.text+0x20): multiple definition of `Serial::softResetResponse(bool)'; serial.o:serial.cpp:(.text+0x20): first defined here\n/usr/bin/ld: moc_serial.o: in function `Serial::fastWriteReadResponse(QByteArray)':\nmoc_serial.cpp:(.text+0x90): multiple definition of `Serial::fastWriteReadResponse(QByteArray)'; serial.o:serial.cpp:(.text+0x90): first defined here\n/usr/bin/ld: moc_serial.o: in function `Serial::qt_static_metacall(QObject*, QMetaObject::Call, int, void**)':\nmoc_serial.cpp:(.text+0x100): multiple definition of `Serial::qt_static_metacall(QObject*, QMetaObject::Call, int, void**)'; serial.o:serial.cpp:(.text+0x4320): first defined here\n/usr/bin/ld: moc_serial.o: in function `Serial::qt_metacast(char const*)':\nmoc_serial.cpp:(.text+0x340): multiple definition of `Serial::qt_metacast(char const*)'; serial.o:serial.cpp:(.text+0x4560): first defined here\n/usr/bin/ld: moc_serial.o: in function `Serial::qt_metacall(QMetaObject::Call, int, void**)':\nmoc_serial.cpp:(.text+0x3a0): multiple definition of `Serial::qt_metacall(QMetaObject::Call, int, void**)'; serial.o:serial.cpp:(.text+0x45c0): first defined here\n/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':\n(.text+0x1b): undefined reference to `main'\ncollect2: error: ld returned 1 exit status\nmake: *** [Makefile:145: 3] Error 1\n\n\n\n" ]
[ 0 ]
[]
[]
[ "c++", "qt", "serial_communication" ]
stackoverflow_0074670898_c++_qt_serial_communication.txt
Q: Browser opens twice when running script I'm working on a web driver and I'm trying to implement classes into my code. I had this working but as soon as I turned it into a class my browser started opening twice when I ran the program. It will open a browser, then open the second browser, run the commands and then leave the first browser open. Can any tell me why this is happening? This is just an example of how is is formatted. import selenium import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait class About(object): def __init__(self, driver): self.driver = driver def pause(self): time.sleep(1) def run(self): self.driver.get('https://google.com') self.pause() def tearDown(self): self.driver.quit() go = About(webdriver.Chrome()) if __name__ == '__main__': go.run() go.tearDown() A: It looks like you are creating a new instance of the webdriver.Chrome class when you initialize the About class in this line: go = About(webdriver.Chrome()) This is causing a new Chrome browser to be opened when you create the About object. Instead, you should create the webdriver.Chrome object outside of the About class and pass it to the About class when you create the object. Here is an example of how you can do that: import selenium import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait class About(object): def __init__(self, driver): self.driver = driver def pause(self): time.sleep(1) def run(self): self.driver.get('https://google.com') self.pause() def tearDown(self): self.driver.quit() # Create the webdriver.Chrome object outside of the About class driver = webdriver.Chrome() go = About(driver) if __name__ == '__main__': go.run() go.tearDown() This way, only one instance of the webdriver.Chrome class will be created and only one browser will be opened. When you create the About object, you pass the webdriver.Chrome object to it so that it can be used in the methods of the About class.
Browser opens twice when running script
I'm working on a web driver and I'm trying to implement classes into my code. I had this working but as soon as I turned it into a class my browser started opening twice when I ran the program. It will open a browser, then open the second browser, run the commands and then leave the first browser open. Can any tell me why this is happening? This is just an example of how is is formatted. import selenium import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait class About(object): def __init__(self, driver): self.driver = driver def pause(self): time.sleep(1) def run(self): self.driver.get('https://google.com') self.pause() def tearDown(self): self.driver.quit() go = About(webdriver.Chrome()) if __name__ == '__main__': go.run() go.tearDown()
[ "It looks like you are creating a new instance of the webdriver.Chrome class when you initialize the About class in this line:\ngo = About(webdriver.Chrome())\n\nThis is causing a new Chrome browser to be opened when you create the About object. Instead, you should create the webdriver.Chrome object outside of the About class and pass it to the About class when you create the object. Here is an example of how you can do that:\nimport selenium\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nclass About(object):\n def __init__(self, driver):\n self.driver = driver\n\n def pause(self):\n time.sleep(1)\n\n def run(self):\n self.driver.get('https://google.com')\n self.pause()\n\n def tearDown(self):\n self.driver.quit()\n\n# Create the webdriver.Chrome object outside of the About class\ndriver = webdriver.Chrome()\ngo = About(driver)\n\nif __name__ == '__main__':\n go.run()\n go.tearDown()\n\nThis way, only one instance of the webdriver.Chrome class will be created and only one browser will be opened. When you create the About object, you pass the webdriver.Chrome object to it so that it can be used in the methods of the About class.\n" ]
[ 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_webdriver", "webdriver" ]
stackoverflow_0041432728_google_chrome_python_selenium_selenium_webdriver_webdriver.txt
Q: How to load groovy scripts from within the jar file? I am using groovy to execute a set of groovy scripts, which works fine when the runtime jar is deployed with the webapp and the runtime executes the groovy scripts present under C:\jboss-eap-7.4\bin (java working directory). Due to portability and other constraints now we need to move these groovy scripts as part of the runtime jar and then load and execute these scripts from the class path. Can anyone help in running the groovy scripts present inside the runtime jar file (within the webapp)? The current implementation that executes the groovy scripts from C:\jboss-eap-7.4\bin (java working directory) ** Updated after aswer given by GPT-3** final String PLUGIN_DESCRIPTOR = "Plugins.groovy" final class PluginBootStrapper { private GroovyScriptEngine scriptEngine = null; private GroovyShell shell; private GroovyClassLoader classLoader = null; private final boolean loadFromClasspath; private final List<Plugin> allPlugins = null; private static final Logger logger = LogManager.getLogger(PluginBootStrapper.class); public PluginBootStrapper() { System.out.println("Inside PluginBootStrapper") logger.info("Inside PluginBootStrapper") String pluginsDir = System.getProperty(CSMProperties.endorsed_plugins_dir)//".\\plugins"//System.getProperty(CSMProperties.endorsed_plugins_dir) loadFromClasspath = true shell = new GroovyShell(); //scriptEngine = new GroovyScriptEngine(CommonUtils.getAllDirectories(pluginsDir)) logger.info "Plugins Directory:"+pluginsDir println "Plugins Directory:"+pluginsDir allPlugins = loadDescriptor().invokeMethod("getAllPlugins", null) } private Object loadDescriptor() { Object pluginDescriptor = bootStrapScript(CSMProperties.get(CSMProperties.PLUGIN_DESCRIPTOR)) pluginDescriptor } Object bootStrapScript(String script) { String pluginsDir = System.getProperty(CSMProperties.endorsed_plugins_dir) if (pluginsDir != null) { script = pluginsDir + script } printClassPath(this.class.getClassLoader()) Object pluginScript = null //logger.info "script: "+ script //String path = this.getClass().getClassLoader().getResource(script).toExternalForm() //logger.info "bootStrapScript script "+ script logger.info "bootStrapScript script: "+ script + ", path: "+ new File(script).absolutePath println "bootStrapScript script: "+ script + ", path: "+ new File(script).absolutePath if (this.loadFromClasspath) { pluginScript = new GroovyShell(this.class.getClassLoader()).evaluate(new File(script)); //<-- Line no:60 /* classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); pluginScript = classLoader.parseClass(new File(script)); */ return pluginScript } else { pluginScript = scriptEngine.loadScriptByName(script).newInstance() return pluginScript } return pluginScript } public List<Plugin> getAllPlugins() { return allPlugins } def printClassPath(classLoader) { println "$classLoader" classLoader.getURLs().each {url-> println "- ${url.toString()}" } if (classLoader.parent) { printClassPath(classLoader.parent) } } } CommonUtils.getAllDirectories method public static String[] getAllDirectories(String directory) { logger.info("Inside CommonUtils"+directory) def dir = new File(directory) def dirListing = [] if (dir.exists()) { logger.info "Looking for plugins in "+dir.absolutePath+" directory." dir.eachFileRecurse {file-> if(file.isDirectory()) { dirListing << file.getPath() logger.info "Using "+file.getPath()+" plugin folder." } else { logger.info "Using "+file.getPath()+" plugin file." } } } else { logger.error directory+" folder does not exist. Please provide the plugin files." } dirListing.toArray() as String [] } Test Run Command: java -cp runtime-2.0-jar-with-dependencies.jar;.runtime-2.0-jar-with-dependencies.jar; -Dendorsed_plugins_dir=runtime-2.0-jar-with-dependencies.jar\ com.Main %* Output ** Old Update** At present with the above code, if I place the plugins folder (groovy script) inside the jar, it says it cannot find Plugins.groovy under C:\jboss-eap-7.4\bin folder Screenshot of jar inside war file C:\Users\ricky\Desktop\siperian-mrm.ear\mysupport.war\WEB-INF\lib\runtime.jar\ A: let's assume you have plugins.jar with the following groovy file /a/b/C.groovy def f(x){ println "${this.getClass()} :: ${x}" } option 1 //in this case you don't need plugins.jar to be in classpath //you should detect somehow where the plugins.jar is located for current runtime URL jar = new URL('jar:file:./plugins.jar!/') //jar url must end with !/ def groovyScriptEngine = new GroovyScriptEngine(jar) def C = groovyScriptEngine.loadScriptByName('a/b/C.groovy') def c = C.newInstance() c.f('hello world') option 2 //plugins.jar must be in current classpath //C.groovy must have a `package` header if it's located in /a/b folder: package a.b def C = this.getClass().getClassLoader().loadClass('a.b.C') def c = C.newInstance() c.f('hello world') option 3 //plugins.jar must be in current classpath def url = this.getClass().getClassLoader().getResource('a/b/C.groovy') def gshell = new GroovyShell() def c = gshell.parse(url.toURI()) c.f('hello world') iterating files in jar in theory it's possible to list files inside jar however application server could have restrictions on this. after you got entrypoint - instance of class/script a/b/C.groovy ('Plugins.groovy' in your case), you can get reference to jar and iterate entries: URL jar = c.getClass().protectionDomain.codeSource.location //you don't need this for option #1 JarURLConnection jarConnection = (JarURLConnection)url.openConnection() jarConnection.getJarFile().with{jarFile-> jarFile.entries().each{java.util.jar.JarEntry e-> println e.getName() if(!e.isDirectory()){ //you can load/run script here instead of printing it println '------------------------' println jarFile.getInputStream(e).getText() println '------------------------' } } } A: You can use the GroovyClassLoader to load the groovy scripts from the jar file. GroovyClassLoader classLoader = new GroovyClassLoader(); Class scriptClass = classLoader.parseClass(new File("path/to/script.groovy")); Object scriptInstance = scriptClass.newInstance(); You can also use the GroovyShell to execute the scripts directly from the jar file. GroovyShell shell = new GroovyShell(); Object scriptResult = shell.evaluate(new File("path/to/script.groovy")); A: To execute a Groovy script from within a jar file, first make sure that the script is on the classpath. Do this by adding the jar file that contains the script to the CLASSPATH environment variable or by using the -cp or -classpath option when running the Java command. Once the script is on the classpath, use GroovyClassLoader class: // Get the classloader for the current thread ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // Create a new GroovyClassLoader using the classloader GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader); // Load the Groovy script from the classpath Class groovyClass = groovyClassLoader.parseClass(new File("path/in/jar/to/script.groovy")); // Create a new instance of the script Object groovyObject = groovyClass.newInstance(); // Execute the script groovyObject.run(); This example assumes that the Groovy script is in a file called script.groovy (adjust the path accordingly to the script real location within the jar file). Note that this approach will only work if the script is self-contained and does not depend on any external resources (such as additional libraries or files) that are not already included in the jar file. If the script depends on external resources, make sure that they are also available on the classpath before attempting to execute the script.
How to load groovy scripts from within the jar file?
I am using groovy to execute a set of groovy scripts, which works fine when the runtime jar is deployed with the webapp and the runtime executes the groovy scripts present under C:\jboss-eap-7.4\bin (java working directory). Due to portability and other constraints now we need to move these groovy scripts as part of the runtime jar and then load and execute these scripts from the class path. Can anyone help in running the groovy scripts present inside the runtime jar file (within the webapp)? The current implementation that executes the groovy scripts from C:\jboss-eap-7.4\bin (java working directory) ** Updated after aswer given by GPT-3** final String PLUGIN_DESCRIPTOR = "Plugins.groovy" final class PluginBootStrapper { private GroovyScriptEngine scriptEngine = null; private GroovyShell shell; private GroovyClassLoader classLoader = null; private final boolean loadFromClasspath; private final List<Plugin> allPlugins = null; private static final Logger logger = LogManager.getLogger(PluginBootStrapper.class); public PluginBootStrapper() { System.out.println("Inside PluginBootStrapper") logger.info("Inside PluginBootStrapper") String pluginsDir = System.getProperty(CSMProperties.endorsed_plugins_dir)//".\\plugins"//System.getProperty(CSMProperties.endorsed_plugins_dir) loadFromClasspath = true shell = new GroovyShell(); //scriptEngine = new GroovyScriptEngine(CommonUtils.getAllDirectories(pluginsDir)) logger.info "Plugins Directory:"+pluginsDir println "Plugins Directory:"+pluginsDir allPlugins = loadDescriptor().invokeMethod("getAllPlugins", null) } private Object loadDescriptor() { Object pluginDescriptor = bootStrapScript(CSMProperties.get(CSMProperties.PLUGIN_DESCRIPTOR)) pluginDescriptor } Object bootStrapScript(String script) { String pluginsDir = System.getProperty(CSMProperties.endorsed_plugins_dir) if (pluginsDir != null) { script = pluginsDir + script } printClassPath(this.class.getClassLoader()) Object pluginScript = null //logger.info "script: "+ script //String path = this.getClass().getClassLoader().getResource(script).toExternalForm() //logger.info "bootStrapScript script "+ script logger.info "bootStrapScript script: "+ script + ", path: "+ new File(script).absolutePath println "bootStrapScript script: "+ script + ", path: "+ new File(script).absolutePath if (this.loadFromClasspath) { pluginScript = new GroovyShell(this.class.getClassLoader()).evaluate(new File(script)); //<-- Line no:60 /* classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); pluginScript = classLoader.parseClass(new File(script)); */ return pluginScript } else { pluginScript = scriptEngine.loadScriptByName(script).newInstance() return pluginScript } return pluginScript } public List<Plugin> getAllPlugins() { return allPlugins } def printClassPath(classLoader) { println "$classLoader" classLoader.getURLs().each {url-> println "- ${url.toString()}" } if (classLoader.parent) { printClassPath(classLoader.parent) } } } CommonUtils.getAllDirectories method public static String[] getAllDirectories(String directory) { logger.info("Inside CommonUtils"+directory) def dir = new File(directory) def dirListing = [] if (dir.exists()) { logger.info "Looking for plugins in "+dir.absolutePath+" directory." dir.eachFileRecurse {file-> if(file.isDirectory()) { dirListing << file.getPath() logger.info "Using "+file.getPath()+" plugin folder." } else { logger.info "Using "+file.getPath()+" plugin file." } } } else { logger.error directory+" folder does not exist. Please provide the plugin files." } dirListing.toArray() as String [] } Test Run Command: java -cp runtime-2.0-jar-with-dependencies.jar;.runtime-2.0-jar-with-dependencies.jar; -Dendorsed_plugins_dir=runtime-2.0-jar-with-dependencies.jar\ com.Main %* Output ** Old Update** At present with the above code, if I place the plugins folder (groovy script) inside the jar, it says it cannot find Plugins.groovy under C:\jboss-eap-7.4\bin folder Screenshot of jar inside war file C:\Users\ricky\Desktop\siperian-mrm.ear\mysupport.war\WEB-INF\lib\runtime.jar\
[ "let's assume you have plugins.jar with the following groovy file\n/a/b/C.groovy\ndef f(x){\n println \"${this.getClass()} :: ${x}\"\n}\n\n\noption 1\n//in this case you don't need plugins.jar to be in classpath\n//you should detect somehow where the plugins.jar is located for current runtime\nURL jar = new URL('jar:file:./plugins.jar!/') //jar url must end with !/\ndef groovyScriptEngine = new GroovyScriptEngine(jar)\ndef C = groovyScriptEngine.loadScriptByName('a/b/C.groovy')\ndef c = C.newInstance()\nc.f('hello world')\n\n\noption 2\n//plugins.jar must be in current classpath\n//C.groovy must have a `package` header if it's located in /a/b folder: package a.b\ndef C = this.getClass().getClassLoader().loadClass('a.b.C')\ndef c = C.newInstance()\nc.f('hello world')\n\n\noption 3\n//plugins.jar must be in current classpath\ndef url = this.getClass().getClassLoader().getResource('a/b/C.groovy')\ndef gshell = new GroovyShell()\ndef c = gshell.parse(url.toURI())\nc.f('hello world')\n\n\niterating files in jar\nin theory it's possible to list files inside jar however application server could have restrictions on this.\nafter you got entrypoint - instance of class/script a/b/C.groovy ('Plugins.groovy' in your case), you can get reference to jar and iterate entries:\nURL jar = c.getClass().protectionDomain.codeSource.location //you don't need this for option #1\n\nJarURLConnection jarConnection = (JarURLConnection)url.openConnection()\njarConnection.getJarFile().with{jarFile->\n jarFile.entries().each{java.util.jar.JarEntry e->\n println e.getName()\n if(!e.isDirectory()){\n //you can load/run script here instead of printing it\n println '------------------------'\n println jarFile.getInputStream(e).getText()\n println '------------------------'\n }\n }\n}\n\n", "You can use the GroovyClassLoader to load the groovy scripts from the jar file.\nGroovyClassLoader classLoader = new GroovyClassLoader();\nClass scriptClass = classLoader.parseClass(new File(\"path/to/script.groovy\"));\nObject scriptInstance = scriptClass.newInstance();\n\nYou can also use the GroovyShell to execute the scripts directly from the jar file.\nGroovyShell shell = new GroovyShell();\nObject scriptResult = shell.evaluate(new File(\"path/to/script.groovy\"));\n\n", "To execute a Groovy script from within a jar file, first make sure that the script is on the classpath. Do this by adding the jar file that contains the script to the CLASSPATH environment variable or by using the -cp or -classpath option when running the Java command.\nOnce the script is on the classpath, use GroovyClassLoader class:\n// Get the classloader for the current thread\nClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n\n// Create a new GroovyClassLoader using the classloader\nGroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);\n\n// Load the Groovy script from the classpath\nClass groovyClass = groovyClassLoader.parseClass(new File(\"path/in/jar/to/script.groovy\"));\n\n// Create a new instance of the script\nObject groovyObject = groovyClass.newInstance();\n\n// Execute the script\ngroovyObject.run();\n\nThis example assumes that the Groovy script is in a file called script.groovy (adjust the path accordingly to the script real location within the jar file).\nNote that this approach will only work if the script is self-contained and does not depend on any external resources (such as additional libraries or files) that are not already included in the jar file. If the script depends on external resources, make sure that they are also available on the classpath before attempting to execute the script.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "groovy", "groovyscriptengine", "groovyshell", "java" ]
stackoverflow_0074569226_groovy_groovyscriptengine_groovyshell_java.txt
Q: How to effectively loop through each pixel for saving time with numpy? As you know looping through each pixels and accessing their values with opencv takes too long. As a beginner I'm trying to learn opencv myself when I tried this approach it took me around 7-10 seconds of time to loop through image and perform operations. code is as below original_image = cv2.imread(img_f) image = np.array(original_image) for y in range(image.shape[0]): for x in range(image.shape[1]): # remove grey background if 150 <= image[y, x, 0] <= 180 and \ 150 <= image[y, x, 1] <= 180 and \ 150 <= image[y, x, 2] <= 180: image[y, x, 0] = 0 image[y, x, 1] = 0 image[y, x, 2] = 0 # remove green dashes if image[y, x, 0] == 0 and \ image[y, x, 1] == 169 and \ image[y, x, 2] == 0: image[y, x, 0] = 0 image[y, x, 1] = 0 image[y, x, 2] = 0 in above code i'm just trying to remove grey and green pixel colors. I found similar question asked here but im not able to understand how to use numpy in my usecase as i'm beginner in python and numpy. Any help or suggestion for solving this will be appreciated thanks A: You can take advantage of NumPy's vectorized operations to eliminate all loops which should be much faster. # Remove grey background is_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True) image = np.where(is_grey, 0, image) # Remove green dashes is_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0) is_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end image = np.where(is_green_dash, 0, image) Both invocations of np.where rely on NumPy's broadcasting. A: One way to improve the performance of your code would be to use the cv2.inRange() function to find pixels with the desired colors, and then use the cv2.bitwise_and() function to remove those pixels from the image. This can be done more efficiently than looping through each pixel individually, which can be slow and computationally intensive. Here is an example of how this could be implemented: import cv2 import numpy as np # Read the image original_image = cv2.imread('image.jpg') # Define the colors to be removed as ranges of BGR values grey_min = np.array([150, 150, 150], np.uint8) grey_max = np.array([180, 180, 180], np.uint8) green_min = np.array([0, 0, 0], np.uint8) green_max = np.array([0, 169, 0], np.uint8) # Use inRange() to find pixels with the desired colors grey_mask = cv2.inRange(original_image, grey_min, grey_max) green_mask = cv2.inRange(original_image, green_min, green_max) # Use bitwise_and() to remove the pixels with A: You can apply numpy filtering to image. In your scenario it would be: mask_gray = ( (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180) ) image[mask_gray] = 0 mask_green = ( (image[:, :, 0] == 0) & (image[:, :, 1] == 169) & (image[:, :, 2] == 0) ) image[mask_green] = 0 mask_gray and mask_green here are boolean masks A: If you insist on writing your own loops... You could just use numba. It's a JIT compiler for Python code. from numba import njit @njit def your_function(input): ... return output input = cv.imread(...) # yes this will shadow the builtin of the same name output = your_function(input) The first time you call your_function, it'll take a second to compile. All further calls are blazingly fast.
How to effectively loop through each pixel for saving time with numpy?
As you know looping through each pixels and accessing their values with opencv takes too long. As a beginner I'm trying to learn opencv myself when I tried this approach it took me around 7-10 seconds of time to loop through image and perform operations. code is as below original_image = cv2.imread(img_f) image = np.array(original_image) for y in range(image.shape[0]): for x in range(image.shape[1]): # remove grey background if 150 <= image[y, x, 0] <= 180 and \ 150 <= image[y, x, 1] <= 180 and \ 150 <= image[y, x, 2] <= 180: image[y, x, 0] = 0 image[y, x, 1] = 0 image[y, x, 2] = 0 # remove green dashes if image[y, x, 0] == 0 and \ image[y, x, 1] == 169 and \ image[y, x, 2] == 0: image[y, x, 0] = 0 image[y, x, 1] = 0 image[y, x, 2] = 0 in above code i'm just trying to remove grey and green pixel colors. I found similar question asked here but im not able to understand how to use numpy in my usecase as i'm beginner in python and numpy. Any help or suggestion for solving this will be appreciated thanks
[ "You can take advantage of NumPy's vectorized operations to eliminate all loops which should be much faster.\n# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[..., 1] == 169) & (image[..., 2] == 0)\nis_green_dash = is_green_dash[..., np.newaxis] # append a new dim at the end\nimage = np.where(is_green_dash, 0, image)\n\nBoth invocations of np.where rely on NumPy's broadcasting.\n", "One way to improve the performance of your code would be to use the cv2.inRange() function to find pixels with the desired colors, and then use the cv2.bitwise_and() function to remove those pixels from the image. This can be done more efficiently than looping through each pixel individually, which can be slow and computationally intensive. Here is an example of how this could be implemented:\nimport cv2\nimport numpy as np\n\n# Read the image\noriginal_image = cv2.imread('image.jpg')\n\n# Define the colors to be removed as ranges of BGR values\ngrey_min = np.array([150, 150, 150], np.uint8)\ngrey_max = np.array([180, 180, 180], np.uint8)\ngreen_min = np.array([0, 0, 0], np.uint8)\ngreen_max = np.array([0, 169, 0], np.uint8)\n\n# Use inRange() to find pixels with the desired colors\ngrey_mask = cv2.inRange(original_image, grey_min, grey_max)\ngreen_mask = cv2.inRange(original_image, green_min, green_max)\n\n# Use bitwise_and() to remove the pixels with\n\n", "You can apply numpy filtering to image. In your scenario it would be:\nmask_gray = (\n (150 <= image[:, :, 0]) & (image[:, :, 0] <= 180) & \n (150 <= image[:, :, 1]) & (image[:, :, 1] <= 180) & \n (150 <= image[:, :, 2]) & (image[:, :, 2] <= 180)\n)\n\nimage[mask_gray] = 0\n\nmask_green = (\n (image[:, :, 0] == 0) &\n (image[:, :, 1] == 169) &\n (image[:, :, 2] == 0)\n)\n\nimage[mask_green] = 0\n\nmask_gray and mask_green here are boolean masks\n", "If you insist on writing your own loops...\nYou could just use numba. It's a JIT compiler for Python code.\nfrom numba import njit\n\n@njit\ndef your_function(input):\n ...\n return output\n\ninput = cv.imread(...) # yes this will shadow the builtin of the same name\noutput = your_function(input)\n\nThe first time you call your_function, it'll take a second to compile. All further calls are blazingly fast.\n" ]
[ 3, 1, 0, 0 ]
[]
[]
[ "cv2", "image_processing", "numpy", "python" ]
stackoverflow_0074664212_cv2_image_processing_numpy_python.txt
Q: PullRefreshIndicator overlaps with ScrollableTabRow I'm starting to learn about Jetpack Compose. I put together this app where I explore different day-to-day use cases, each of the feature modules within this project is supposed to tackle different scenarios. One of this feature modules – the chatexample feature module, tries to implement a simple ViewPager where each of the pages is a Fragment, the first page "Messages" is supposed to display a paginated RecyclerView wrapped around a SwipeRefreshLayout. Now, the goal is to implement all this using Jetpack Compose. This is the issue I'm having right now: The PullRefreshIndicator that I'm using to implement the Pull-To-Refresh action works as expected and everything seems pretty straightforward so far, but I cannot figure out why the ProgresBar stays there on top. So far I've tried; Carrying on the Modifier from the parent Scaffold all the way through. Making sure I explicitly set the sizes to fit the max height and width. Add an empty Box in the when statement - but nothing has worked so far, I'm guessing I could just remove the PullRefreshIndicator if I see that the ViewModel isn't supposed to be refreshing, but I don't think that's the right thing to do. To quickly explain the Composables that I'm using here I have: <Surface> <Scaffold> // Set with a topBar <Column> <ScrollableTabRow> <Tab/> // Set for the first "Messages" tab <Tab/> // Set for the second "Dashboard" tab </ScrollableTabRow> <HorizontalPager> // ChatExampleScreen <Box> // A Box set with the pullRefresh modifier // Depending on the ChatExamleViewModel we might pull different composables here </PullRefreshIndicator> </Box> // Another ChatExampleScreen for the second tab </HorizontalPager> </Column> <Scaffold> </Surface> Honestly, I don't get how the PullRefreshIndicator that is in a completely different Composable (ChatExampleScreen) gets to overlap with the ScrollableTabRow that is outside. Hope this makes digesting the UI a bit easier. Any tip, advice, or recommendation is appreciated. Thanks! Edit: Just to be completely clear, what I'm trying to achieve here is to have a PullRefreshIndicator on each page. Something like this: On each page, you pull down, see the ProgressBar appear, and when it is done, it goes away, within the same page. Not overlapping with the tabs above. A: I think there's nothing wrong with the PullRefresh api and the Compose/Accompanist Tab/Pager api being used together, it seems like the PullRefresh is just respecting the placement structure of the layout/container it is put into. Consider this code, no tabs, no pager, just a simple set-up of widgets that is identical to your set-up Column( modifier = Modifier.padding(it) ) { Box( modifier = Modifier .fillMaxWidth() .height(80.dp) .background(Color.Blue) ) val pullRefreshState = rememberPullRefreshState( refreshing = false, onRefresh = { viewModel.fetchMessages() } ) Box( modifier = Modifier.pullRefresh(pullRefreshState) ) { PullRefreshIndicator( modifier = Modifier.align(Alignment.TopCenter), refreshing = false, state = pullRefreshState, ) } } What it looks like. The PullRefresh is placed inside a component(Box) that is placed below another component in a Column vertical placement, and since it's below another widget, its initial position will not be hidden like the image sample. With your set-up, since I noticed that the ViewModel is being shared by the tabs and also the reason why I was confirming if you are decided with your architecture is because the only fix I can think of is moving the PullRefresh up in the sequence of the composable widgets. First changes I made is in your ChatExampleScreen composable, which ended up like this, all PullRefresh components are removed. @Composable fun ChatExampleScreen( chatexampleViewModel: ChatExampleViewModel, modifier: Modifier = Modifier ) { val chatexampleViewModelState by chatexampleViewModel.state.observeAsState() Box( modifier = modifier .fillMaxSize() ) { when (val result = chatexampleViewModelState) { is ChatExampleViewModel.State.SuccessfullyLoadedMessages -> { ChatExampleScreenSuccessfullyLoadedMessages( chatexampleMessages = result.list, modifier = modifier, ) } is ChatExampleViewModel.State.NoMessagesFetched -> { ChatExampleScreenEmptyState( modifier = modifier ) } is ChatExampleViewModel.State.NoInternetConnectivity -> { NoInternetConnectivityScreen( modifier = modifier ) } else -> { // Agus - Do nothing??? Box(modifier = modifier.fillMaxSize()) } } } } and in your Activity I moved all the setContent{…} scope into another function named ChatTabsContent and placed everything inside it including the PullRefresh components. @OptIn(ExperimentalMaterialApi::class) @Composable fun ChatTabsContent( modifier : Modifier = Modifier, viewModel : ChatExampleViewModel ) { val chatexampleViewModelIsLoadingState by viewModel.isLoading.observeAsState() val pullRefreshState = rememberPullRefreshState( refreshing = chatexampleViewModelIsLoadingState == true, onRefresh = { viewModel.fetchMessages() } ) Box( modifier = modifier .pullRefresh(pullRefreshState) ) { Column( Modifier .fillMaxSize() ) { val pagerState = rememberPagerState() ScrollableTabRow( selectedTabIndex = pagerState.currentPage, indicator = { tabPositions -> TabRowDefaults.Indicator( modifier = Modifier.tabIndicatorOffset( currentTabPosition = tabPositions[pagerState.currentPage], ) ) } ) { Tab( selected = pagerState.currentPage == 0, onClick = { }, text = { Text( text = "Messages" ) } ) Tab( selected = pagerState.currentPage == 1, onClick = { }, text = { Text( text = "Dashboard" ) } ) } HorizontalPager( count = 2, state = pagerState, modifier = Modifier.fillMaxWidth(), ) { page -> when (page) { 0 -> { ChatExampleScreen( chatexampleViewModel = viewModel, modifier = Modifier.fillMaxSize() ) } 1 -> { ChatExampleScreen( chatexampleViewModel = viewModel, modifier = Modifier.fillMaxWidth() ) } } } } PullRefreshIndicator( modifier = Modifier.align(Alignment.TopCenter), refreshing = chatexampleViewModelIsLoadingState == true, state = pullRefreshState, ) } } which ended up like this setContent { TheOneAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { TopAppBarSample() } ) { ChatTabsContent( modifier = Modifier.padding(it), viewModel = viewModel ) } } } } Result: Structural changes. <Surface> <Scaffold> // Set with a topBar <Box> <Column> <ScrollableTabRow> <Tab/> // Set for the first "Messages" tab <Tab/> // Set for the second "Dashboard" tab </ScrollableTabRow> <HorizontalPager> <Box/> </HorizontalPager> </Column> // pull refresh is now at the most "z" index of the // box, overlapping the content (tabs/pager) <PullRefreshIndicator/> </Box> <Scaffold> </Surface> I haven't explored this API yet, but it looks like it should be used directly in a z-oriented layout/container parent such as Box as the last child. A: I want to leave my first answer as I feel it will still be useful to future readers, so heres another one you might consider. But apologies since I wasn't able to modify your current code, I decided to make a short working example. All of these are copy-and-paste-able. I also tried to keep it as closely identical to your own implementation as possible. Though there are slight differences such as one of the Box has a scroll modifier, because according to the Accompanist Docs and the actual functionality. … The content needs to be 'vertically scrollable' for SwipeRefresh() to be able to react to swipe gestures. Layouts such as LazyColumn are automatically vertically scrollable, but others such as Column or LazyRow are not. In those instances, you can provide a Modifier.verticalScroll modifier… It's from accompanist documentation about the migration of the API but it still applies to this current one in compose framework. The way I understand it is a scroll event should be present for the PullRefresh to get activated manually. I also changed the viewmodel components from LiveData to StateFlows. Activity: class PullRefreshActivity: ComponentActivity() { private val viewModel: MyViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Scaffold( modifier = Modifier.fillMaxSize(), topBar = { TopAppBarSample() } ) { MyScreen( modifier = Modifier.padding(it), viewModel = viewModel ) } } } } } } Some data classes: data class MessageItems( val message: String = "", val author: String = "" ) data class DashboardBanner( val bannerMessage: String = "", val content: String = "" ) ViewModel: class MyViewModel: ViewModel() { var isLoading by mutableStateOf(false) private val _messageState = MutableStateFlow(mutableStateListOf<MessageItems>()) val messageState = _messageState.asStateFlow() private val _dashboardState = MutableStateFlow(DashboardBanner()) val dashboardState = _dashboardState.asStateFlow() fun fetchMessages() { viewModelScope.launch { isLoading = true delay(2000L) _messageState.update { it.add( MessageItems( message = "Hello First Message", author = "Author 1" ), ) it.add( MessageItems( message = "Hello Second Message", author = "Author 2" ) ) it } isLoading = false } } fun fetchDashboard() { viewModelScope.launch { isLoading = true delay(2000L) _dashboardState.update { it.copy( bannerMessage = "Hello World!!", content = "Welcome to Pull Refresh Content!" ) } isLoading = false } } } Tab Screen Composables: @Composable fun MessageTab( myViewModel : MyViewModel ) { val messages by myViewModel.messageState.collectAsState() LazyColumn( modifier = Modifier.fillMaxSize() ) { items(messages) { item -> Column( modifier = Modifier .fillMaxWidth() .border(BorderStroke(Dp.Hairline, Color.DarkGray)), horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = item.message) Text(text = item.author) } } } } @Composable fun DashboardTab( myViewModel: MyViewModel ) { val banner by myViewModel.dashboardState.collectAsState() Box( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()), contentAlignment = Alignment.Center ) { Column { Text( text = banner.bannerMessage, fontSize = 52.sp ) Text( text = banner.content, fontSize = 16.sp ) } } } and finally the Screen that contains PullRefresh and Pager/Tab components: Edit: I modified the set-up where all the components are direct children of a ConstraintLayout not by a Column anymore. Now the only way to achieve the PullRefresh behind the Tabs but still on top of the HorizontalPager is, first I had to put the HorizontalPager as the first child, the PullRefresh as the second and the Tabs as the last one, constraining them accordingly to preserve its visual arrangement. @OptIn(ExperimentalMaterialApi::class, ExperimentalPagerApi::class) @Composable fun MyScreen( modifier : Modifier = Modifier, viewModel: MyViewModel ) { val refreshing = viewModel.isLoading val pagerState = rememberPagerState() val pullRefreshState = rememberPullRefreshState( refreshing = refreshing, onRefresh = { when (pagerState.currentPage) { 0 -> { viewModel.fetchMessages() } 1 -> { viewModel.fetchDashboard() } } }, refreshingOffset = 100.dp // just an arbitrary offset where the refresh will animate ) ConstraintLayout( modifier = modifier .fillMaxSize() .pullRefresh(pullRefreshState) ) { val (pager, pullRefresh, tabs) = createRefs() HorizontalPager( count = 2, state = pagerState, modifier = Modifier.constrainAs(pager) { top.linkTo(tabs.bottom) start.linkTo(parent.start) end.linkTo(parent.end) bottom.linkTo(parent.bottom) height = Dimension.fillToConstraints } ) { page -> when (page) { 0 -> { MessageTab( myViewModel = viewModel ) } 1 -> { DashboardTab( myViewModel = viewModel ) } } } PullRefreshIndicator( modifier = Modifier.constrainAs(pullRefresh) { top.linkTo(parent.top) start.linkTo(parent.start) end.linkTo(parent.end) }, refreshing = refreshing, state = pullRefreshState, ) ScrollableTabRow( modifier = Modifier.constrainAs(tabs) { top.linkTo(parent.top) start.linkTo(parent.start) end.linkTo(parent.end) }, selectedTabIndex = pagerState.currentPage, indicator = { tabPositions -> TabRowDefaults.Indicator( modifier = Modifier.tabIndicatorOffset( currentTabPosition = tabPositions[pagerState.currentPage], ) ) }, ) { Tab( selected = pagerState.currentPage == 0, onClick = {}, text = { Text( text = "Messages" ) } ) Tab( selected = pagerState.currentPage == 1, onClick = {}, text = { Text( text = "Dashboard" ) } ) } } } output: <Surface> <Scaffold> <ConstraintLayout> // top to ScrollableTabRow's bottom // start, end, bottom to parent's start, end and bottom // 0.dp (view), fillToConstraints (compose) <HorizontalPager> <PagerScreens/> </HorizontalPager> // top, start, end of parent <PullRefreshIndicator/> // top, start and end of parent <ScrollableTabRow> <Tab/> // Set for the first "Messages" tab <Tab/> // Set for the second "Dashboard" tab </ScrollableTabRow> </ConstraintLayout> <Scaffold> </Surface> A: I just want to share more details about the issue here and what the solution is. I appreciate a lot the solutions shared above and these were definitely key to figuring the problem out. The bare-minimum solution here is to replace the Box with a ConstraintLayout in the ChatScreenExample composable: Why? Because as @z.y shared above the PullRefreshIndicator needs to be contained on a "vertically scrollable" composable, and while the Box composable can be set with the vericalScroll() modifier we need to make sure we constraint the height of the content, that's why we had to change to a ConstraintLayout. Feel free to correct me if I'm missing something.
PullRefreshIndicator overlaps with ScrollableTabRow
I'm starting to learn about Jetpack Compose. I put together this app where I explore different day-to-day use cases, each of the feature modules within this project is supposed to tackle different scenarios. One of this feature modules – the chatexample feature module, tries to implement a simple ViewPager where each of the pages is a Fragment, the first page "Messages" is supposed to display a paginated RecyclerView wrapped around a SwipeRefreshLayout. Now, the goal is to implement all this using Jetpack Compose. This is the issue I'm having right now: The PullRefreshIndicator that I'm using to implement the Pull-To-Refresh action works as expected and everything seems pretty straightforward so far, but I cannot figure out why the ProgresBar stays there on top. So far I've tried; Carrying on the Modifier from the parent Scaffold all the way through. Making sure I explicitly set the sizes to fit the max height and width. Add an empty Box in the when statement - but nothing has worked so far, I'm guessing I could just remove the PullRefreshIndicator if I see that the ViewModel isn't supposed to be refreshing, but I don't think that's the right thing to do. To quickly explain the Composables that I'm using here I have: <Surface> <Scaffold> // Set with a topBar <Column> <ScrollableTabRow> <Tab/> // Set for the first "Messages" tab <Tab/> // Set for the second "Dashboard" tab </ScrollableTabRow> <HorizontalPager> // ChatExampleScreen <Box> // A Box set with the pullRefresh modifier // Depending on the ChatExamleViewModel we might pull different composables here </PullRefreshIndicator> </Box> // Another ChatExampleScreen for the second tab </HorizontalPager> </Column> <Scaffold> </Surface> Honestly, I don't get how the PullRefreshIndicator that is in a completely different Composable (ChatExampleScreen) gets to overlap with the ScrollableTabRow that is outside. Hope this makes digesting the UI a bit easier. Any tip, advice, or recommendation is appreciated. Thanks! Edit: Just to be completely clear, what I'm trying to achieve here is to have a PullRefreshIndicator on each page. Something like this: On each page, you pull down, see the ProgressBar appear, and when it is done, it goes away, within the same page. Not overlapping with the tabs above.
[ "I think there's nothing wrong with the PullRefresh api and the Compose/Accompanist Tab/Pager api being used together, it seems like the PullRefresh is just respecting the placement structure of the layout/container it is put into.\nConsider this code, no tabs, no pager, just a simple set-up of widgets that is identical to your set-up\nColumn(\n modifier = Modifier.padding(it)\n ) {\n\n Box(\n modifier = Modifier\n .fillMaxWidth()\n .height(80.dp)\n .background(Color.Blue)\n )\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = false,\n onRefresh = { viewModel.fetchMessages() }\n )\n\n Box(\n modifier = Modifier.pullRefresh(pullRefreshState)\n ) {\n\n PullRefreshIndicator(\n modifier = Modifier.align(Alignment.TopCenter),\n refreshing = false,\n state = pullRefreshState,\n )\n }\n }\n\nWhat it looks like.\n\nThe PullRefresh is placed inside a component(Box) that is placed below another component in a Column vertical placement, and since it's below another widget, its initial position will not be hidden like the image sample.\nWith your set-up, since I noticed that the ViewModel is being shared by the tabs and also the reason why I was confirming if you are decided with your architecture is because the only fix I can think of is moving the PullRefresh up in the sequence of the composable widgets.\nFirst changes I made is in your ChatExampleScreen composable, which ended up like this, all PullRefresh components are removed.\n@Composable\nfun ChatExampleScreen(\n chatexampleViewModel: ChatExampleViewModel,\n modifier: Modifier = Modifier\n) {\n val chatexampleViewModelState by chatexampleViewModel.state.observeAsState()\n\n Box(\n modifier = modifier\n .fillMaxSize()\n ) {\n\n when (val result = chatexampleViewModelState) {\n is ChatExampleViewModel.State.SuccessfullyLoadedMessages -> {\n ChatExampleScreenSuccessfullyLoadedMessages(\n chatexampleMessages = result.list,\n modifier = modifier,\n )\n }\n is ChatExampleViewModel.State.NoMessagesFetched -> {\n ChatExampleScreenEmptyState(\n modifier = modifier\n )\n }\n is ChatExampleViewModel.State.NoInternetConnectivity -> {\n NoInternetConnectivityScreen(\n modifier = modifier\n )\n }\n else -> {\n // Agus - Do nothing???\n Box(modifier = modifier.fillMaxSize())\n }\n }\n }\n}\n\nand in your Activity I moved all the setContent{…} scope into another function named ChatTabsContent and placed everything inside it including the PullRefresh components.\n@OptIn(ExperimentalMaterialApi::class)\n@Composable\nfun ChatTabsContent(\n modifier : Modifier = Modifier,\n viewModel : ChatExampleViewModel\n) {\n val chatexampleViewModelIsLoadingState by viewModel.isLoading.observeAsState()\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = chatexampleViewModelIsLoadingState == true,\n onRefresh = { viewModel.fetchMessages() }\n )\n\n Box(\n modifier = modifier\n .pullRefresh(pullRefreshState)\n ) {\n\n Column(\n Modifier\n .fillMaxSize()\n ) {\n val pagerState = rememberPagerState()\n\n ScrollableTabRow(\n selectedTabIndex = pagerState.currentPage,\n indicator = { tabPositions ->\n TabRowDefaults.Indicator(\n modifier = Modifier.tabIndicatorOffset(\n currentTabPosition = tabPositions[pagerState.currentPage],\n )\n )\n }\n ) {\n Tab(\n selected = pagerState.currentPage == 0,\n onClick = { },\n text = {\n Text(\n text = \"Messages\"\n )\n }\n )\n Tab(\n selected = pagerState.currentPage == 1,\n onClick = { },\n text = {\n Text(\n text = \"Dashboard\"\n )\n }\n )\n }\n\n HorizontalPager(\n count = 2,\n state = pagerState,\n modifier = Modifier.fillMaxWidth(),\n ) { page ->\n when (page) {\n 0 -> {\n ChatExampleScreen(\n chatexampleViewModel = viewModel,\n modifier = Modifier.fillMaxSize()\n )\n }\n 1 -> {\n ChatExampleScreen(\n chatexampleViewModel = viewModel,\n modifier = Modifier.fillMaxWidth()\n )\n }\n }\n }\n }\n\n PullRefreshIndicator(\n modifier = Modifier.align(Alignment.TopCenter),\n refreshing = chatexampleViewModelIsLoadingState == true,\n state = pullRefreshState,\n )\n }\n}\n\nwhich ended up like this\n setContent {\n TheOneAppTheme {\n // A surface container using the 'background' color from the theme\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Scaffold(\n modifier = Modifier.fillMaxSize(),\n topBar = { TopAppBarSample() }\n ) {\n\n ChatTabsContent(\n modifier = Modifier.padding(it),\n viewModel = viewModel\n )\n }\n }\n }\n }\n\nResult:\n\nStructural changes.\n<Surface>\n <Scaffold> // Set with a topBar\n <Box>\n <Column>\n <ScrollableTabRow>\n <Tab/> // Set for the first \"Messages\" tab\n <Tab/> // Set for the second \"Dashboard\" tab\n </ScrollableTabRow>\n <HorizontalPager>\n <Box/>\n </HorizontalPager>\n </Column>\n\n // pull refresh is now at the most \"z\" index of the \n // box, overlapping the content (tabs/pager)\n <PullRefreshIndicator/> \n </Box>\n <Scaffold>\n</Surface>\n\nI haven't explored this API yet, but it looks like it should be used directly in a z-oriented layout/container parent such as Box as the last child.\n", "I want to leave my first answer as I feel it will still be useful to future readers, so heres another one you might consider.\nBut apologies since I wasn't able to modify your current code, I decided to make a short working example. All of these are copy-and-paste-able. I also tried to keep it as closely identical to your own implementation as possible.\nThough there are slight differences such as one of the Box has a scroll modifier, because according to the Accompanist Docs and the actual functionality.\n\n… The content needs to be 'vertically scrollable' for SwipeRefresh()\nto be able to react to swipe gestures. Layouts such as LazyColumn are\nautomatically vertically scrollable, but others such as Column or\nLazyRow are not. In those instances, you can provide a\nModifier.verticalScroll modifier…\n\nIt's from accompanist documentation about the migration of the API but it still applies to this current one in compose framework.\nThe way I understand it is a scroll event should be present for the PullRefresh to get activated manually.\nI also changed the viewmodel components from LiveData to StateFlows.\nActivity:\nclass PullRefreshActivity: ComponentActivity() {\n\n private val viewModel: MyViewModel by viewModels()\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContent {\n MyAppTheme {\n Surface(\n modifier = Modifier.fillMaxSize(),\n color = MaterialTheme.colors.background\n ) {\n Scaffold(\n modifier = Modifier.fillMaxSize(),\n topBar = { TopAppBarSample() }\n ) {\n MyScreen(\n modifier = Modifier.padding(it),\n viewModel = viewModel\n )\n }\n }\n }\n }\n }\n}\n\nSome data classes:\ndata class MessageItems(\n val message: String = \"\",\n val author: String = \"\"\n)\n\ndata class DashboardBanner(\n val bannerMessage: String = \"\",\n val content: String = \"\"\n)\n\nViewModel:\nclass MyViewModel: ViewModel() {\n\n var isLoading by mutableStateOf(false)\n\n private val _messageState = MutableStateFlow(mutableStateListOf<MessageItems>())\n val messageState = _messageState.asStateFlow()\n\n private val _dashboardState = MutableStateFlow(DashboardBanner())\n val dashboardState = _dashboardState.asStateFlow()\n\n fun fetchMessages() {\n\n viewModelScope.launch {\n isLoading = true\n\n delay(2000L)\n\n _messageState.update {\n it.add(\n MessageItems(\n message = \"Hello First Message\",\n author = \"Author 1\"\n ),\n )\n it.add(\n MessageItems(\n message = \"Hello Second Message\",\n author = \"Author 2\"\n )\n )\n\n it\n }\n isLoading = false\n }\n }\n\n fun fetchDashboard() {\n\n viewModelScope.launch {\n isLoading = true\n\n delay(2000L)\n\n _dashboardState.update {\n it.copy(\n bannerMessage = \"Hello World!!\",\n content = \"Welcome to Pull Refresh Content!\"\n )\n }\n isLoading = false\n }\n }\n}\n\nTab Screen Composables:\n@Composable\nfun MessageTab(\n myViewModel : MyViewModel\n) {\n val messages by myViewModel.messageState.collectAsState()\n\n LazyColumn(\n modifier = Modifier.fillMaxSize()\n ) {\n items(messages) { item ->\n Column(\n modifier = Modifier\n .fillMaxWidth()\n .border(BorderStroke(Dp.Hairline, Color.DarkGray)),\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n Text(text = item.message)\n Text(text = item.author)\n }\n }\n }\n}\n\n@Composable\nfun DashboardTab(\n myViewModel: MyViewModel\n) {\n\n val banner by myViewModel.dashboardState.collectAsState()\n\n Box(\n modifier = Modifier\n .fillMaxSize()\n .verticalScroll(rememberScrollState()),\n contentAlignment = Alignment.Center\n ) {\n Column {\n Text(\n text = banner.bannerMessage,\n fontSize = 52.sp\n )\n\n Text(\n text = banner.content,\n fontSize = 16.sp\n )\n }\n }\n}\n\nand finally the Screen that contains PullRefresh and Pager/Tab components:\nEdit: I modified the set-up where all the components are direct children of a ConstraintLayout not by a Column anymore. Now the only way to achieve the PullRefresh behind the Tabs but still on top of the HorizontalPager is, first I had to put the HorizontalPager as the first child, the PullRefresh as the second and the Tabs as the last one, constraining them accordingly to preserve its visual arrangement.\n@OptIn(ExperimentalMaterialApi::class, ExperimentalPagerApi::class)\n@Composable\nfun MyScreen(\n modifier : Modifier = Modifier,\n viewModel: MyViewModel\n) {\n val refreshing = viewModel.isLoading\n val pagerState = rememberPagerState()\n\n val pullRefreshState = rememberPullRefreshState(\n refreshing = refreshing,\n onRefresh = {\n when (pagerState.currentPage) {\n 0 -> {\n viewModel.fetchMessages()\n }\n 1 -> {\n viewModel.fetchDashboard()\n }\n }\n },\n refreshingOffset = 100.dp // just an arbitrary offset where the refresh will animate\n )\n\n ConstraintLayout(\n modifier = modifier\n .fillMaxSize()\n .pullRefresh(pullRefreshState)\n ) {\n val (pager, pullRefresh, tabs) = createRefs()\n\n HorizontalPager(\n count = 2,\n state = pagerState,\n modifier = Modifier.constrainAs(pager) {\n top.linkTo(tabs.bottom)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n bottom.linkTo(parent.bottom)\n height = Dimension.fillToConstraints\n }\n ) { page ->\n when (page) {\n 0 -> {\n MessageTab(\n myViewModel = viewModel\n )\n }\n 1 -> {\n DashboardTab(\n myViewModel = viewModel\n )\n }\n }\n }\n\n PullRefreshIndicator(\n modifier = Modifier.constrainAs(pullRefresh) {\n top.linkTo(parent.top)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n },\n refreshing = refreshing,\n state = pullRefreshState,\n )\n\n ScrollableTabRow(\n modifier = Modifier.constrainAs(tabs) {\n top.linkTo(parent.top)\n start.linkTo(parent.start)\n end.linkTo(parent.end)\n },\n selectedTabIndex = pagerState.currentPage,\n indicator = { tabPositions ->\n TabRowDefaults.Indicator(\n modifier = Modifier.tabIndicatorOffset(\n currentTabPosition = tabPositions[pagerState.currentPage],\n )\n )\n },\n ) {\n Tab(\n selected = pagerState.currentPage == 0,\n onClick = {},\n text = {\n Text(\n text = \"Messages\"\n )\n }\n )\n\n Tab(\n selected = pagerState.currentPage == 1,\n onClick = {},\n text = {\n Text(\n text = \"Dashboard\"\n )\n }\n )\n }\n }\n}\n\noutput:\n\n<Surface>\n <Scaffold>\n <ConstraintLayout>\n\n // top to ScrollableTabRow's bottom\n // start, end, bottom to parent's start, end and bottom\n // 0.dp (view), fillToConstraints (compose)\n <HorizontalPager>\n <PagerScreens/>\n </HorizontalPager>\n\n // top, start, end of parent\n <PullRefreshIndicator/>\n\n // top, start and end of parent\n <ScrollableTabRow>\n <Tab/> // Set for the first \"Messages\" tab\n <Tab/> // Set for the second \"Dashboard\" tab\n </ScrollableTabRow>\n </ConstraintLayout>\n <Scaffold>\n</Surface>\n\n", "I just want to share more details about the issue here and what the solution is. I appreciate a lot the solutions shared above and these were definitely key to figuring the problem out.\nThe bare-minimum solution here is to replace the Box with a ConstraintLayout in the ChatScreenExample composable:\n\nWhy? Because as @z.y shared above the PullRefreshIndicator needs to be contained on a \"vertically scrollable\" composable, and while the Box composable can be set with the vericalScroll() modifier we need to make sure we constraint the height of the content, that's why we had to change to a ConstraintLayout.\nFeel free to correct me if I'm missing something.\n" ]
[ 3, 3, 2 ]
[]
[]
[ "android", "android_jetpack_compose", "android_scrollable_tabs", "pager", "pull_to_refresh" ]
stackoverflow_0074594418_android_android_jetpack_compose_android_scrollable_tabs_pager_pull_to_refresh.txt
Q: how to check if a line contains text and then stop after it reaches a blank line? [Python] am writing this algorithm that takes strings from a text file and appends them to an array. if the strings are in continuous line ex. ABCD EFG HIJK LMNOP then they would be appended into the same array until it reaches a blank line at which point it stops and starts appending the next number of continuous arrays to a different array. In my head a for loop is the way to go as i have the number of lines but i am just not sure how to check if a line has ANY TYPE of text or not (Not looking for any substrings just checking if the line itself contains anything). A: Simply check if the current line equal the new line character. with open('filename.txt', 'r') as f: for line in f: if line == '\n': print('Empty line') else: print('line contain string') A: If you're stripping the linebreak off each line, you can just check afterward to see if the result is empty. Given the following file text.txt: ABCD EFG HIJK LMNOP QRSTUV WXYZ here's an example of reading it into a list of lists of strings: >>> arr = [[]] >>> with open("text.txt") as f: ... for line in f: ... line = line.strip() ... if line: ... arr[-1].append(line) ... else: ... arr.append([]) ... >>> arr [['ABCD', 'EFG', 'HIJK', 'LMNOP'], ['QRSTUV', 'WXYZ']]
how to check if a line contains text and then stop after it reaches a blank line? [Python]
am writing this algorithm that takes strings from a text file and appends them to an array. if the strings are in continuous line ex. ABCD EFG HIJK LMNOP then they would be appended into the same array until it reaches a blank line at which point it stops and starts appending the next number of continuous arrays to a different array. In my head a for loop is the way to go as i have the number of lines but i am just not sure how to check if a line has ANY TYPE of text or not (Not looking for any substrings just checking if the line itself contains anything).
[ "Simply check if the current line equal the new line character.\nwith open('filename.txt', 'r') as f:\n for line in f:\n if line == '\\n':\n print('Empty line')\n else:\n print('line contain string')\n\n", "If you're stripping the linebreak off each line, you can just check afterward to see if the result is empty. Given the following file text.txt:\nABCD\nEFG\nHIJK\nLMNOP\n\nQRSTUV\nWXYZ\n\nhere's an example of reading it into a list of lists of strings:\n>>> arr = [[]]\n>>> with open(\"text.txt\") as f:\n... for line in f:\n... line = line.strip()\n... if line:\n... arr[-1].append(line)\n... else:\n... arr.append([])\n...\n>>> arr\n[['ABCD', 'EFG', 'HIJK', 'LMNOP'], ['QRSTUV', 'WXYZ']]\n\n" ]
[ 0, 0 ]
[]
[]
[ "file", "python", "txt" ]
stackoverflow_0074671373_file_python_txt.txt
Q: Create multicategory chart by python I have the data like the following in excel: company month-year #people got interviewed # people employed link to the data: (https://docs.google.com/spreadsheets/d/1DwZt9fpnzR9yUNBMjmqA1hg11d-2dXNs/edit?usp=share_link&ouid=113997824301423906122&rtpof=true&sd=true) when I try to create multicategory chart(company as first category and the year-month as second category) by plotly library by python it mixes up the order of second category for y,z company. Putting the code and the screenshot of the chart below. Code : import pandas as pd from helper_functions import get_df import plotly.graph_objects as go from datetime import datetime def multicat_chart(infile=None, sheet_name=None, chart_type = None, chart_title = None): #chart type must be given df=pd.read_excel(infile,sheet_name) df = df.fillna(method='ffill') cat = df.columns[0] sub_cat = df.columns[1] cols = df.columns[2:] fig = go.Figure() cats = [] sub_cats = [] for c in df[cat].unique(): new_df = df.loc[df[cat] == c] scats = new_df[sub_cat] scats = scats.apply(lambda date: datetime.strptime(date, "%b-%Y")) scats = list(scats) scats.sort() scats = [datetime.strftime(element, '%b-%y') for element in scats] scats = [str(element) for element in scats] for sc in scats: cats.append(str(c)) sub_cats.append(str(sc)) print(c) for i in scats: print(i) fig.add_trace( go.Bar(x = [cats,sub_cats],y = df[cols[0]], name="# people got interviewed" )) fig.add_trace( go.Bar(x = [cats,sub_cats],y = df[cols[1]], name="# people employed" )) fig.update_layout(width = 1000, height = 1000) return fig fig = multicat_chart(infile = 'data_for_test.xlsx', sheet_name = 'data', chart_type = 'bar') fig.show() Chart: I gave the data to the Bar() function in ordered way but it mixes somehow, I would like to have in ascending order, what I did I convert string to datetime object and then sorted all subcategory data with the sort() function of list, and converted back to string. And By running the script you can notice that it prints in the right order, it means that it is given ordered to function, but it mixes, who can help me to understand why it behaves so? A: Once you made the dates month-year, they were object type--character strings, not dates—as in date-type. When you sorted, you sorted by calendar month. First, use strptime to make it a date, sort it, then use strftime. import pandas as pd import plotly.graph_objects as go from datetime import datetime as dt def multicat_chart(infile=None, sheet_name=None, chart_type = None, chart_title = None): #chart type must be given df = pd.read_excel(infile, sheet_name) df = df.fillna(method='ffill') # fill in companies df['month'] = [dt.strptime(x, '%b-%Y') for x in df['month']] # date for ordering df.sort_values(by = ['month', 'company'], inplace = True) # appearance order df['month2'] = [dt.strftime(x, '%b-%Y') for x in df['month']] # visual appearance fig = go.Figure() # plot it fig.add_trace( go.Bar(x = [df.iloc[:, 0], df.iloc[:, 4]], y = df.iloc[:, 2], name="# people got interviewed" )) fig.add_trace( go.Bar(x = [df.iloc[:, 0], df.iloc[:, 4]], y = df.iloc[:, 3], name="# people employed" )) fig.update_layout(width = 1000, height = 1000) return fig You had a lot of extra work going on in your function; I cut a lot of that out because you didn't need it. If you have any questions, let me know!
Create multicategory chart by python
I have the data like the following in excel: company month-year #people got interviewed # people employed link to the data: (https://docs.google.com/spreadsheets/d/1DwZt9fpnzR9yUNBMjmqA1hg11d-2dXNs/edit?usp=share_link&ouid=113997824301423906122&rtpof=true&sd=true) when I try to create multicategory chart(company as first category and the year-month as second category) by plotly library by python it mixes up the order of second category for y,z company. Putting the code and the screenshot of the chart below. Code : import pandas as pd from helper_functions import get_df import plotly.graph_objects as go from datetime import datetime def multicat_chart(infile=None, sheet_name=None, chart_type = None, chart_title = None): #chart type must be given df=pd.read_excel(infile,sheet_name) df = df.fillna(method='ffill') cat = df.columns[0] sub_cat = df.columns[1] cols = df.columns[2:] fig = go.Figure() cats = [] sub_cats = [] for c in df[cat].unique(): new_df = df.loc[df[cat] == c] scats = new_df[sub_cat] scats = scats.apply(lambda date: datetime.strptime(date, "%b-%Y")) scats = list(scats) scats.sort() scats = [datetime.strftime(element, '%b-%y') for element in scats] scats = [str(element) for element in scats] for sc in scats: cats.append(str(c)) sub_cats.append(str(sc)) print(c) for i in scats: print(i) fig.add_trace( go.Bar(x = [cats,sub_cats],y = df[cols[0]], name="# people got interviewed" )) fig.add_trace( go.Bar(x = [cats,sub_cats],y = df[cols[1]], name="# people employed" )) fig.update_layout(width = 1000, height = 1000) return fig fig = multicat_chart(infile = 'data_for_test.xlsx', sheet_name = 'data', chart_type = 'bar') fig.show() Chart: I gave the data to the Bar() function in ordered way but it mixes somehow, I would like to have in ascending order, what I did I convert string to datetime object and then sorted all subcategory data with the sort() function of list, and converted back to string. And By running the script you can notice that it prints in the right order, it means that it is given ordered to function, but it mixes, who can help me to understand why it behaves so?
[ "Once you made the dates month-year, they were object type--character strings, not dates—as in date-type. When you sorted, you sorted by calendar month.\nFirst, use strptime to make it a date, sort it, then use strftime.\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom datetime import datetime as dt\n\ndef multicat_chart(infile=None, sheet_name=None, chart_type = None, chart_title = None):\n \n #chart type must be given\n df = pd.read_excel(infile, sheet_name)\n df = df.fillna(method='ffill') # fill in companies\n\n df['month'] = [dt.strptime(x, '%b-%Y') for x in df['month']] # date for ordering\n df.sort_values(by = ['month', 'company'], inplace = True) # appearance order\n df['month2'] = [dt.strftime(x, '%b-%Y') for x in df['month']] # visual appearance\n fig = go.Figure() # plot it\n fig.add_trace( go.Bar(x = [df.iloc[:, 0], df.iloc[:, 4]], \n y = df.iloc[:, 2], name=\"# people got interviewed\" ))\n fig.add_trace( go.Bar(x = [df.iloc[:, 0], df.iloc[:, 4]], \n y = df.iloc[:, 3], name=\"# people employed\" ))\n fig.update_layout(width = 1000, height = 1000)\n return fig\n\n\n\nYou had a lot of extra work going on in your function; I cut a lot of that out because you didn't need it.\nIf you have any questions, let me know!\n" ]
[ 0 ]
[]
[]
[ "linux", "plotly", "python" ]
stackoverflow_0074625714_linux_plotly_python.txt
Q: Change colour of JTable Header Column sorter arrow icons How do I custom the colours of a JTable? The default arrow icons used to show the sorting direction of a column header in my JTable are hard to see since they are the same colour as the background. A: I know it's been a while, however I think this information may be useful to other people in the future, I clarify that I found this solution right here on stackoverflow and I adapted it to give you the most complete solution possible, I hope you serve: import java.awt.BorderLayout; import java.awt.Component; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.RowSorter.SortKey; import javax.swing.SortOrder; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; public class TestTableSortIcon extends JPanel { private String[] columnNames = {"Country", "Capital", "Population in Millions", "Democracy"}; private Object[][] data = { {"USA", "Washington DC", 280, true}, {"Canada", "Ottawa", 32, true}, {"United Kingdom", "London", 60, true}, {"Germany", "Berlin", 83, true}, {"France", "Paris", 60, true}, {"Norway", "Oslo", 4.5, true}, {"India", "New Delhi", 1046, true} }; ImageIcon ascendingIcon= new ImageIcon("src/icons/ascendingIcon.png"); ImageIcon descendingIcon= new ImageIcon("src/icons/descendingIcon.png"); private DefaultTableModel model = new DefaultTableModel(data, columnNames); private JTable table = new JTable(model); final TableCellRenderer r = table.getTableHeader().getDefaultRenderer(); TableCellRenderer wrapper; private TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(table.getModel()); public TestTableSortIcon() { table.setRowSorter(rowSorter); wrapper = new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = r.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (comp instanceof JLabel) { JLabel label = (JLabel) comp; label.setIcon(getSortIcon(table, column)); } return comp; } /** * Implements the logic to choose the appropriate icon. */ private ImageIcon getSortIcon(JTable table, int column) { SortOrder sortOrder = getColumnSortOrder(table, column); if (SortOrder.UNSORTED == sortOrder) { return null; } return SortOrder.ASCENDING == sortOrder ? ascendingIcon : descendingIcon; } private SortOrder getColumnSortOrder(JTable table, int column) { if (table == null || table.getRowSorter() == null) { return SortOrder.UNSORTED; } List<? extends SortKey> keys = table.getRowSorter().getSortKeys(); if (keys.size() > 0) { SortKey key = keys.get(0); if (key.getColumn() == table.convertColumnIndexToModel(column)) { return key.getSortOrder(); } } return SortOrder.UNSORTED; } }; table.getTableHeader().setDefaultRenderer(wrapper); setLayout(new BorderLayout()); add(new JScrollPane(table), BorderLayout.CENTER); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame("Row Filter"); frame.add(new TestTableSortIcon()); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
Change colour of JTable Header Column sorter arrow icons
How do I custom the colours of a JTable? The default arrow icons used to show the sorting direction of a column header in my JTable are hard to see since they are the same colour as the background.
[ "I know it's been a while, however I think this information may be useful to other people in the future, I clarify that I found this solution right here on stackoverflow and I adapted it to give you the most complete solution possible, I hope you serve:\n import java.awt.BorderLayout;\n import java.awt.Component;\n import java.util.List;\n import javax.swing.ImageIcon;\n import javax.swing.JFrame;\n import javax.swing.JLabel;\n import javax.swing.JPanel;\n import javax.swing.JScrollPane;\n import javax.swing.JTable;\n import javax.swing.RowSorter.SortKey;\n import javax.swing.SortOrder;\n import javax.swing.SwingUtilities;\n import javax.swing.table.DefaultTableModel;\n import javax.swing.table.TableCellRenderer;\n import javax.swing.table.TableModel;\n import javax.swing.table.TableRowSorter;\n\n public class TestTableSortIcon extends JPanel {\n\n private String[] columnNames\n = {\"Country\", \"Capital\", \"Population in Millions\", \"Democracy\"};\n\n private Object[][] data = {\n {\"USA\", \"Washington DC\", 280, true},\n {\"Canada\", \"Ottawa\", 32, true},\n {\"United Kingdom\", \"London\", 60, true},\n {\"Germany\", \"Berlin\", 83, true},\n {\"France\", \"Paris\", 60, true},\n {\"Norway\", \"Oslo\", 4.5, true},\n {\"India\", \"New Delhi\", 1046, true}\n };\n\n ImageIcon ascendingIcon= new ImageIcon(\"src/icons/ascendingIcon.png\");\n ImageIcon descendingIcon= new ImageIcon(\"src/icons/descendingIcon.png\");\n\n private DefaultTableModel model = new DefaultTableModel(data, columnNames);\n private JTable table = new JTable(model);\n\n final TableCellRenderer r = table.getTableHeader().getDefaultRenderer();\n TableCellRenderer wrapper;\n\n private TableRowSorter<TableModel> rowSorter\n = new TableRowSorter<>(table.getModel());\n\n public TestTableSortIcon() {\n table.setRowSorter(rowSorter); \n wrapper = new TableCellRenderer() {\n\n @Override\n public Component getTableCellRendererComponent(JTable table,\n Object value, boolean isSelected, boolean hasFocus,\n int row, int column) {\n Component comp = r.getTableCellRendererComponent(table, value, isSelected, \n hasFocus, row, column);\n if (comp instanceof JLabel) {\n JLabel label = (JLabel) comp;\n label.setIcon(getSortIcon(table, column));\n }\n return comp;\n }\n\n /**\n * Implements the logic to choose the appropriate icon.\n */\n private ImageIcon getSortIcon(JTable table, int column) {\n SortOrder sortOrder = getColumnSortOrder(table, column);\n if (SortOrder.UNSORTED == sortOrder) {\n return null;\n }\n return SortOrder.ASCENDING == sortOrder ? ascendingIcon : descendingIcon;\n }\n\n private SortOrder getColumnSortOrder(JTable table, int column) {\n if (table == null || table.getRowSorter() == null) {\n return SortOrder.UNSORTED;\n }\n List<? extends SortKey> keys = table.getRowSorter().getSortKeys();\n if (keys.size() > 0) {\n SortKey key = keys.get(0);\n if (key.getColumn() == table.convertColumnIndexToModel(column)) {\n return key.getSortOrder();\n }\n }\n return SortOrder.UNSORTED;\n }\n\n };\n table.getTableHeader().setDefaultRenderer(wrapper);\n\n setLayout(new BorderLayout());\n\n add(new JScrollPane(table), BorderLayout.CENTER);\n\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n JFrame frame = new JFrame(\"Row Filter\");\n frame.add(new TestTableSortIcon());\n frame.pack();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n\n });\n }\n }\n\n" ]
[ 0 ]
[]
[]
[ "colors", "header", "java", "jtable", "swing" ]
stackoverflow_0052939496_colors_header_java_jtable_swing.txt
Q: Swiftui Preview Crashing using Navigationstack (Problem Report included) I can't figure out why my preview is crashing each time I press the "Hello World" text. I have a programatically navigationstack setup, and each time a view is appended it crashes in the preview. The app on my phone works great though, but I thought I must be doing something wrong if the preview is messing up. Thanks! Here is the problem report: ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Incident Identifier: 980494AC-44F1-43DF-B8BE-AB6FAA94E7A7 CrashReporter Key: 2F1EEC48-C1DA-2145-0171-733D5994FA2F Hardware Model: MacBookAir9,1 Process: Previewtest [88699] Path: /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B5B42958-9616-46D6-A056-B44D3D125005/data/Containers/Bundle/Application/E4B38613-49C2-4582-9650-7295F743C525/Previewtest.app/Previewtest Identifier: Partyhallen.Previewtest Version: 1.0 (1) Code Type: X86-64 (Native) Role: Foreground Parent Process: launchd_sim [87351] Coalition: com.apple.CoreSimulator.SimDevice.B5B42958-9616-46D6-A056-B44D3D125005 [11821] Responsible Process: SimulatorTrampoline [2117] Date/Time: 2022-12-03 00:13:50.6532 +0100 Launch Time: 2022-12-03 00:13:49.4824 +0100 OS Version: macOS 12.6 (21G115) Release Type: User Report Version: 104 Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: SIGNAL 4 Illegal instruction: 4 Terminating Process: exc handler [88699] Triggered by Thread: 0 Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libswiftCore.dylib 0x7ff80d700cc8 _assertionFailure(_:_:file:line:flags:) + 424 1 SwiftUI 0x10d6c9ed8 0x10c316000 + 20659928 2 SwiftUI 0x10d6c9de5 0x10c316000 + 20659685 3 Previewtest 0x1081105ab ContentView.router.getter + 139 4 ContentView.1.preview-thunk.dylib 0x10e4b761e closure #1 in closure #1 in ContentView.__preview__body.getter + 30 (ContentView.swift:13) 5 SwiftUI 0x10c7fc79d 0x10c316000 + 5138333 6 SwiftUI 0x10d08588a 0x10c316000 + 14088330 7 SwiftUI 0x10cded270 0x10c316000 + 11367024 8 SwiftUI 0x10cded284 0x10c316000 + 11367044 9 SwiftUI 0x10cded270 0x10c316000 + 11367024 10 SwiftUI 0x10cb03491 0x10c316000 + 8311953 11 SwiftUI 0x10cb02df2 0x10c316000 + 8310258 12 SwiftUI 0x10cc947a5 0x10c316000 + 9955237 13 SwiftUI 0x10d4437c8 0x10c316000 + 18012104 14 SwiftUI 0x10d441e5e 0x10c316000 + 18005598 15 SwiftUI 0x10d441f42 0x10c316000 + 18005826 16 SwiftUI 0x10d441720 0x10c316000 + 18003744 17 UIKitCore 0x1090274b9 -[UIGestureRecognizer _componentsEnded:withEvent:] + 153 18 UIKitCore 0x1096c6ebd -[UITouchesEvent _sendEventToGestureRecognizer:] + 662 19 UIKitCore 0x1090176f7 -[UIGestureEnvironment _updateForEvent:window:] + 469 20 UIKitCore 0x109669edb -[UIWindow sendEvent:] + 5282 21 UIKitCore 0x10963d7f2 -[UIApplication sendEvent:] + 898 22 UIKitCore 0x1096e4e61 __dispatchPreprocessedEventFromEventQueue + 9381 23 UIKitCore 0x1096e7569 __processEventQueue + 8334 24 UIKitCore 0x1096dd8a1 __eventFetcherSourceCallback + 272 25 CoreFoundation 0x7ff800387035 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 26 CoreFoundation 0x7ff800386f74 __CFRunLoopDoSource0 + 157 27 CoreFoundation 0x7ff800386771 __CFRunLoopDoSources0 + 212 28 CoreFoundation 0x7ff800380e73 __CFRunLoopRun + 927 29 CoreFoundation 0x7ff8003806f7 CFRunLoopRunSpecific + 560 30 GraphicsServices 0x7ff809c5c28a GSEventRunModal + 139 31 UIKitCore 0x10961c62b -[UIApplication _run] + 994 32 UIKitCore 0x109621547 UIApplicationMain + 123 33 SwiftUI 0x10d3fbcfb 0x10c316000 + 17718523 34 SwiftUI 0x10d3fbba8 0x10c316000 + 17718184 35 SwiftUI 0x10cab1b7d 0x10c316000 + 7977853 36 Previewtest 0x108112d4e static PreviewtestApp.$main() + 30 (PreviewtestApp.swift:4) 37 Previewtest 0x108112e09 main + 9 38 dyld_sim 0x1083662bf start_sim + 10 39 dyld 0x11476f52e start + 462 Thread 1: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 2: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 3: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 4: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 5: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 6:: com.apple.uikit.eventfetch-thread 0 libsystem_kernel.dylib 0x7ff834bdf97a mach_msg_trap + 10 1 libsystem_kernel.dylib 0x7ff834bdfce8 mach_msg + 56 2 CoreFoundation 0x7ff8003868de __CFRunLoopServiceMachPort + 145 3 CoreFoundation 0x7ff80038102f __CFRunLoopRun + 1371 4 CoreFoundation 0x7ff8003806f7 CFRunLoopRunSpecific + 560 5 Foundation 0x7ff800c5595c -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213 6 Foundation 0x7ff800c55bd5 -[NSRunLoop(NSRunLoop) runUntilDate:] + 72 7 UIKitCore 0x1096f0886 -[UIEventFetcher threadMain] + 535 8 Foundation 0x7ff800c7f1c3 __NSThread__start__ + 1009 9 libsystem_pthread.dylib 0x7ff834c3d4e1 _pthread_start + 125 10 libsystem_pthread.dylib 0x7ff834c38f6b thread_start + 15 Thread 0 crashed with X86 Thread State (64-bit): rax: 0x0000000200000003 rbx: 0x000000010d6ff670 rcx: 0xfffffffe00000000 rdx: 0x0000000000000003 rdi: 0x00007f7959c0f888 rsi: 0x000000000000001b rbp: 0x00007ff7b7def100 rsp: 0x00007ff7b7def0b0 r8: 0x0000000000000071 r9: 0x0000000000000070 r10: 0x0000000000000f30 r11: 0x0000600001a61aa8 r12: 0x0000000000000000 r13: 0x0000000000000046 r14: 0x00007f7959c0f880 r15: 0x000000000000000b rip: 0x00007ff80d700cc8 rfl: 0x0000000000010246 cr2: 0x000000012793b000 Logical CPU: 1 Error Code: 0x00000000 Trap Number: 6 Binary Images: 0x7ff80d6d4000 - 0x7ff80db90ff4 libswiftCore.dylib (*) <1d23cd50-8b48-349b-9163-f7990e0f95bd> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib 0x10c316000 - 0x10d9eefff com.apple.SwiftUI (4.1.17.100) <1622c162-0a3a-354c-94ea-62c5dd369612> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI 0x10810c000 - 0x108113fff Partyhallen.Previewtest (1.0) <a989b4b0-9e28-34db-865c-bbcabac9f176> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B5B42958-9616-46D6-A056-B44D3D125005/data/Containers/Bundle/Application/E4B38613-49C2-4582-9650-7295F743C525/Previewtest.app/Previewtest 0x10e4b5000 - 0x10e4b8fff ContentView.1.preview-thunk.dylib (*) <5d91714e-5553-3450-88be-8850c5896cb4> /Users/USER/Library/Developer/Xcode/DerivedData/Previewtest-haqnqqxsierjlvhdmnfotfqgnorc/Build/Intermediates.noindex/Previews/Previewtest/Intermediates.noindex/Previewtest.build/Debug-iphonesimulator/Previewtest.build/Objects-normal/x86_64/ContentView.1.preview-thunk.dylib 0x1087e1000 - 0x10a29dfff com.apple.UIKitCore (1.0) <c2258b63-cdcc-3504-a06e-8067adba9c34> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore 0x7ff800302000 - 0x7ff80068affc com.apple.CoreFoundation (6.9) <55edff37-af14-3fed-b932-031049d0a665> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation 0x7ff809c59000 - 0x7ff809c60ff2 com.apple.GraphicsServices (1.0) <5dad91c5-e70d-3f9a-88f2-2d1ed7c8dd24> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices 0x108364000 - 0x1083c3fff dyld_sim (*) <638f8a1f-2a32-396d-8389-8d7a60b96b8d> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim 0x11476a000 - 0x1147d5fff dyld (*) <71febccd-d9dc-3599-9971-2b3407c588a8> /usr/lib/dyld 0x7ff834c37000 - 0x7ff834c42ff7 libsystem_pthread.dylib (*) <b5454e27-e8c7-3fdb-b77f-714f1e82e70b> /usr/lib/system/libsystem_pthread.dylib 0x7ff834bde000 - 0x7ff834c15fff libsystem_kernel.dylib (*) <8cc28466-fd2f-3c80-9834-9525b7beac19> /usr/lib/system/libsystem_kernel.dylib 0x7ff8006fd000 - 0x7ff80102dffc com.apple.Foundation (6.9) <353e6739-fc3a-3636-89f2-194adba7203b> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation EOF ----------- Full Report ----------- {"app_name":"Previewtest","timestamp":"2022-12-03 00:13:51.00 +0100","app_version":"1.0","slice_uuid":"a989b4b0-9e28-34db-865c-bbcabac9f176","build_version":"1","platform":7,"bundleID":"Partyhallen.Previewtest","share_with_app_devs":0,"is_first_party":0,"bug_type":"309","os_version":"macOS 12.6 (21G115)","incident_id":"980494AC-44F1-43DF-B8BE-AB6FAA94E7A7","name":"Previewtest"} { "uptime" : 370000, "procLaunch" : "2022-12-03 00:13:49.4824 +0100", "procRole" : "Foreground", "version" : 2, "userID" : 501, "deployVersion" : 210, "modelCode" : "MacBookAir9,1", "procStartAbsTime" : 374779515462303, "coalitionID" : 11821, "osVersion" : { "train" : "macOS 12.6", "build" : "21G115", "releaseType" : "User" }, "captureTime" : "2022-12-03 00:13:50.6532 +0100", "incident" : "980494AC-44F1-43DF-B8BE-AB6FAA94E7A7", "bug_type" : "309", "pid" : 88699, "procExitAbsTime" : 374780663063696, "cpuType" : "X86-64", "procName" : "Previewtest", "procPath" : "\/Users\/USER\/Library\/Developer\/Xcode\/UserData\/Previews\/Simulator Devices\/B5B42958-9616-46D6-A056-B44D3D125005\/data\/Containers\/Bundle\/Application\/E4B38613-49C2-4582-9650-7295F743C525\/Previewtest.app\/Previewtest", "bundleInfo" : {"CFBundleShortVersionString":"1.0","CFBundleVersion":"1","CFBundleIdentifier":"Partyhallen.Previewtest"}, "storeInfo" : {"deviceIdentifierForVendor":"B5E785AA-2399-55A2-8DC1-FCE60C089E4D","thirdParty":true}, "parentProc" : "launchd_sim", "parentPid" : 87351, "coalitionName" : "com.apple.CoreSimulator.SimDevice.B5B42958-9616-46D6-A056-B44D3D125005", "crashReporterKey" : "2F1EEC48-C1DA-2145-0171-733D5994FA2F", "responsiblePid" : 2117, "responsibleProc" : "SimulatorTrampoline", "wakeTime" : 5437, "bridgeVersion" : {"build":"19P6067","train":"6.6"}, "sleepWakeUUID" : "407BF33E-E77C-46C9-BE09-2761B3AEE27C", "sip" : "enabled", "isCorpse" : 1, "exception" : {"codes":"0x0000000000000001, 0x0000000000000000","rawCodes":[1,0],"type":"EXC_BAD_INSTRUCTION","signal":"SIGILL"}, "termination" : {"flags":0,"code":4,"namespace":"SIGNAL","indicator":"Illegal instruction: 4","byProc":"exc handler","byPid":88699}, "extMods" : {"caller":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"system":{"thread_create":0,"thread_set_state":0,"task_for_pid":28},"targeted":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"warnings":0}, "faultingThread" : 0, "threads" : [{"triggered":true,"id":4314897,"instructionState":{"instructionStream":{"bytes":[184,0,0,0,0,0,0,0,16,73,133,196,15,132,198,1,0,0,72,131,192,255,76,137,247,72,33,199,72,131,199,32,72,184,255,255,255,255,255,255,0,0,73,33,196,72,131,236,8,68,15,182,69,24,76,137,230,72,139,85,208,72,139,77,16,73,137,217,69,49,228,139,69,40,80,65,85,65,87,232,20,18,0,0,72,131,196,32,76,137,247,232,56,65,52,0,15,11,72,131,236,8,72,141,5,251,241,69,0,72,141,61,184,237,69,0,72,141,13,205,240,69,0,190,11,0,0,0,65,184,57,0,0,0,186,2,0,0,0,65,185,2,0,0,0,106,0,104,148,0,0,0,106,2,106,24,80,232,182,2,0,0,72,131,236,8,72,141,5,203,237,69,0,72,141,61,120,237,69,0,72,141,13,141,237,69,0,190,11,0,0,0],"offset":96}},"threadState":{"r13":{"value":70},"rax":{"value":8589934595},"rflags":{"value":66118},"cpu":{"value":1},"r14":{"value":140159173589120},"rsi":{"value":27},"r8":{"value":113},"cr2":{"value":4958957568},"rdx":{"value":3},"r10":{"value":3888},"r9":{"value":112},"r15":{"value":11},"rbx":{"value":4520408688},"trap":{"value":6},"err":{"value":0},"r11":{"value":105553143929512},"rip":{"value":140703354064072,"matchesCrashFrame":1},"rbp":{"value":140701918490880},"rsp":{"value":140701918490800},"r12":{"value":0},"rcx":{"value":18446744065119617024},"flavor":"x86_THREAD_STATE","rdi":{"value":140159173589128}},"queue":"com.apple.main-thread","frames":[{"imageOffset":183496,"symbol":"_assertionFailure(_:_:file:line:flags:)","symbolLocation":424,"imageIndex":0},{"imageOffset":20659928,"imageIndex":1},{"imageOffset":20659685,"imageIndex":1},{"imageOffset":17835,"sourceFile":"ContentView.swift","symbol":"ContentView.router.getter","symbolLocation":139,"imageIndex":2},{"imageOffset":9758,"sourceLine":13,"sourceFile":"ContentView.swift","symbol":"closure #1 in closure #1 in ContentView.__preview__body.getter","imageIndex":3,"symbolLocation":30},{"imageOffset":5138333,"imageIndex":1},{"imageOffset":14088330,"imageIndex":1},{"imageOffset":11367024,"imageIndex":1},{"imageOffset":11367044,"imageIndex":1},{"imageOffset":11367024,"imageIndex":1},{"imageOffset":8311953,"imageIndex":1},{"imageOffset":8310258,"imageIndex":1},{"imageOffset":9955237,"imageIndex":1},{"imageOffset":18012104,"imageIndex":1},{"imageOffset":18005598,"imageIndex":1},{"imageOffset":18005826,"imageIndex":1},{"imageOffset":18003744,"imageIndex":1},{"imageOffset":8676537,"symbol":"-[UIGestureRecognizer _componentsEnded:withEvent:]","symbolLocation":153,"imageIndex":4},{"imageOffset":15621821,"symbol":"-[UITouchesEvent _sendEventToGestureRecognizer:]","symbolLocation":662,"imageIndex":4},{"imageOffset":8611575,"symbol":"-[UIGestureEnvironment _updateForEvent:window:]","symbolLocation":469,"imageIndex":4},{"imageOffset":15240923,"symbol":"-[UIWindow sendEvent:]","symbolLocation":5282,"imageIndex":4},{"imageOffset":15058930,"symbol":"-[UIApplication sendEvent:]","symbolLocation":898,"imageIndex":4},{"imageOffset":15744609,"symbol":"__dispatchPreprocessedEventFromEventQueue","symbolLocation":9381,"imageIndex":4},{"imageOffset":15754601,"symbol":"__processEventQueue","symbolLocation":8334,"imageIndex":4},{"imageOffset":15714465,"symbol":"__eventFetcherSourceCallback","symbolLocation":272,"imageIndex":4},{"imageOffset":544821,"symbol":"__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__","symbolLocation":17,"imageIndex":5},{"imageOffset":544628,"symbol":"__CFRunLoopDoSource0","symbolLocation":157,"imageIndex":5},{"imageOffset":542577,"symbol":"__CFRunLoopDoSources0","symbolLocation":212,"imageIndex":5},{"imageOffset":519795,"symbol":"__CFRunLoopRun","symbolLocation":927,"imageIndex":5},{"imageOffset":517879,"symbol":"CFRunLoopRunSpecific","symbolLocation":560,"imageIndex":5},{"imageOffset":12938,"symbol":"GSEventRunModal","symbolLocation":139,"imageIndex":6},{"imageOffset":14923307,"symbol":"-[UIApplication _run]","symbolLocation":994,"imageIndex":4},{"imageOffset":14943559,"symbol":"UIApplicationMain","symbolLocation":123,"imageIndex":4},{"imageOffset":17718523,"imageIndex":1},{"imageOffset":17718184,"imageIndex":1},{"imageOffset":7977853,"imageIndex":1},{"imageOffset":27982,"sourceLine":4,"sourceFile":"PreviewtestApp.swift","symbol":"static PreviewtestApp.$main()","imageIndex":2,"symbolLocation":30},{"imageOffset":28169,"sourceFile":"PreviewtestApp.swift","symbol":"main","symbolLocation":9,"imageIndex":2},{"imageOffset":8895,"symbol":"start_sim","symbolLocation":10,"imageIndex":7},{"imageOffset":21806,"symbol":"start","symbolLocation":462,"imageIndex":8}]},{"id":4314907,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314908,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314909,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314910,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314911,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314912,"name":"com.apple.uikit.eventfetch-thread","frames":[{"imageOffset":6522,"symbol":"mach_msg_trap","symbolLocation":10,"imageIndex":10},{"imageOffset":7400,"symbol":"mach_msg","symbolLocation":56,"imageIndex":10},{"imageOffset":542942,"symbol":"__CFRunLoopServiceMachPort","symbolLocation":145,"imageIndex":5},{"imageOffset":520239,"symbol":"__CFRunLoopRun","symbolLocation":1371,"imageIndex":5},{"imageOffset":517879,"symbol":"CFRunLoopRunSpecific","symbolLocation":560,"imageIndex":5},{"imageOffset":5605724,"symbol":"-[NSRunLoop(NSRunLoop) runMode:beforeDate:]","symbolLocation":213,"imageIndex":11},{"imageOffset":5606357,"symbol":"-[NSRunLoop(NSRunLoop) runUntilDate:]","symbolLocation":72,"imageIndex":11},{"imageOffset":15792262,"symbol":"-[UIEventFetcher threadMain]","symbolLocation":535,"imageIndex":4},{"imageOffset":5775811,"symbol":"__NSThread__start__","symbolLocation":1009,"imageIndex":11},{"imageOffset":25825,"symbol":"_pthread_start","symbolLocation":125,"imageIndex":9},{"imageOffset":8043,"symbol":"thread_start","symbolLocation":15,"imageIndex":9}]}], "usedImages" : [ { "source" : "P", "arch" : "x86_64", "base" : 140703353880576, "size" : 4968437, "uuid" : "1d23cd50-8b48-349b-9163-f7990e0f95bd", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/usr\/lib\/swift\/libswiftCore.dylib", "name" : "libswiftCore.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 4499529728, "CFBundleShortVersionString" : "4.1.17.100", "CFBundleIdentifier" : "com.apple.SwiftUI", "size" : 23957504, "uuid" : "1622c162-0a3a-354c-94ea-62c5dd369612", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/Frameworks\/SwiftUI.framework\/SwiftUI", "name" : "SwiftUI", "CFBundleVersion" : "4.1.17.100" }, { "source" : "P", "arch" : "x86_64", "base" : 4430282752, "CFBundleShortVersionString" : "1.0", "CFBundleIdentifier" : "Partyhallen.Previewtest", "size" : 32768, "uuid" : "a989b4b0-9e28-34db-865c-bbcabac9f176", "path" : "\/Users\/USER\/Library\/Developer\/Xcode\/UserData\/Previews\/Simulator Devices\/B5B42958-9616-46D6-A056-B44D3D125005\/data\/Containers\/Bundle\/Application\/E4B38613-49C2-4582-9650-7295F743C525\/Previewtest.app\/Previewtest", "name" : "Previewtest", "CFBundleVersion" : "1" }, { "source" : "P", "arch" : "x86_64", "base" : 4534784000, "size" : 16384, "uuid" : "5d91714e-5553-3450-88be-8850c5896cb4", "path" : "\/Users\/USER\/Library\/Developer\/Xcode\/DerivedData\/Previewtest-haqnqqxsierjlvhdmnfotfqgnorc\/Build\/Intermediates.noindex\/Previews\/Previewtest\/Intermediates.noindex\/Previewtest.build\/Debug-iphonesimulator\/Previewtest.build\/Objects-normal\/x86_64\/ContentView.1.preview-thunk.dylib", "name" : "ContentView.1.preview-thunk.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 4437446656, "CFBundleShortVersionString" : "1.0", "CFBundleIdentifier" : "com.apple.UIKitCore", "size" : 28037120, "uuid" : "c2258b63-cdcc-3504-a06e-8067adba9c34", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/PrivateFrameworks\/UIKitCore.framework\/UIKitCore", "name" : "UIKitCore", "CFBundleVersion" : "6109.1.108" }, { "source" : "P", "arch" : "x86_64", "base" : 140703131770880, "CFBundleShortVersionString" : "6.9", "CFBundleIdentifier" : "com.apple.CoreFoundation", "size" : 3706877, "uuid" : "55edff37-af14-3fed-b932-031049d0a665", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/Frameworks\/CoreFoundation.framework\/CoreFoundation", "name" : "CoreFoundation", "CFBundleVersion" : "1953.1" }, { "source" : "P", "arch" : "x86_64", "base" : 140703292559360, "CFBundleShortVersionString" : "1.0", "CFBundleIdentifier" : "com.apple.GraphicsServices", "size" : 32755, "uuid" : "5dad91c5-e70d-3f9a-88f2-2d1ed7c8dd24", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/PrivateFrameworks\/GraphicsServices.framework\/GraphicsServices", "name" : "GraphicsServices", "CFBundleVersion" : "1.0" }, { "source" : "P", "arch" : "x86_64", "base" : 4432740352, "size" : 393216, "uuid" : "638f8a1f-2a32-396d-8389-8d7a60b96b8d", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/usr\/lib\/dyld_sim", "name" : "dyld_sim" }, { "source" : "P", "arch" : "x86_64", "base" : 4638285824, "size" : 442368, "uuid" : "71febccd-d9dc-3599-9971-2b3407c588a8", "path" : "\/usr\/lib\/dyld", "name" : "dyld" }, { "source" : "P", "arch" : "x86_64", "base" : 140704013840384, "size" : 49144, "uuid" : "b5454e27-e8c7-3fdb-b77f-714f1e82e70b", "path" : "\/usr\/lib\/system\/libsystem_pthread.dylib", "name" : "libsystem_pthread.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 140704013475840, "size" : 229376, "uuid" : "8cc28466-fd2f-3c80-9834-9525b7beac19", "path" : "\/usr\/lib\/system\/libsystem_kernel.dylib", "name" : "libsystem_kernel.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 140703135944704, "CFBundleShortVersionString" : "6.9", "CFBundleIdentifier" : "com.apple.Foundation", "size" : 9637885, "uuid" : "353e6739-fc3a-3636-89f2-194adba7203b", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/Frameworks\/Foundation.framework\/Foundation", "name" : "Foundation", "CFBundleVersion" : "1953.1" } ], "sharedCache" : { "base" : 140703128616960, "size" : 2998861824, "uuid" : "3140e7f6-3cc2-3fac-81dd-5fbfbbe796e1" }, "vmSummary" : "ReadOnly portion of Libraries: Total=803.7M resident=0K(0%) swapped_out_or_unallocated=803.7M(100%)\nWritable regions: Total=575.2M written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=575.2M(100%)\n\n VIRTUAL REGION \nREGION TYPE SIZE COUNT (non-coalesced) \n=========== ======= ======= \nActivity Tracing 256K 1 \nCG raster data 8K 1 \nColorSync 88K 5 \nCoreAnimation 20K 1 \nFoundation 16K 1 \nKernel Alloc Once 8K 1 \nMALLOC 177.5M 30 \nMALLOC guard page 32K 8 \nMALLOC_NANO (reserved) 384.0M 1 reserved VM address space (unallocated)\nSTACK GUARD 56.0M 7 \nStack 11.0M 7 \nVM_ALLOCATE 1052K 4 \n__DATA 11.3M 398 \n__DATA_CONST 36.7M 402 \n__DATA_DIRTY 26K 12 \n__FONT_DATA 2352 1 \n__LINKEDIT 358.0M 33 \n__OBJC_RO 28.3M 1 \n__OBJC_RW 880K 1 \n__TEXT 445.8M 410 \ndyld private memory 1280K 2 \nmapped file 206.8M 11 \nshared memory 16K 1 \n=========== ======= ======= \nTOTAL 1.7G 1339 \nTOTAL, minus reserved VM space 1.3G 1339 \n", "legacyInfo" : { "threadTriggered" : { "queue" : "com.apple.main-thread" } }, "trialInfo" : { "rollouts" : [ { "rolloutId" : "63582c5f8a53461413999550", "factorPackIds" : { }, "deploymentId" : 240000002 }, { "rolloutId" : "60f8ddccefea4203d95cbeef", "factorPackIds" : { }, "deploymentId" : 240000021 } ], "experiments" : [ ] } } Here is my code: import SwiftUI import Foundation @main struct PreviewtestApp: App { var body: some Scene { WindowGroup { AppContainerView() } } } import SwiftUI import Foundation struct AppContainerView: View { @StateObject var router = Router() var body: some View { NavigationStack(path: $router.navigationPath) { ContentView() .navigationDestination(for: Route.self) { route in switch route { case .ContentView: ContentView() } } }.environmentObject(router) } } import SwiftUI import Foundation struct ContentView: View { @EnvironmentObject private var router: Router var body: some View { VStack { Text("Hello, world!") .onTapGesture { router.pushView(route: .ContentView) } } .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } import Foundation import SwiftUI enum Route: Hashable { case ContentView } final class Router: ObservableObject { @Published var navigationPath = NavigationPath() func pushView(route: Route) { navigationPath.append(route) } func popToRootView() { navigationPath = .init() } func popToSpecificView(k: Int) { navigationPath.removeLast(k) } } A: @StateObject aren't init during previewing so that is probably causing the crash. You could workaround it by previewing AppContainerView instead of ContentView. By the way, @StateObject is for when you need to store a reference type in a @State but in this example don't need a reference type. Also, NavigationPath is designed to hold the data values, not routes. You can use multiple navigationDestination for each kind of value, instead of one with a switch statement.
Swiftui Preview Crashing using Navigationstack (Problem Report included)
I can't figure out why my preview is crashing each time I press the "Hello World" text. I have a programatically navigationstack setup, and each time a view is appended it crashes in the preview. The app on my phone works great though, but I thought I must be doing something wrong if the preview is messing up. Thanks! Here is the problem report: ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Incident Identifier: 980494AC-44F1-43DF-B8BE-AB6FAA94E7A7 CrashReporter Key: 2F1EEC48-C1DA-2145-0171-733D5994FA2F Hardware Model: MacBookAir9,1 Process: Previewtest [88699] Path: /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B5B42958-9616-46D6-A056-B44D3D125005/data/Containers/Bundle/Application/E4B38613-49C2-4582-9650-7295F743C525/Previewtest.app/Previewtest Identifier: Partyhallen.Previewtest Version: 1.0 (1) Code Type: X86-64 (Native) Role: Foreground Parent Process: launchd_sim [87351] Coalition: com.apple.CoreSimulator.SimDevice.B5B42958-9616-46D6-A056-B44D3D125005 [11821] Responsible Process: SimulatorTrampoline [2117] Date/Time: 2022-12-03 00:13:50.6532 +0100 Launch Time: 2022-12-03 00:13:49.4824 +0100 OS Version: macOS 12.6 (21G115) Release Type: User Report Version: 104 Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: SIGNAL 4 Illegal instruction: 4 Terminating Process: exc handler [88699] Triggered by Thread: 0 Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libswiftCore.dylib 0x7ff80d700cc8 _assertionFailure(_:_:file:line:flags:) + 424 1 SwiftUI 0x10d6c9ed8 0x10c316000 + 20659928 2 SwiftUI 0x10d6c9de5 0x10c316000 + 20659685 3 Previewtest 0x1081105ab ContentView.router.getter + 139 4 ContentView.1.preview-thunk.dylib 0x10e4b761e closure #1 in closure #1 in ContentView.__preview__body.getter + 30 (ContentView.swift:13) 5 SwiftUI 0x10c7fc79d 0x10c316000 + 5138333 6 SwiftUI 0x10d08588a 0x10c316000 + 14088330 7 SwiftUI 0x10cded270 0x10c316000 + 11367024 8 SwiftUI 0x10cded284 0x10c316000 + 11367044 9 SwiftUI 0x10cded270 0x10c316000 + 11367024 10 SwiftUI 0x10cb03491 0x10c316000 + 8311953 11 SwiftUI 0x10cb02df2 0x10c316000 + 8310258 12 SwiftUI 0x10cc947a5 0x10c316000 + 9955237 13 SwiftUI 0x10d4437c8 0x10c316000 + 18012104 14 SwiftUI 0x10d441e5e 0x10c316000 + 18005598 15 SwiftUI 0x10d441f42 0x10c316000 + 18005826 16 SwiftUI 0x10d441720 0x10c316000 + 18003744 17 UIKitCore 0x1090274b9 -[UIGestureRecognizer _componentsEnded:withEvent:] + 153 18 UIKitCore 0x1096c6ebd -[UITouchesEvent _sendEventToGestureRecognizer:] + 662 19 UIKitCore 0x1090176f7 -[UIGestureEnvironment _updateForEvent:window:] + 469 20 UIKitCore 0x109669edb -[UIWindow sendEvent:] + 5282 21 UIKitCore 0x10963d7f2 -[UIApplication sendEvent:] + 898 22 UIKitCore 0x1096e4e61 __dispatchPreprocessedEventFromEventQueue + 9381 23 UIKitCore 0x1096e7569 __processEventQueue + 8334 24 UIKitCore 0x1096dd8a1 __eventFetcherSourceCallback + 272 25 CoreFoundation 0x7ff800387035 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 26 CoreFoundation 0x7ff800386f74 __CFRunLoopDoSource0 + 157 27 CoreFoundation 0x7ff800386771 __CFRunLoopDoSources0 + 212 28 CoreFoundation 0x7ff800380e73 __CFRunLoopRun + 927 29 CoreFoundation 0x7ff8003806f7 CFRunLoopRunSpecific + 560 30 GraphicsServices 0x7ff809c5c28a GSEventRunModal + 139 31 UIKitCore 0x10961c62b -[UIApplication _run] + 994 32 UIKitCore 0x109621547 UIApplicationMain + 123 33 SwiftUI 0x10d3fbcfb 0x10c316000 + 17718523 34 SwiftUI 0x10d3fbba8 0x10c316000 + 17718184 35 SwiftUI 0x10cab1b7d 0x10c316000 + 7977853 36 Previewtest 0x108112d4e static PreviewtestApp.$main() + 30 (PreviewtestApp.swift:4) 37 Previewtest 0x108112e09 main + 9 38 dyld_sim 0x1083662bf start_sim + 10 39 dyld 0x11476f52e start + 462 Thread 1: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 2: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 3: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 4: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 5: 0 libsystem_pthread.dylib 0x7ff834c38f48 start_wqthread + 0 Thread 6:: com.apple.uikit.eventfetch-thread 0 libsystem_kernel.dylib 0x7ff834bdf97a mach_msg_trap + 10 1 libsystem_kernel.dylib 0x7ff834bdfce8 mach_msg + 56 2 CoreFoundation 0x7ff8003868de __CFRunLoopServiceMachPort + 145 3 CoreFoundation 0x7ff80038102f __CFRunLoopRun + 1371 4 CoreFoundation 0x7ff8003806f7 CFRunLoopRunSpecific + 560 5 Foundation 0x7ff800c5595c -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 213 6 Foundation 0x7ff800c55bd5 -[NSRunLoop(NSRunLoop) runUntilDate:] + 72 7 UIKitCore 0x1096f0886 -[UIEventFetcher threadMain] + 535 8 Foundation 0x7ff800c7f1c3 __NSThread__start__ + 1009 9 libsystem_pthread.dylib 0x7ff834c3d4e1 _pthread_start + 125 10 libsystem_pthread.dylib 0x7ff834c38f6b thread_start + 15 Thread 0 crashed with X86 Thread State (64-bit): rax: 0x0000000200000003 rbx: 0x000000010d6ff670 rcx: 0xfffffffe00000000 rdx: 0x0000000000000003 rdi: 0x00007f7959c0f888 rsi: 0x000000000000001b rbp: 0x00007ff7b7def100 rsp: 0x00007ff7b7def0b0 r8: 0x0000000000000071 r9: 0x0000000000000070 r10: 0x0000000000000f30 r11: 0x0000600001a61aa8 r12: 0x0000000000000000 r13: 0x0000000000000046 r14: 0x00007f7959c0f880 r15: 0x000000000000000b rip: 0x00007ff80d700cc8 rfl: 0x0000000000010246 cr2: 0x000000012793b000 Logical CPU: 1 Error Code: 0x00000000 Trap Number: 6 Binary Images: 0x7ff80d6d4000 - 0x7ff80db90ff4 libswiftCore.dylib (*) <1d23cd50-8b48-349b-9163-f7990e0f95bd> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCore.dylib 0x10c316000 - 0x10d9eefff com.apple.SwiftUI (4.1.17.100) <1622c162-0a3a-354c-94ea-62c5dd369612> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/SwiftUI.framework/SwiftUI 0x10810c000 - 0x108113fff Partyhallen.Previewtest (1.0) <a989b4b0-9e28-34db-865c-bbcabac9f176> /Users/USER/Library/Developer/Xcode/UserData/Previews/Simulator Devices/B5B42958-9616-46D6-A056-B44D3D125005/data/Containers/Bundle/Application/E4B38613-49C2-4582-9650-7295F743C525/Previewtest.app/Previewtest 0x10e4b5000 - 0x10e4b8fff ContentView.1.preview-thunk.dylib (*) <5d91714e-5553-3450-88be-8850c5896cb4> /Users/USER/Library/Developer/Xcode/DerivedData/Previewtest-haqnqqxsierjlvhdmnfotfqgnorc/Build/Intermediates.noindex/Previews/Previewtest/Intermediates.noindex/Previewtest.build/Debug-iphonesimulator/Previewtest.build/Objects-normal/x86_64/ContentView.1.preview-thunk.dylib 0x1087e1000 - 0x10a29dfff com.apple.UIKitCore (1.0) <c2258b63-cdcc-3504-a06e-8067adba9c34> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore 0x7ff800302000 - 0x7ff80068affc com.apple.CoreFoundation (6.9) <55edff37-af14-3fed-b932-031049d0a665> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation 0x7ff809c59000 - 0x7ff809c60ff2 com.apple.GraphicsServices (1.0) <5dad91c5-e70d-3f9a-88f2-2d1ed7c8dd24> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices 0x108364000 - 0x1083c3fff dyld_sim (*) <638f8a1f-2a32-396d-8389-8d7a60b96b8d> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/dyld_sim 0x11476a000 - 0x1147d5fff dyld (*) <71febccd-d9dc-3599-9971-2b3407c588a8> /usr/lib/dyld 0x7ff834c37000 - 0x7ff834c42ff7 libsystem_pthread.dylib (*) <b5454e27-e8c7-3fdb-b77f-714f1e82e70b> /usr/lib/system/libsystem_pthread.dylib 0x7ff834bde000 - 0x7ff834c15fff libsystem_kernel.dylib (*) <8cc28466-fd2f-3c80-9834-9525b7beac19> /usr/lib/system/libsystem_kernel.dylib 0x7ff8006fd000 - 0x7ff80102dffc com.apple.Foundation (6.9) <353e6739-fc3a-3636-89f2-194adba7203b> /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/Foundation.framework/Foundation EOF ----------- Full Report ----------- {"app_name":"Previewtest","timestamp":"2022-12-03 00:13:51.00 +0100","app_version":"1.0","slice_uuid":"a989b4b0-9e28-34db-865c-bbcabac9f176","build_version":"1","platform":7,"bundleID":"Partyhallen.Previewtest","share_with_app_devs":0,"is_first_party":0,"bug_type":"309","os_version":"macOS 12.6 (21G115)","incident_id":"980494AC-44F1-43DF-B8BE-AB6FAA94E7A7","name":"Previewtest"} { "uptime" : 370000, "procLaunch" : "2022-12-03 00:13:49.4824 +0100", "procRole" : "Foreground", "version" : 2, "userID" : 501, "deployVersion" : 210, "modelCode" : "MacBookAir9,1", "procStartAbsTime" : 374779515462303, "coalitionID" : 11821, "osVersion" : { "train" : "macOS 12.6", "build" : "21G115", "releaseType" : "User" }, "captureTime" : "2022-12-03 00:13:50.6532 +0100", "incident" : "980494AC-44F1-43DF-B8BE-AB6FAA94E7A7", "bug_type" : "309", "pid" : 88699, "procExitAbsTime" : 374780663063696, "cpuType" : "X86-64", "procName" : "Previewtest", "procPath" : "\/Users\/USER\/Library\/Developer\/Xcode\/UserData\/Previews\/Simulator Devices\/B5B42958-9616-46D6-A056-B44D3D125005\/data\/Containers\/Bundle\/Application\/E4B38613-49C2-4582-9650-7295F743C525\/Previewtest.app\/Previewtest", "bundleInfo" : {"CFBundleShortVersionString":"1.0","CFBundleVersion":"1","CFBundleIdentifier":"Partyhallen.Previewtest"}, "storeInfo" : {"deviceIdentifierForVendor":"B5E785AA-2399-55A2-8DC1-FCE60C089E4D","thirdParty":true}, "parentProc" : "launchd_sim", "parentPid" : 87351, "coalitionName" : "com.apple.CoreSimulator.SimDevice.B5B42958-9616-46D6-A056-B44D3D125005", "crashReporterKey" : "2F1EEC48-C1DA-2145-0171-733D5994FA2F", "responsiblePid" : 2117, "responsibleProc" : "SimulatorTrampoline", "wakeTime" : 5437, "bridgeVersion" : {"build":"19P6067","train":"6.6"}, "sleepWakeUUID" : "407BF33E-E77C-46C9-BE09-2761B3AEE27C", "sip" : "enabled", "isCorpse" : 1, "exception" : {"codes":"0x0000000000000001, 0x0000000000000000","rawCodes":[1,0],"type":"EXC_BAD_INSTRUCTION","signal":"SIGILL"}, "termination" : {"flags":0,"code":4,"namespace":"SIGNAL","indicator":"Illegal instruction: 4","byProc":"exc handler","byPid":88699}, "extMods" : {"caller":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"system":{"thread_create":0,"thread_set_state":0,"task_for_pid":28},"targeted":{"thread_create":0,"thread_set_state":0,"task_for_pid":0},"warnings":0}, "faultingThread" : 0, "threads" : [{"triggered":true,"id":4314897,"instructionState":{"instructionStream":{"bytes":[184,0,0,0,0,0,0,0,16,73,133,196,15,132,198,1,0,0,72,131,192,255,76,137,247,72,33,199,72,131,199,32,72,184,255,255,255,255,255,255,0,0,73,33,196,72,131,236,8,68,15,182,69,24,76,137,230,72,139,85,208,72,139,77,16,73,137,217,69,49,228,139,69,40,80,65,85,65,87,232,20,18,0,0,72,131,196,32,76,137,247,232,56,65,52,0,15,11,72,131,236,8,72,141,5,251,241,69,0,72,141,61,184,237,69,0,72,141,13,205,240,69,0,190,11,0,0,0,65,184,57,0,0,0,186,2,0,0,0,65,185,2,0,0,0,106,0,104,148,0,0,0,106,2,106,24,80,232,182,2,0,0,72,131,236,8,72,141,5,203,237,69,0,72,141,61,120,237,69,0,72,141,13,141,237,69,0,190,11,0,0,0],"offset":96}},"threadState":{"r13":{"value":70},"rax":{"value":8589934595},"rflags":{"value":66118},"cpu":{"value":1},"r14":{"value":140159173589120},"rsi":{"value":27},"r8":{"value":113},"cr2":{"value":4958957568},"rdx":{"value":3},"r10":{"value":3888},"r9":{"value":112},"r15":{"value":11},"rbx":{"value":4520408688},"trap":{"value":6},"err":{"value":0},"r11":{"value":105553143929512},"rip":{"value":140703354064072,"matchesCrashFrame":1},"rbp":{"value":140701918490880},"rsp":{"value":140701918490800},"r12":{"value":0},"rcx":{"value":18446744065119617024},"flavor":"x86_THREAD_STATE","rdi":{"value":140159173589128}},"queue":"com.apple.main-thread","frames":[{"imageOffset":183496,"symbol":"_assertionFailure(_:_:file:line:flags:)","symbolLocation":424,"imageIndex":0},{"imageOffset":20659928,"imageIndex":1},{"imageOffset":20659685,"imageIndex":1},{"imageOffset":17835,"sourceFile":"ContentView.swift","symbol":"ContentView.router.getter","symbolLocation":139,"imageIndex":2},{"imageOffset":9758,"sourceLine":13,"sourceFile":"ContentView.swift","symbol":"closure #1 in closure #1 in ContentView.__preview__body.getter","imageIndex":3,"symbolLocation":30},{"imageOffset":5138333,"imageIndex":1},{"imageOffset":14088330,"imageIndex":1},{"imageOffset":11367024,"imageIndex":1},{"imageOffset":11367044,"imageIndex":1},{"imageOffset":11367024,"imageIndex":1},{"imageOffset":8311953,"imageIndex":1},{"imageOffset":8310258,"imageIndex":1},{"imageOffset":9955237,"imageIndex":1},{"imageOffset":18012104,"imageIndex":1},{"imageOffset":18005598,"imageIndex":1},{"imageOffset":18005826,"imageIndex":1},{"imageOffset":18003744,"imageIndex":1},{"imageOffset":8676537,"symbol":"-[UIGestureRecognizer _componentsEnded:withEvent:]","symbolLocation":153,"imageIndex":4},{"imageOffset":15621821,"symbol":"-[UITouchesEvent _sendEventToGestureRecognizer:]","symbolLocation":662,"imageIndex":4},{"imageOffset":8611575,"symbol":"-[UIGestureEnvironment _updateForEvent:window:]","symbolLocation":469,"imageIndex":4},{"imageOffset":15240923,"symbol":"-[UIWindow sendEvent:]","symbolLocation":5282,"imageIndex":4},{"imageOffset":15058930,"symbol":"-[UIApplication sendEvent:]","symbolLocation":898,"imageIndex":4},{"imageOffset":15744609,"symbol":"__dispatchPreprocessedEventFromEventQueue","symbolLocation":9381,"imageIndex":4},{"imageOffset":15754601,"symbol":"__processEventQueue","symbolLocation":8334,"imageIndex":4},{"imageOffset":15714465,"symbol":"__eventFetcherSourceCallback","symbolLocation":272,"imageIndex":4},{"imageOffset":544821,"symbol":"__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__","symbolLocation":17,"imageIndex":5},{"imageOffset":544628,"symbol":"__CFRunLoopDoSource0","symbolLocation":157,"imageIndex":5},{"imageOffset":542577,"symbol":"__CFRunLoopDoSources0","symbolLocation":212,"imageIndex":5},{"imageOffset":519795,"symbol":"__CFRunLoopRun","symbolLocation":927,"imageIndex":5},{"imageOffset":517879,"symbol":"CFRunLoopRunSpecific","symbolLocation":560,"imageIndex":5},{"imageOffset":12938,"symbol":"GSEventRunModal","symbolLocation":139,"imageIndex":6},{"imageOffset":14923307,"symbol":"-[UIApplication _run]","symbolLocation":994,"imageIndex":4},{"imageOffset":14943559,"symbol":"UIApplicationMain","symbolLocation":123,"imageIndex":4},{"imageOffset":17718523,"imageIndex":1},{"imageOffset":17718184,"imageIndex":1},{"imageOffset":7977853,"imageIndex":1},{"imageOffset":27982,"sourceLine":4,"sourceFile":"PreviewtestApp.swift","symbol":"static PreviewtestApp.$main()","imageIndex":2,"symbolLocation":30},{"imageOffset":28169,"sourceFile":"PreviewtestApp.swift","symbol":"main","symbolLocation":9,"imageIndex":2},{"imageOffset":8895,"symbol":"start_sim","symbolLocation":10,"imageIndex":7},{"imageOffset":21806,"symbol":"start","symbolLocation":462,"imageIndex":8}]},{"id":4314907,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314908,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314909,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314910,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314911,"frames":[{"imageOffset":8008,"symbol":"start_wqthread","symbolLocation":0,"imageIndex":9}]},{"id":4314912,"name":"com.apple.uikit.eventfetch-thread","frames":[{"imageOffset":6522,"symbol":"mach_msg_trap","symbolLocation":10,"imageIndex":10},{"imageOffset":7400,"symbol":"mach_msg","symbolLocation":56,"imageIndex":10},{"imageOffset":542942,"symbol":"__CFRunLoopServiceMachPort","symbolLocation":145,"imageIndex":5},{"imageOffset":520239,"symbol":"__CFRunLoopRun","symbolLocation":1371,"imageIndex":5},{"imageOffset":517879,"symbol":"CFRunLoopRunSpecific","symbolLocation":560,"imageIndex":5},{"imageOffset":5605724,"symbol":"-[NSRunLoop(NSRunLoop) runMode:beforeDate:]","symbolLocation":213,"imageIndex":11},{"imageOffset":5606357,"symbol":"-[NSRunLoop(NSRunLoop) runUntilDate:]","symbolLocation":72,"imageIndex":11},{"imageOffset":15792262,"symbol":"-[UIEventFetcher threadMain]","symbolLocation":535,"imageIndex":4},{"imageOffset":5775811,"symbol":"__NSThread__start__","symbolLocation":1009,"imageIndex":11},{"imageOffset":25825,"symbol":"_pthread_start","symbolLocation":125,"imageIndex":9},{"imageOffset":8043,"symbol":"thread_start","symbolLocation":15,"imageIndex":9}]}], "usedImages" : [ { "source" : "P", "arch" : "x86_64", "base" : 140703353880576, "size" : 4968437, "uuid" : "1d23cd50-8b48-349b-9163-f7990e0f95bd", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/usr\/lib\/swift\/libswiftCore.dylib", "name" : "libswiftCore.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 4499529728, "CFBundleShortVersionString" : "4.1.17.100", "CFBundleIdentifier" : "com.apple.SwiftUI", "size" : 23957504, "uuid" : "1622c162-0a3a-354c-94ea-62c5dd369612", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/Frameworks\/SwiftUI.framework\/SwiftUI", "name" : "SwiftUI", "CFBundleVersion" : "4.1.17.100" }, { "source" : "P", "arch" : "x86_64", "base" : 4430282752, "CFBundleShortVersionString" : "1.0", "CFBundleIdentifier" : "Partyhallen.Previewtest", "size" : 32768, "uuid" : "a989b4b0-9e28-34db-865c-bbcabac9f176", "path" : "\/Users\/USER\/Library\/Developer\/Xcode\/UserData\/Previews\/Simulator Devices\/B5B42958-9616-46D6-A056-B44D3D125005\/data\/Containers\/Bundle\/Application\/E4B38613-49C2-4582-9650-7295F743C525\/Previewtest.app\/Previewtest", "name" : "Previewtest", "CFBundleVersion" : "1" }, { "source" : "P", "arch" : "x86_64", "base" : 4534784000, "size" : 16384, "uuid" : "5d91714e-5553-3450-88be-8850c5896cb4", "path" : "\/Users\/USER\/Library\/Developer\/Xcode\/DerivedData\/Previewtest-haqnqqxsierjlvhdmnfotfqgnorc\/Build\/Intermediates.noindex\/Previews\/Previewtest\/Intermediates.noindex\/Previewtest.build\/Debug-iphonesimulator\/Previewtest.build\/Objects-normal\/x86_64\/ContentView.1.preview-thunk.dylib", "name" : "ContentView.1.preview-thunk.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 4437446656, "CFBundleShortVersionString" : "1.0", "CFBundleIdentifier" : "com.apple.UIKitCore", "size" : 28037120, "uuid" : "c2258b63-cdcc-3504-a06e-8067adba9c34", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/PrivateFrameworks\/UIKitCore.framework\/UIKitCore", "name" : "UIKitCore", "CFBundleVersion" : "6109.1.108" }, { "source" : "P", "arch" : "x86_64", "base" : 140703131770880, "CFBundleShortVersionString" : "6.9", "CFBundleIdentifier" : "com.apple.CoreFoundation", "size" : 3706877, "uuid" : "55edff37-af14-3fed-b932-031049d0a665", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/Frameworks\/CoreFoundation.framework\/CoreFoundation", "name" : "CoreFoundation", "CFBundleVersion" : "1953.1" }, { "source" : "P", "arch" : "x86_64", "base" : 140703292559360, "CFBundleShortVersionString" : "1.0", "CFBundleIdentifier" : "com.apple.GraphicsServices", "size" : 32755, "uuid" : "5dad91c5-e70d-3f9a-88f2-2d1ed7c8dd24", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/PrivateFrameworks\/GraphicsServices.framework\/GraphicsServices", "name" : "GraphicsServices", "CFBundleVersion" : "1.0" }, { "source" : "P", "arch" : "x86_64", "base" : 4432740352, "size" : 393216, "uuid" : "638f8a1f-2a32-396d-8389-8d7a60b96b8d", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/usr\/lib\/dyld_sim", "name" : "dyld_sim" }, { "source" : "P", "arch" : "x86_64", "base" : 4638285824, "size" : 442368, "uuid" : "71febccd-d9dc-3599-9971-2b3407c588a8", "path" : "\/usr\/lib\/dyld", "name" : "dyld" }, { "source" : "P", "arch" : "x86_64", "base" : 140704013840384, "size" : 49144, "uuid" : "b5454e27-e8c7-3fdb-b77f-714f1e82e70b", "path" : "\/usr\/lib\/system\/libsystem_pthread.dylib", "name" : "libsystem_pthread.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 140704013475840, "size" : 229376, "uuid" : "8cc28466-fd2f-3c80-9834-9525b7beac19", "path" : "\/usr\/lib\/system\/libsystem_kernel.dylib", "name" : "libsystem_kernel.dylib" }, { "source" : "P", "arch" : "x86_64", "base" : 140703135944704, "CFBundleShortVersionString" : "6.9", "CFBundleIdentifier" : "com.apple.Foundation", "size" : 9637885, "uuid" : "353e6739-fc3a-3636-89f2-194adba7203b", "path" : "\/Applications\/Xcode.app\/Contents\/Developer\/Platforms\/iPhoneOS.platform\/Library\/Developer\/CoreSimulator\/Profiles\/Runtimes\/iOS.simruntime\/Contents\/Resources\/RuntimeRoot\/System\/Library\/Frameworks\/Foundation.framework\/Foundation", "name" : "Foundation", "CFBundleVersion" : "1953.1" } ], "sharedCache" : { "base" : 140703128616960, "size" : 2998861824, "uuid" : "3140e7f6-3cc2-3fac-81dd-5fbfbbe796e1" }, "vmSummary" : "ReadOnly portion of Libraries: Total=803.7M resident=0K(0%) swapped_out_or_unallocated=803.7M(100%)\nWritable regions: Total=575.2M written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=575.2M(100%)\n\n VIRTUAL REGION \nREGION TYPE SIZE COUNT (non-coalesced) \n=========== ======= ======= \nActivity Tracing 256K 1 \nCG raster data 8K 1 \nColorSync 88K 5 \nCoreAnimation 20K 1 \nFoundation 16K 1 \nKernel Alloc Once 8K 1 \nMALLOC 177.5M 30 \nMALLOC guard page 32K 8 \nMALLOC_NANO (reserved) 384.0M 1 reserved VM address space (unallocated)\nSTACK GUARD 56.0M 7 \nStack 11.0M 7 \nVM_ALLOCATE 1052K 4 \n__DATA 11.3M 398 \n__DATA_CONST 36.7M 402 \n__DATA_DIRTY 26K 12 \n__FONT_DATA 2352 1 \n__LINKEDIT 358.0M 33 \n__OBJC_RO 28.3M 1 \n__OBJC_RW 880K 1 \n__TEXT 445.8M 410 \ndyld private memory 1280K 2 \nmapped file 206.8M 11 \nshared memory 16K 1 \n=========== ======= ======= \nTOTAL 1.7G 1339 \nTOTAL, minus reserved VM space 1.3G 1339 \n", "legacyInfo" : { "threadTriggered" : { "queue" : "com.apple.main-thread" } }, "trialInfo" : { "rollouts" : [ { "rolloutId" : "63582c5f8a53461413999550", "factorPackIds" : { }, "deploymentId" : 240000002 }, { "rolloutId" : "60f8ddccefea4203d95cbeef", "factorPackIds" : { }, "deploymentId" : 240000021 } ], "experiments" : [ ] } } Here is my code: import SwiftUI import Foundation @main struct PreviewtestApp: App { var body: some Scene { WindowGroup { AppContainerView() } } } import SwiftUI import Foundation struct AppContainerView: View { @StateObject var router = Router() var body: some View { NavigationStack(path: $router.navigationPath) { ContentView() .navigationDestination(for: Route.self) { route in switch route { case .ContentView: ContentView() } } }.environmentObject(router) } } import SwiftUI import Foundation struct ContentView: View { @EnvironmentObject private var router: Router var body: some View { VStack { Text("Hello, world!") .onTapGesture { router.pushView(route: .ContentView) } } .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } import Foundation import SwiftUI enum Route: Hashable { case ContentView } final class Router: ObservableObject { @Published var navigationPath = NavigationPath() func pushView(route: Route) { navigationPath.append(route) } func popToRootView() { navigationPath = .init() } func popToSpecificView(k: Int) { navigationPath.removeLast(k) } }
[ "@StateObject aren't init during previewing so that is probably causing the crash. You could workaround it by previewing AppContainerView instead of ContentView.\nBy the way, @StateObject is for when you need to store a reference type in a @State but in this example don't need a reference type. Also, NavigationPath is designed to hold the data values, not routes. You can use multiple navigationDestination for each kind of value, instead of one with a switch statement.\n" ]
[ 1 ]
[]
[]
[ "swift", "swiftui", "swiftui_navigationview" ]
stackoverflow_0074662515_swift_swiftui_swiftui_navigationview.txt
Q: Chrome Extension suddenly not working, Errors page is blank I'm new to Chrome Extensions and am trying to make a simple 'Hello World' extension - all it does is inject a .css file that makes 'h1' tags red. This worked fine, until today when I resumed working on it and couldn't get it to work again. I noticed there is an Errors button against the Extension chrome://extensions/, but clicking it reveals nothing - a blank page. I removed and re-installed the extension, but the issue remains. I am not getting any other errors and am stumped as to why this suddenly stopped working. Would anyone know if I've done anything wrong? My Manifest (V3) file: { "name": "Hello World", "description": "Test", "version": "0.1.0", "manifest_version": 3, "icons": { "16": "/images/icon-16x16.png", "32": "/images/icon-32x32.png", "48": "/images/icon-48x48.png", "128": "/images/icon-128x128.png" }, "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html", "default_icon": { "16": "/images/icon-16x16.png", "32": "/images/icon-32x32.png", "48": "/images/icon-48x48.png", "128": "/images/icon-128x128.png" } }, "options_page": "options.html", "permissions": [ "storage", "activeTab", "scripting", "tabs" ] } My background.js file: chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (changeInfo.status === 'complete' && /^http/(tab.url)) { chrome.scripting.insertCSS({ target: { tabId: tabId }, files: ["./styles.css"] }) .then(() => { console.log("INJECTED THE FOREGROUND STYLES."); }) .catch(err => console.log(err)); } }); styles.css simply contains: h1 { color: red !important; } My popup.html: <!doctype html> <html> <head> <title>Hello World</title> </head> <body> <div><p>Hello World</p></div> </body> </html> And my options.html exists but is empty. Would anyone be able to point me in the right direction? A: An error is output to DevTools of the service worker. Error in event handler: TypeError: /^http/ is not a function at Here is where the error occurs. if (changeInfo.status === 'complete' && /^http/(tab.url)) {
Chrome Extension suddenly not working, Errors page is blank
I'm new to Chrome Extensions and am trying to make a simple 'Hello World' extension - all it does is inject a .css file that makes 'h1' tags red. This worked fine, until today when I resumed working on it and couldn't get it to work again. I noticed there is an Errors button against the Extension chrome://extensions/, but clicking it reveals nothing - a blank page. I removed and re-installed the extension, but the issue remains. I am not getting any other errors and am stumped as to why this suddenly stopped working. Would anyone know if I've done anything wrong? My Manifest (V3) file: { "name": "Hello World", "description": "Test", "version": "0.1.0", "manifest_version": 3, "icons": { "16": "/images/icon-16x16.png", "32": "/images/icon-32x32.png", "48": "/images/icon-48x48.png", "128": "/images/icon-128x128.png" }, "background": { "service_worker": "background.js" }, "action": { "default_popup": "popup.html", "default_icon": { "16": "/images/icon-16x16.png", "32": "/images/icon-32x32.png", "48": "/images/icon-48x48.png", "128": "/images/icon-128x128.png" } }, "options_page": "options.html", "permissions": [ "storage", "activeTab", "scripting", "tabs" ] } My background.js file: chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { if (changeInfo.status === 'complete' && /^http/(tab.url)) { chrome.scripting.insertCSS({ target: { tabId: tabId }, files: ["./styles.css"] }) .then(() => { console.log("INJECTED THE FOREGROUND STYLES."); }) .catch(err => console.log(err)); } }); styles.css simply contains: h1 { color: red !important; } My popup.html: <!doctype html> <html> <head> <title>Hello World</title> </head> <body> <div><p>Hello World</p></div> </body> </html> And my options.html exists but is empty. Would anyone be able to point me in the right direction?
[ "An error is output to DevTools of the service worker.\n\nError in event handler: TypeError: /^http/ is not a function\nat \n\nHere is where the error occurs.\n if (changeInfo.status === 'complete' && /^http/(tab.url)) {\n\n" ]
[ 2 ]
[]
[]
[ "chrome_extension_manifest_v3", "google_chrome_extension", "javascript" ]
stackoverflow_0074671379_chrome_extension_manifest_v3_google_chrome_extension_javascript.txt
Q: Scrape tweets by Python and BeautifulSoup I want to scrape the tweets of a specific account on Twitter via SB but it is not working for me this is my code : import facebook as fb from bs4 import BeautifulSoup as bs import requests myUrl = requests.get('https://twitter.com/search?q=(from%3AAlMosahf)&src=typed_query&f=live') source = myUrl.content soup = bs(source, 'html.parser') twi = soup.find_all('div', {'data-testid':'tweetText'}) myTW = twi[1].text print(myTW) The result is "list index out of range" .. because "twi" is empty A: It looks like you're trying to scrape Twitter using Beautiful Soup, but the code you've provided won't work for several reasons. First, the Twitter website uses JavaScript to dynamically generate its content, which means that the raw HTML you get from a requests.get() call won't include the tweets you're looking for. Instead, you'll need to use a tool that can execute the JavaScript on the page and return the fully-rendered HTML. Second, even if you were able to get the fully-rendered HTML, the code you've provided won't work because the data-testid attribute you're using to find the tweets doesn't exist on the page. You'll need to use a different approach to locate the tweets in the HTML. To scrape Twitter using Beautiful Soup, you'll need to use a different approach. One option is to use the Twitter API to retrieve the tweets you're interested in, and then use Beautiful Soup to parse the returned data. Here's an example of how you could do that: import tweepy from bs4 import BeautifulSoup as bs # Authenticate with the Twitter API auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # Get the tweets from the user with the username "AlMosahf" tweets = api.user_timeline(screen_name="AlMosahf") # Parse the tweets using Beautiful Soup for tweet in tweets: soup = bs(tweet.text, 'html.parser') # Do something with the parsed tweet A: The error you are seeing is because you are trying to access the second element of the twi list, but the list is empty. This means that the find_all() method did not find any elements that match the search criteria you specified. There are several reasons why this might happen, in general. One possible reason is that the page structure has changed, so the elements you are trying to find are no longer present on the page. Another possible reason (the reason in this scenario) is that the page uses JavaScript to dynamically generate its content, so the content you see in the browser may not be present in the initial HTML source that is downloaded by the requests library. To fix this error, you can try the following steps: Use the developer tools in your web browser to inspect the page and verify that the elements you are trying to find are actually present on the page. If the elements are present, try using a different method to extract the content. For example, you could use a different parsing library, or you could try using a web scraping framework like Scrapy or Selenium. If the elements are not present, you may need to use a different approach to extract the content. For example, you could try using the Twitter API to access the tweets directly, rather than trying to scrape them from the page. You can use the tweepy library to access the Twitter API and extract the tweets from a specific account. This can be a more reliable and efficient way to access the tweets, compared to scraping the page using BeautifulSoup. Here is an example of how you could use tweepy to extract the tweets from a specific account: import tweepy # Set up your API keys and access tokens consumer_key = 'your-consumer-key' consumer_secret = 'your-consumer-secret' access_token = 'your-access-token' access_token_secret = 'your-access-token-secret' # Authenticate with the Twitter API auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # Extract the tweets from the specified account account = 'AlMosahf' tweets = api.user_timeline(screen_name=account) # Print the tweets for tweet in tweets: print(tweet.text) This code uses the tweepy library to authenticate with the Twitter API and extract the tweets from the specified account. The tweets are then printed to the console. You can modify this code to suit your needs. For example, you could use the limit parameter to specify the number of tweets you want to extract, or you could use the since_id and max_id parameters to specify a date range for the tweets. For more information, you can refer to the tweepy documentation.
Scrape tweets by Python and BeautifulSoup
I want to scrape the tweets of a specific account on Twitter via SB but it is not working for me this is my code : import facebook as fb from bs4 import BeautifulSoup as bs import requests myUrl = requests.get('https://twitter.com/search?q=(from%3AAlMosahf)&src=typed_query&f=live') source = myUrl.content soup = bs(source, 'html.parser') twi = soup.find_all('div', {'data-testid':'tweetText'}) myTW = twi[1].text print(myTW) The result is "list index out of range" .. because "twi" is empty
[ "It looks like you're trying to scrape Twitter using Beautiful Soup, but the code you've provided won't work for several reasons.\nFirst, the Twitter website uses JavaScript to dynamically generate its content, which means that the raw HTML you get from a requests.get() call won't include the tweets you're looking for. Instead, you'll need to use a tool that can execute the JavaScript on the page and return the fully-rendered HTML.\nSecond, even if you were able to get the fully-rendered HTML, the code you've provided won't work because the data-testid attribute you're using to find the tweets doesn't exist on the page. You'll need to use a different approach to locate the tweets in the HTML.\nTo scrape Twitter using Beautiful Soup, you'll need to use a different approach. One option is to use the Twitter API to retrieve the tweets you're interested in, and then use Beautiful Soup to parse the returned data. Here's an example of how you could do that:\nimport tweepy\nfrom bs4 import BeautifulSoup as bs\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Get the tweets from the user with the username \"AlMosahf\"\ntweets = api.user_timeline(screen_name=\"AlMosahf\")\n\n# Parse the tweets using Beautiful Soup\nfor tweet in tweets:\n soup = bs(tweet.text, 'html.parser')\n # Do something with the parsed tweet\n\n", "The error you are seeing is because you are trying to access the second element of the twi list, but the list is empty. This means that the find_all() method did not find any elements that match the search criteria you specified.\nThere are several reasons why this might happen, in general. One possible reason is that the page structure has changed, so the elements you are trying to find are no longer present on the page. Another possible reason (the reason in this scenario) is that the page uses JavaScript to dynamically generate its content, so the content you see in the browser may not be present in the initial HTML source that is downloaded by the requests library.\nTo fix this error, you can try the following steps:\n\nUse the developer tools in your web browser to inspect the page and verify that the elements you are trying to find are actually present on the page.\nIf the elements are present, try using a different method to extract the content. For example, you could use a different parsing library, or you could try using a web scraping framework like Scrapy or Selenium.\nIf the elements are not present, you may need to use a different approach to extract the content. For example, you could try using the Twitter API to access the tweets directly, rather than trying to scrape them from the page.\n\nYou can use the tweepy library to access the Twitter API and extract the tweets from a specific account. This can be a more reliable and efficient way to access the tweets, compared to scraping the page using BeautifulSoup.\nHere is an example of how you could use tweepy to extract the tweets from a specific account:\nimport tweepy\n\n# Set up your API keys and access tokens\nconsumer_key = 'your-consumer-key'\nconsumer_secret = 'your-consumer-secret'\naccess_token = 'your-access-token'\naccess_token_secret = 'your-access-token-secret'\n\n# Authenticate with the Twitter API\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\n\n# Extract the tweets from the specified account\naccount = 'AlMosahf'\ntweets = api.user_timeline(screen_name=account)\n\n# Print the tweets\nfor tweet in tweets:\n print(tweet.text)\n\nThis code uses the tweepy library to authenticate with the Twitter API and extract the tweets from the specified account. The tweets are then printed to the console.\nYou can modify this code to suit your needs. For example, you could use the limit parameter to specify the number of tweets you want to extract, or you could use the since_id and max_id parameters to specify a date range for the tweets. For more information, you can refer to the tweepy documentation.\n" ]
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074669065_beautifulsoup_python.txt
Q: Deploy multiple databases with SSDT We have an existing system with multiple databases on one SQL Server instance, and we want to deploy database changes using SQL Server Data Tools. Thus I've created a solution with one database project per database. When I run a build, it creates a .dacpac file for each project. Ideally we want to bundle the deployment of database changes, such that all databases are deployed in one shot. I've seen that database projects can reference other projects and suppose that you can use this mechanism for bundling as well - but I am reluctant to add references just for the sake of deployment. What is the recommended way to deploy multiple databases in one package? A: I don't think you can do this. By default, each database gets its own dacpac. You can set up a script that can build/publish all databases in one shot, but it will do them one at a time. I created a basic batch file some time ago that would build all of the dacpacs and publish each of them in order. A: Surprising there isn’t a solid answer to this. I know red gate has sql automate tool, but your company will have to pay for it. Interested if you got a solid answer
Deploy multiple databases with SSDT
We have an existing system with multiple databases on one SQL Server instance, and we want to deploy database changes using SQL Server Data Tools. Thus I've created a solution with one database project per database. When I run a build, it creates a .dacpac file for each project. Ideally we want to bundle the deployment of database changes, such that all databases are deployed in one shot. I've seen that database projects can reference other projects and suppose that you can use this mechanism for bundling as well - but I am reluctant to add references just for the sake of deployment. What is the recommended way to deploy multiple databases in one package?
[ "I don't think you can do this. By default, each database gets its own dacpac. You can set up a script that can build/publish all databases in one shot, but it will do them one at a time. I created a basic batch file some time ago that would build all of the dacpacs and publish each of them in order.\n", "Surprising there isn’t a solid answer to this. I know red gate has sql automate tool, but your company will have to pay for it. Interested if you got a solid answer\n" ]
[ 2, 0 ]
[]
[]
[ "sql_server", "sql_server_data_tools" ]
stackoverflow_0051615598_sql_server_sql_server_data_tools.txt
Q: Dicts not being popped from list? The context doesn't matter too much, but I came across the problem that while trying to pop dict objects from a list, it wouldn't delete all of them. I'm doing this to filter for certain values in the dict objects, and I was left with things that should have been removed. Just to see what would happen, I tried deleting every item in the list called accepted_auctions (shown below), but it did not work. for auction in accepted_auctions: accepted_auctions.pop(accepted_auctions.index(auction)) print(len(accepted_auctions)) When I tested this code, print(len(accepted_auctions)) printed 44 into the console. What am I doing wrong? A: It looks like you're using a for loop to iterate over the list and calling pop on the list at the same time. This is generally not a good idea because the for loop uses an iterator to go through the items in the list, and modifying the list while you're iterating over it can cause the iterator to become confused and not behave as expected. One way to fix this is to create a new list that contains only the items that you want to keep, and then replace the original list with the new one. Here's an example: # Create an empty list to store the items that we want to keep filtered_auctions = [] # Iterate over the items in the list for auction in accepted_auctions: # Check if the item meets the criteria for being kept if some_condition(auction): # If it does, append it to the filtered list filtered_auctions.append(auction) # Replace the original list with the filtered list accepted_auctions = filtered_auctions Another way to fix this is to use a while loop instead of a for loop. Here's an example: # Keep looping until the list is empty while accepted_auctions: # Pop the first item from the list auction = accepted_auctions.pop(0) # Check if the item meets the criteria for being kept if some_condition(auction): # If it does, append it to the filtered list filtered_auctions.append(auction) # Replace the original list with the filtered list accepted_auctions = filtered_auctions I hope this helps! Let me know if you have any other questions. A: Modifying a list as you iterate over it will invalidate the iterator (because the indices of all the items are changing as you remove items), which in turn causes it to skip items. Don't do that. The easiest way to create a filtered list is via a list comprehension that creates a new list, e.g.: accepted_auctions = [a for a in accepted_auctions if something(a)] Here's a simple example using a list comprehension to filter a list of ints to only the odd numbers: >>> nums = list(range(10)) >>> nums [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> nums = [n for n in nums if n % 2] >>> nums [1, 3, 5, 7, 9]
Dicts not being popped from list?
The context doesn't matter too much, but I came across the problem that while trying to pop dict objects from a list, it wouldn't delete all of them. I'm doing this to filter for certain values in the dict objects, and I was left with things that should have been removed. Just to see what would happen, I tried deleting every item in the list called accepted_auctions (shown below), but it did not work. for auction in accepted_auctions: accepted_auctions.pop(accepted_auctions.index(auction)) print(len(accepted_auctions)) When I tested this code, print(len(accepted_auctions)) printed 44 into the console. What am I doing wrong?
[ "It looks like you're using a for loop to iterate over the list and calling pop on the list at the same time. This is generally not a good idea because the for loop uses an iterator to go through the items in the list, and modifying the list while you're iterating over it can cause the iterator to become confused and not behave as expected.\nOne way to fix this is to create a new list that contains only the items that you want to keep, and then replace the original list with the new one. Here's an example:\n# Create an empty list to store the items that we want to keep\nfiltered_auctions = []\n\n# Iterate over the items in the list\nfor auction in accepted_auctions:\n # Check if the item meets the criteria for being kept\n if some_condition(auction):\n # If it does, append it to the filtered list\n filtered_auctions.append(auction)\n\n# Replace the original list with the filtered list\naccepted_auctions = filtered_auctions\n\nAnother way to fix this is to use a while loop instead of a for loop. Here's an example:\n# Keep looping until the list is empty\nwhile accepted_auctions:\n # Pop the first item from the list\n auction = accepted_auctions.pop(0)\n\n # Check if the item meets the criteria for being kept\n if some_condition(auction):\n # If it does, append it to the filtered list\n filtered_auctions.append(auction)\n\n# Replace the original list with the filtered list\naccepted_auctions = filtered_auctions\n\nI hope this helps! Let me know if you have any other questions.\n", "Modifying a list as you iterate over it will invalidate the iterator (because the indices of all the items are changing as you remove items), which in turn causes it to skip items. Don't do that.\nThe easiest way to create a filtered list is via a list comprehension that creates a new list, e.g.:\naccepted_auctions = [a for a in accepted_auctions if something(a)]\n\nHere's a simple example using a list comprehension to filter a list of ints to only the odd numbers:\n>>> nums = list(range(10))\n>>> nums\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> nums = [n for n in nums if n % 2]\n>>> nums\n[1, 3, 5, 7, 9]\n\n" ]
[ 3, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074671420_python_python_3.x.txt
Q: Android Studio - XML Editor autocomplete not working with support libraries I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions! For example, <android.support.design.widget.CoordinatorLayout android:id="@+id/header_root" android:layout_width="match_parent" android:layout_height="200dp"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/primary_dark" /> <android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|right" android:src="@drawable/ic_action_add" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginTop="56dp" app:fabSize="normal" app:layout_anchor="@id/header_root" app:layout_anchorGravity="bottom|right|end" /> </android.support.design.widget.CoordinatorLayout> None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture. I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working! A: If NONE of the above answers worked, ... Just navigate to your android studio installation directory, i.e, yourDrive:/.AndroidStudio3.3/system and DELETE THE CACHE FOLDER ( first close android studio, if its running ). Then start Android Studio again. Done. P.S I am using android studio 4.0 A: I have tried a lot of things (restart Android Studio, PC, Invalidate Caches, Power Saver mode,...). Finally, deleting the .idea folder and all .iml files from the project, restarting Android Studio, and rebuilding Gradle did the trick. Autocomplete in XML support library is working again. Checking out files from Version Control or copying all the source files in a new project would do the trick as well. A: The answer for me was to switch to lower sdk when compiling project, I think this is platform problem. I was using sdk 33. Change in build.gradle compileSdk=32 Edit: It seems that it is also fixed in newest Android Studio version A: I got my autocomplete suggestions back by invalidating Caches and restarting. File -> Invalidate Caches / Restart... -> Select Invalidate and Restart A: This same problem appeared in version 3.2. . The solution for that is Close Android Studio Go to C:\Users\UserName\.android and rename the build-cache folder to build-cache.bak Go to C:\Users\UserName\.AndroidStudio3.2\system and rename these folders caches to caches.bak compiler to compiler.bak compile-server to compile-server.bak conversion to conversion.bak external_build_system to external_build_system.bak frameworks to frameworks.bak gradle to gradle.bak resource_folder_cache to resource_folder_cache.bak Open the Android Studio and open your project again. A: If NONE of the above worked ... Just navigate to your android studio installation directory, i.e, yourDrive:/.AndroidStudio3.4/system first close android studio, if its running. then delete the cache folder in system Then start Android Studio again. Done. i am using android studio 3.4 A: I try to downgrade the "Compile SDK Version" from 29 to 28 and it's works good A: The Santanu Sur answer works for me! But in Windows I found these folders in %USERNAME%/.AndroidStudio3.4 or %USERNAME%/.AndroidStudio3.3 I deleted these two folders and it worked well finally. A: Deleting Library/Application Support/AndroidStudio* folder and Invalidate Cache after that helped me. All other options didn't work. A: A few years too late, but I wanted to submit an answer to this that I figured out and worked for me. It was very quick and didnt require a lot of reconfiguration as some of other answers on here had, so I thought I'd add it. Solution Comment the gradle dependencies for xml attributes, sync the project, and then un-comment them and sync it again. For me, resyncing these three with and then without the comments was enough to get them to start coming up again. //implementation 'com.android.support:appcompat-v7:27.1.1' //implementation 'com.android.support.constraint:constraint-layout:1.1.3' //implementation 'com.android.support:design:27.1.1' And don't worry if your build fails after the first step, it should if you already have any of those attributes in your project. Another note, the attributes that I had previously put in (without the autocomplete before the resync) needed to be re-inputted for some reason. A: If you use compileSdkVersion 33, upgrade your Android Studio to Dolphin. It worked for me. A: I got in a situation where only the EditText tag was broken. I've deleted the .idea folder and all .iml, invalidated the cache and restarted... What actually worked was to erase the tag and type it again. Really Odd. A: I too faced this issue and this was only happening on an imported module class. Tried everything like deleting .idea folder, power saver mode, invalidate cache and restart, etc. Finally updating compileSdkVersion and buildToolsVersion of the module to match with the app module fixed the issue. In my case I was using: compileSdkVersion 29 buildToolsVersion '29.0.3' A: In my case Code Completion suggestions were not appearing because Gradle dependency was missing in my application's module. I was using android.support.design.widget.TabLayout in my XML layout, but I have not added Design Support Library compile 'com.android.support:design:25.3.1' Gradle dependency in my application module. A: If you're having this problem in November 2018 with Android Studio 3.2.1, you should try downgrading it to 3.1.4. With 3.2.1 i tried every of this answers and didn't work, but after i downgraded to 3.1.4 and did the Invalidate Caches / Restart it worked fine. A: I tried with Invalid caches/restart option but it didn't work for me. For Android Studio 3> versions check following first: compileSdkVersion targetSdkVersion buildToolsVersion Set these 3 to the latest version and then try to sync the project and clean, ReBuild once. It will work and show the XML editor autocomplete options. A: Delete the complete folder ` of the android studio and then restarting it. Solve the problem driveLocation:/.AndroidStudio3.3 .AndroidStudio3.3 may be different in your case A: One possibility is to check power mode in the android studio. Go to File > Power mode and check it's on or off. If it is on, You also will not get any suggestions. To get suggestions, It must be off. If it doesn't work for you then you should reset your Android studio which will set the default configuration for you. For that, find out .AndroidStudioBeta or .AndroidStudio folder and delete those and restart the android studio. Generally, you will get this folder into users\[user name]\.AndroidStudio3.3. Let me know if it helps you then. Happy coding..! A: Tried everything like deleting .idea folder, power saver mode, deleting cache folder under user/.android , invalidate cache and restart, etc nothing worked. Setting compileSdkVersion 31 (latest till date) worked for me. A: As this just happened to me, working with Android Studio Chipmunk Patch 2. and nothing of the above answers worked so targeting SDK version number 33 causing this error lowering it solved the issue defaultConfig { targetSdkVersion = 30 compileSdkVersion = 30 } A: Solved by deleting '.androidStudioPreview1.X' in my home folder. A: I too got in a situation where only the EditText tag was broken. The solution was found in Setting > Editor >General > Auto Import where Edit Text was listed as excluded from auto completion. Remove that by select and click Minus sign. A: File -> Invalidate Caches / Restart... -> Select Invalidate and Restart and turn of power save mode it does works A: The best option is to make a zip folder of the project and change its path.(Relocate this project than open it). This will do the needful. A: Check 5 ways: Restart Android Studio File -> Invalidate Caches / Restart... -> Select Invalidate and Restart File -> turn of power save mode and restart Android Studio Delete .idea folder. Search for *.iml files and delete all those and use way number 2 A: Change to an older version in build.gradle(Module: app) -Make sure is the one under Gradle Script and it is NOT build.gradle(Project: yourproject). After getting XML autocomplete suggestions change to the current version. A: My issue was that I tried to autocomplete on an xml layout file inside res/xml. Autocomplete does not work there for layout files. Moving the xml file to res/layout made autocomplete work again. A: I just tried waiting for 10 seconds and the auto-complete suggestions appeared(Using Android Studio 4.2) , it seems that the xml just takes some time to resolve them.And no my PC is not slow. A: I share my answer for Android studio 4.2: I had to delete folder C:\Users\Username\.gradle\caches A: just go to gradle-wrapper.properties and update version gradle...zip my version is gradle-6.7.1-all.zip and restart android studio A: Invalidate Caches / Restart worked for me. ==> Go to File Menu on top left corner of android studio ==> Select Invalidate Caches / Restart A: I have this issue when doing my project. I tried everything: Delete every folders if I can; Un-install; Reset to default (I actually search SO for this); Invalidate Cache; Create a very new project for test; Etc... All of those have no resolve problem Now I have a final way to do: use Intellji instead of Android Studio and I am very happy now. This is advice for anyone who suffered by this issue A: use this lib implementation 'com.android.support.constraint:constraint-layout:1.1.3' and Do invalidating Caches and restarting. A: I tried all, Invalidate Cache, Restart, Clean, and rebuild the project. Downgrading from SDK 33 to 30 also I did after searching. Nothing worked. In the end, I updated my Android Studio from Chipmunk to Dolphin. Everything is sorted now. So the final conclusion that worked for me is: Update the Android Studio A: the implementation 'androidx.core:core-ktx:1.9.0' need compileSdk 33 just change ktx to implementation 'androidx.core:core-ktx:1.7.2 and sdk version to compileSdk 33 . this worked for me. GL A: If u have updated ur compileSdkVersion 33. Decrease it. It works in my case compileSdkVersion 32 targetSdkVersion 32
Android Studio - XML Editor autocomplete not working with support libraries
I just started using the new android.support.design library. When using any of the widgets inside the XML editor I stop getting the XML autocomplete suggestions! For example, <android.support.design.widget.CoordinatorLayout android:id="@+id/header_root" android:layout_width="match_parent" android:layout_height="200dp"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/primary_dark" /> <android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|right" android:src="@drawable/ic_action_add" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginTop="56dp" app:fabSize="normal" app:layout_anchor="@id/header_root" app:layout_anchorGravity="bottom|right|end" /> </android.support.design.widget.CoordinatorLayout> None of the tags will show the autocomplete popup, like when I start typing "android:i" no popup appears, the only suggestion I get is shown in the following picture. I have tried cleaning my project, restarting the pc, restarting Android Studio.. nothing is working!
[ "If NONE of the above answers worked, ...\nJust navigate to your android studio installation directory, i.e, \nyourDrive:/.AndroidStudio3.3/system\n\nand DELETE THE CACHE FOLDER ( first close android studio, if its running ).\nThen start Android Studio again. Done.\nP.S I am using android studio 4.0\n", "I have tried a lot of things (restart Android Studio, PC, Invalidate Caches, Power Saver mode,...).\nFinally, deleting the .idea folder and all .iml files from the project, restarting Android Studio, and rebuilding Gradle did the trick. Autocomplete in XML support library is working again.\nChecking out files from Version Control or copying all the source files in a new project would do the trick as well.\n", "The answer for me was to switch to lower sdk when compiling project, I think this is platform problem. I was using sdk 33.\nChange in build.gradle\ncompileSdk=32\n\nEdit: It seems that it is also fixed in newest Android Studio version\n", "I got my autocomplete suggestions back by invalidating Caches and restarting. \nFile -> Invalidate Caches / Restart... -> Select Invalidate and Restart\n", "This same problem appeared in version 3.2. . The solution for that is \nClose Android Studio\nGo to C:\\Users\\UserName\\.android and rename the build-cache folder to build-cache.bak\n\nGo to C:\\Users\\UserName\\.AndroidStudio3.2\\system and rename these folders\n\ncaches to caches.bak\n\ncompiler to compiler.bak\n\ncompile-server to compile-server.bak\n\nconversion to conversion.bak\n\nexternal_build_system to external_build_system.bak\n\nframeworks to frameworks.bak\n\ngradle to gradle.bak\n\nresource_folder_cache to resource_folder_cache.bak\n\nOpen the Android Studio and open your project again.\n\n", "If NONE of the above worked ...\nJust navigate to your android studio installation directory, i.e,\nyourDrive:/.AndroidStudio3.4/system\nfirst close android studio, if its running.\nthen delete the cache folder in system\nThen start Android Studio again. Done.\ni am using android studio 3.4\n", "I try to downgrade the \"Compile SDK Version\" from 29 to 28 and it's works good\n", "The Santanu Sur answer works for me! But in Windows I found these folders in %USERNAME%/.AndroidStudio3.4 or %USERNAME%/.AndroidStudio3.3\nI deleted these two folders and it worked well finally.\n", "Deleting Library/Application Support/AndroidStudio* folder and Invalidate Cache after that helped me. All other options didn't work.\n", "A few years too late, but I wanted to submit an answer to this that I figured out and worked for me. It was very quick and didnt require a lot of reconfiguration as some of other answers on here had, so I thought I'd add it.\nSolution\nComment the gradle dependencies for xml attributes, sync the project, and then un-comment them and sync it again. For me, resyncing these three with and then without the comments was enough to get them to start coming up again. \n//implementation 'com.android.support:appcompat-v7:27.1.1'\n//implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n//implementation 'com.android.support:design:27.1.1'\n\nAnd don't worry if your build fails after the first step, it should if you already have any of those attributes in your project. Another note, the attributes that I had previously put in (without the autocomplete before the resync) needed to be re-inputted for some reason.\n", "If you use compileSdkVersion 33, upgrade your Android Studio to Dolphin. It worked for me.\n", "I got in a situation where only the EditText tag was broken. I've deleted the .idea folder and all .iml, invalidated the cache and restarted... What actually worked was to erase the tag and type it again. Really Odd.\n", "I too faced this issue and this was only happening on an imported module class. Tried everything like deleting .idea folder, power saver mode, invalidate cache and restart, etc.\nFinally updating compileSdkVersion and buildToolsVersion of the module to match with the app module fixed the issue. \nIn my case I was using:\n compileSdkVersion 29\n buildToolsVersion '29.0.3'\n\n", "In my case Code Completion suggestions were not appearing because Gradle dependency was missing in my application's module.\nI was using android.support.design.widget.TabLayout in my XML layout, but I have not added Design Support Library compile 'com.android.support:design:25.3.1' Gradle dependency in my application module.\n", "If you're having this problem in November 2018 with Android Studio 3.2.1, you should try downgrading it to 3.1.4.\nWith 3.2.1 i tried every of this answers and didn't work, but after i downgraded to 3.1.4 and did the Invalidate Caches / Restart it worked fine.\n", "I tried with Invalid caches/restart option but it didn't work for me.\nFor Android Studio 3> versions check following first:\ncompileSdkVersion\ntargetSdkVersion\nbuildToolsVersion\n\nSet these 3 to the latest version and then try to sync the project and clean, ReBuild once. It will work and show the XML editor autocomplete options.\n", "Delete the complete folder ` of the android studio and then restarting it. Solve the problem\n\ndriveLocation:/.AndroidStudio3.3\n\n.AndroidStudio3.3 may be different in your case \n", "One possibility is to check power mode in the android studio. Go to File > Power mode and check it's on or off. \nIf it is on, You also will not get any suggestions. To get suggestions, It must be off. \nIf it doesn't work for you then you should reset your Android studio which will set the default configuration for you. \nFor that, find out .AndroidStudioBeta or .AndroidStudio folder and delete those and restart the android studio. Generally, you will get this folder into users\\[user name]\\.AndroidStudio3.3.\nLet me know if it helps you then. Happy coding..!\n", "Tried everything like deleting .idea folder, power saver mode, deleting cache folder under user/.android , invalidate cache and restart, etc nothing worked.\nSetting compileSdkVersion 31 (latest till date) worked for me.\n", "As this just happened to me, working with Android Studio Chipmunk Patch 2. and nothing of the above answers worked so targeting SDK version number 33 causing this error lowering it solved the issue\n defaultConfig {\n targetSdkVersion = 30\n compileSdkVersion = 30 }\n\n", "Solved by deleting '.androidStudioPreview1.X' in my home folder.\n", "I too got in a situation where only the EditText tag was broken. The solution was found in Setting > Editor >General > Auto Import where Edit Text was listed as excluded from auto completion. Remove that by select and click Minus sign. \n", "File -> Invalidate Caches / Restart... -> Select Invalidate and Restart\nand turn of power save mode it does works\n", "The best option is to make a zip folder of the project and change its path.(Relocate this project than open it).\nThis will do the needful.\n", "Check 5 ways:\n\nRestart Android Studio\nFile -> Invalidate Caches / Restart... -> Select Invalidate and Restart\nFile -> turn of power save mode and restart Android Studio\nDelete .idea folder. Search for *.iml files and delete all those and use way number 2\n\n", "Change to an older version in build.gradle(Module: app) -Make sure is the one under Gradle Script and it is NOT build.gradle(Project: yourproject). After getting XML autocomplete suggestions change to the current version.\n", "My issue was that I tried to autocomplete on an xml layout file inside res/xml. Autocomplete does not work there for layout files. Moving the xml file to res/layout made autocomplete work again.\n", "I just tried waiting for 10 seconds and the auto-complete suggestions appeared(Using Android Studio 4.2) , it seems that the xml just takes some time to resolve them.And no my PC is not slow.\n", "I share my answer for Android studio 4.2:\nI had to delete folder C:\\Users\\Username\\.gradle\\caches\n", "just go to gradle-wrapper.properties and update version gradle...zip\nmy version is gradle-6.7.1-all.zip\nand restart android studio\n", "Invalidate Caches / Restart worked for me.\n==> Go to File Menu on top left corner of android studio\n==> Select Invalidate Caches / Restart\n", "I have this issue when doing my project.\nI tried everything:\nDelete every folders if I can;\nUn-install;\nReset to default (I actually search SO for this);\nInvalidate Cache;\nCreate a very new project for test;\nEtc... All of those have no resolve problem\nNow I have a final way to do: use Intellji instead of Android Studio and I am very happy now. This is advice for anyone who suffered by this issue\n", "use this lib\nimplementation 'com.android.support.constraint:constraint-layout:1.1.3'\nand Do invalidating Caches and restarting.\n", "I tried all, Invalidate Cache, Restart, Clean, and rebuild the project. Downgrading from SDK 33 to 30 also I did after searching. Nothing worked.\nIn the end, I updated my Android Studio from Chipmunk to Dolphin. Everything is sorted now.\nSo the final conclusion that worked for me is: Update the Android Studio\n", "the implementation 'androidx.core:core-ktx:1.9.0' need compileSdk 33 just change ktx to implementation 'androidx.core:core-ktx:1.7.2 and sdk version to compileSdk 33 .\nthis worked for me.\nGL\n", "If u have updated ur compileSdkVersion 33. Decrease it.\nIt works in my case\ncompileSdkVersion 32\n targetSdkVersion 32\n\n" ]
[ 145, 132, 93, 39, 32, 25, 7, 5, 3, 3, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "What worked for me was renaming $USERDIR/.AndroidStudio3.3/system folder and restarting AS. \n" ]
[ -1 ]
[ "android", "android_studio", "autocomplete" ]
stackoverflow_0030684613_android_android_studio_autocomplete.txt
Q: Jest: How to test for optional object keys Say, I have an object below const obj1 = {name: expect.any(String)} Backend return response as below with object the key 'age' as optional key const response = {name: 'bbb', age: 10} So, how can I assert obj1 have age as the optional key, which means if it exists, it must be number type, if it doesn't exist, we can omit the checking ? expect(response).toMatchObject(obj1); A: I don't think there's a built-in function for that, but toMatchObject along with destructuring can do what you need: expect({ age: 0, ...response }).toMatchObject(obj1); If age is not present in the object, it will assume 0; if it is present, it will use the present value and therefore fail if it's the wrong type. A: You can use a special matcher .toHaveProperty provided by Jest to check whether a property exists in an object. This matcher also allows you to check the value of the property. In your case, you can use the .toHaveProperty matcher to check if the response object has the optional age property and that its value is a number. Here's an example: const response = {name: 'bbb', age: 10}; expect(response).toHaveProperty('age', expect.any(Number)); If you want to omit the checking for the age property if it doesn't exist, you can use the .optional modifier. This modifier allows the matcher to pass if the property doesn't exist in the object. Here's an example: const response = {name: 'bbb'}; expect(response).toHaveProperty('age', expect.any(Number).optional); Note that the .optional modifier only works when used with the .toHaveProperty matcher. It doesn't work with .toMatchObject or other matchers.
Jest: How to test for optional object keys
Say, I have an object below const obj1 = {name: expect.any(String)} Backend return response as below with object the key 'age' as optional key const response = {name: 'bbb', age: 10} So, how can I assert obj1 have age as the optional key, which means if it exists, it must be number type, if it doesn't exist, we can omit the checking ? expect(response).toMatchObject(obj1);
[ "I don't think there's a built-in function for that, but toMatchObject along with destructuring can do what you need:\nexpect({\n age: 0, \n ...response\n}).toMatchObject(obj1);\n\nIf age is not present in the object, it will assume 0; if it is present, it will use the present value and therefore fail if it's the wrong type.\n", "You can use a special matcher .toHaveProperty provided by Jest to check whether a property exists in an object. This matcher also allows you to check the value of the property.\nIn your case, you can use the .toHaveProperty matcher to check if the response object has the optional age property and that its value is a number.\nHere's an example:\nconst response = {name: 'bbb', age: 10};\n\nexpect(response).toHaveProperty('age', expect.any(Number));\n\nIf you want to omit the checking for the age property if it doesn't exist, you can use the .optional modifier. This modifier allows the matcher to pass if the property doesn't exist in the object.\nHere's an example:\nconst response = {name: 'bbb'};\n\nexpect(response).toHaveProperty('age', expect.any(Number).optional);\n\nNote that the .optional modifier only works when used with the .toHaveProperty matcher. It doesn't work with .toMatchObject or other matchers.\n" ]
[ 5, 1 ]
[ "From what i can understand, you want to check that if the property is defined, check that its type is a number? And if the property does not exist then do not check the property type? Correct?\nAssuming that the above understanding is correct, this should do:\n\n\n const response = {name: \"bbb\", age:10};\r\n if (response.age) {\r\n if (typeof response.age === 'number') {\r\n console.log(\"age is a number\");\r\n //your logic if age is a number\r\n }\r\n else {\r\n //your logic in case age exists but its not a number\r\n }\r\n }\r\n else {\r\n //your logic in case age does not exist\r\n }\n\n\n\n" ]
[ -4 ]
[ "javascript", "jestjs" ]
stackoverflow_0050637827_javascript_jestjs.txt
Q: Count of distinct values in pandas column which has list of values I have a dataframe column which contains lists of values. I am interested in getting the count of each distinct value inside the list across the column using python. A: To visualize it: import seaborn as sns sns.countplot(x='ColumnName',data=df) too see counts normally: df['ColumnName'].value_counts()
Count of distinct values in pandas column which has list of values
I have a dataframe column which contains lists of values. I am interested in getting the count of each distinct value inside the list across the column using python.
[ "To visualize it:\nimport seaborn as sns\nsns.countplot(x='ColumnName',data=df)\n\ntoo see counts normally:\ndf['ColumnName'].value_counts()\n\n" ]
[ 1 ]
[]
[]
[ "data_science", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074671443_data_science_dataframe_numpy_pandas_python.txt
Q: why my react hook(usestate) not rendering? i'm using django restframework for my server side, i have fetch my datas on ReactJS, set it using "setPosts", consoled my response and i am getting my require response but when i try to render it in my return() block. i am not getting the data. rather i am having a blank page. i am using a windows 11 and python 3.11.0 import React,{Component,useState,useEffect,useRef} from "react"; import user_img from '../1.jpeg'; import music_img from '../2.jpg'; import music from '../Victony.mp3'; import { Button } from "@mui/material"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faPlay,faPause,faForward,faBackward } from '@fortawesome/free-solid-svg-icons'; import WaveSurfer from 'wavesurfer.js'; import AudioPlayer from 'react-modern-audio-player'; import RegionsPlugin from "wavesurfer.js/dist/plugin/wavesurfer.regions.min"; import TimelinePlugin from "wavesurfer.js/dist/plugin/wavesurfer.timeline.min"; import CursorPlugin from "wavesurfer.js/dist/plugin/wavesurfer.cursor.min"; // import MyCustomPlugin from 'my-custom-plugin-path'; // const WaveFormOptions=ref=>({ // barWidth: 3, // cursorWidth: 1, // container: ref, // // backend: 'WebAudio', // height: 80, // progressColor: '#2D5BFF', // responsive: true, // waveColor: '#EFEFEF', // cursorColor: 'transparent', // }); const Home=()=>{ const audio=document.querySelector('#audio') const music_container=document.querySelector('#music_container') const [image, setImage]=useState('') const [posts, setPosts]=useState([]) const [icon,setIcon]=useState(faPlay) const[playing,setPlaying]=useState(false) // const progress=useRef() const[progress,SetCurrentProgress]=useState(0) function getAllPosts(){ fetch(`http://127.0.0.1:8000/`) .then(response=>response.json()) .then(data=>{ console.log(data) setPosts(data) }) } // console.log(posts.artist_name) // LOAD ALL POSTS // function soundrimage(){ // // setImage(music_img) // } useEffect(()=>{ getAllPosts() // console.log(this) },[]) // LOAD AND CONTROL MUSIC function playSong(){ music_container.classList.add('play') setIcon(faPause) setPlaying(true) audio.play() } function pauseSong(){ music_container.classList.remove('play') setIcon(faPlay) setPlaying(true) audio.pause() } function playPause(){ let isplaying=music_container.classList.contains('play') if(isplaying){ pauseSong() }else{ playSong() } } const UpdateProgress=(e)=>{ // console.log(e.target.duration) const {duration,currentTime}=e.target const ProgressPercent=(currentTime/duration)*100 SetCurrentProgress(`${ProgressPercent}`) } // console.log(progress.current) const setProgress=(e)=>{ const width=e.target.clientWidth // console.log(e) const clickX=e.nativeEvent.offsetX // console.log(clickX) const duration=audio.duration // console.log(duration) audio.currentTime=(clickX/width)*duration } // MUSIC INFO // const music_image= document.querySelector("#music_image") return( <body> <Navbar/> <main className="landing"> {posts.map(post=>{ <div className="music_container" onClick={playPause} id="music_container"> <img id="music_image" src={'http://127.0.0.1:8000'+post.image} /> <button > <FontAwesomeIcon icon={icon} id="playBtn" /> </button> <audio src='' id="audio" onTimeUpdate={e=>UpdateProgress(e)}/> <p className="caption">{post.title}</p> <p>{post.title}</p> </div> console.log(post.image) } )} </main> <Play image={image} playing={playing} playpause={playPause} playicon={icon} progress={progress} setProgress={e=>setProgress(e)} /> </body> ) } export default Home A: The issue here is with your map function. Try the following syntax: { posts.map((post) => ( <div className="music_container" onClick={playPause} id="music_container"> <img id="music_image" src={'http://127.0.0.1:8000'+post.image} /> <button> <FontAwesomeIcon icon={icon} id="playBtn" /> </button> <audio src='' id="audio" onTimeUpdate={e=>UpdateProgress(e)}/> <p className="caption">{post.title}</p> <p>{post.title}</p> </div> )) }
why my react hook(usestate) not rendering?
i'm using django restframework for my server side, i have fetch my datas on ReactJS, set it using "setPosts", consoled my response and i am getting my require response but when i try to render it in my return() block. i am not getting the data. rather i am having a blank page. i am using a windows 11 and python 3.11.0 import React,{Component,useState,useEffect,useRef} from "react"; import user_img from '../1.jpeg'; import music_img from '../2.jpg'; import music from '../Victony.mp3'; import { Button } from "@mui/material"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faPlay,faPause,faForward,faBackward } from '@fortawesome/free-solid-svg-icons'; import WaveSurfer from 'wavesurfer.js'; import AudioPlayer from 'react-modern-audio-player'; import RegionsPlugin from "wavesurfer.js/dist/plugin/wavesurfer.regions.min"; import TimelinePlugin from "wavesurfer.js/dist/plugin/wavesurfer.timeline.min"; import CursorPlugin from "wavesurfer.js/dist/plugin/wavesurfer.cursor.min"; // import MyCustomPlugin from 'my-custom-plugin-path'; // const WaveFormOptions=ref=>({ // barWidth: 3, // cursorWidth: 1, // container: ref, // // backend: 'WebAudio', // height: 80, // progressColor: '#2D5BFF', // responsive: true, // waveColor: '#EFEFEF', // cursorColor: 'transparent', // }); const Home=()=>{ const audio=document.querySelector('#audio') const music_container=document.querySelector('#music_container') const [image, setImage]=useState('') const [posts, setPosts]=useState([]) const [icon,setIcon]=useState(faPlay) const[playing,setPlaying]=useState(false) // const progress=useRef() const[progress,SetCurrentProgress]=useState(0) function getAllPosts(){ fetch(`http://127.0.0.1:8000/`) .then(response=>response.json()) .then(data=>{ console.log(data) setPosts(data) }) } // console.log(posts.artist_name) // LOAD ALL POSTS // function soundrimage(){ // // setImage(music_img) // } useEffect(()=>{ getAllPosts() // console.log(this) },[]) // LOAD AND CONTROL MUSIC function playSong(){ music_container.classList.add('play') setIcon(faPause) setPlaying(true) audio.play() } function pauseSong(){ music_container.classList.remove('play') setIcon(faPlay) setPlaying(true) audio.pause() } function playPause(){ let isplaying=music_container.classList.contains('play') if(isplaying){ pauseSong() }else{ playSong() } } const UpdateProgress=(e)=>{ // console.log(e.target.duration) const {duration,currentTime}=e.target const ProgressPercent=(currentTime/duration)*100 SetCurrentProgress(`${ProgressPercent}`) } // console.log(progress.current) const setProgress=(e)=>{ const width=e.target.clientWidth // console.log(e) const clickX=e.nativeEvent.offsetX // console.log(clickX) const duration=audio.duration // console.log(duration) audio.currentTime=(clickX/width)*duration } // MUSIC INFO // const music_image= document.querySelector("#music_image") return( <body> <Navbar/> <main className="landing"> {posts.map(post=>{ <div className="music_container" onClick={playPause} id="music_container"> <img id="music_image" src={'http://127.0.0.1:8000'+post.image} /> <button > <FontAwesomeIcon icon={icon} id="playBtn" /> </button> <audio src='' id="audio" onTimeUpdate={e=>UpdateProgress(e)}/> <p className="caption">{post.title}</p> <p>{post.title}</p> </div> console.log(post.image) } )} </main> <Play image={image} playing={playing} playpause={playPause} playicon={icon} progress={progress} setProgress={e=>setProgress(e)} /> </body> ) } export default Home
[ "The issue here is with your map function. Try the following syntax:\n{ posts.map((post) => (\n <div className=\"music_container\" onClick={playPause} id=\"music_container\">\n <img id=\"music_image\" src={'http://127.0.0.1:8000'+post.image} />\n <button>\n <FontAwesomeIcon icon={icon} id=\"playBtn\" />\n </button>\n <audio src='' id=\"audio\" onTimeUpdate={e=>UpdateProgress(e)}/>\n <p className=\"caption\">{post.title}</p>\n <p>{post.title}</p>\n </div>\n)) }\n\n" ]
[ 0 ]
[]
[]
[ "django_rest_framework", "python", "reactjs" ]
stackoverflow_0074671368_django_rest_framework_python_reactjs.txt
Q: Express with Handlebars will not load data into variables I have a NodeJS/Express app that is using Handlebars for templates. All of the templates and partials load fine except where I am returning data from an Express API. The data is returned and I can see it in the Chrome debugger. In this template, I am defining the HTML in a script and compiling it in JS. Here is the template HTML: <script id="search-result-template" type="text/x-handlebars"> <div>String</div> {{#each patient}} <div> {{cp_first_name}} </div> {{!-- {{> searchresultpartial}} --}} {{/each}} </script> The actual page is quite a bit more structured but I've narrowed it down to this for debugging. Here is the code that compiles the template: let patientSearchButton = document.getElementById('patient-search-execute'); patientSearchButton.addEventListener("click", async function (e) { e.preventDefault(); let patientSearchFirstname = document.getElementById('patient-search-firstname') let cp_first_name = patientSearchFirstname.value; let url = baseURL + 'patientsearchquery/' + cp_first_name; const response = await fetch(url, { method: 'get', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' } }); var data = response.json(); let patientList = await data; patient = patientList; if (response.status === 200) { let patientSearchResultTemplate = document.querySelector("#search-result-template").innerHTML; let patientSearchResultTemplateFunction = Handlebars.compile(patientSearchResultTemplate); let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient); let contentPartial = document.getElementById('patient-search-table'); contentPartial.innerHTML = patientSearchResultTemplateObject; if (Handlebars.Utils.isArray(patient)) { console.log("Array"); } else { console.log("Not"); } console.log(patient); } else { alert("HTTP-Error: " + response.status); } }); I can see the data from the API and I'm verifying that Handlebars sees it as an Array. It seems to break when it enters the #each helper. I've tried to shift the context with ../ and I've tried every variation I can think of the coax the data into the template. I was concerned that being in an event handler tied to a button click, that the "this" context was breaking. I moved the code outside of the event handler and "this" seemed to be correct in Chrome but the behavior did not change. Here is the array data in Chrome: When paused on a breakpoint in Chrome, I can see that the patient data is present when being passed to the template. I know it's something dumb but my head hurts from banging it against the wall. This has happened on two different templates. Granted, they were similar, but I've tried numerous variations and it still isn't loading. Thanks for any help you might offer. Does anybody see anything obvious? Addendum: I changed the code to pass the property and I can see it in Chrome now. It still doesn't show up in Handlebars. this.patients shows the data in the console. Why won't it render the variable? A: The {{#each patient}} in your template anticipates that the data that you pass to your template function has a property named patient and that the value of this property is iterable - like an Array. However, it appears that you are simply passing an Array directly to your template function, and that Array does not have a patient property, and so the #each loop never executes. One way to make this work would be to pass an Object to your template function and to assign to that Object a key, patient, with its value being your Array of patients. This would require changing: let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient); to: let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient }); Or use the shorthand: let patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient }); Note: As patient is an Array of Patient Objects, if I were on your team, I would urge you to add an "s" to its name to make it plural. A: Ultimately, the problem was that the data was seen Handlebars as a Sequelizer Object. It was unable to access the prototype due to a security update in Handlebars 4.6.0. Rather than using "allowInsecurePrototypeAccess" which is a widely suggested fix but one that seems like unsound advice, I made a deep copy of the data by using JSON.stringify() and JSON.parse() and Handlebars was able to access it. It was a context error, just not the one I was expecting.
Express with Handlebars will not load data into variables
I have a NodeJS/Express app that is using Handlebars for templates. All of the templates and partials load fine except where I am returning data from an Express API. The data is returned and I can see it in the Chrome debugger. In this template, I am defining the HTML in a script and compiling it in JS. Here is the template HTML: <script id="search-result-template" type="text/x-handlebars"> <div>String</div> {{#each patient}} <div> {{cp_first_name}} </div> {{!-- {{> searchresultpartial}} --}} {{/each}} </script> The actual page is quite a bit more structured but I've narrowed it down to this for debugging. Here is the code that compiles the template: let patientSearchButton = document.getElementById('patient-search-execute'); patientSearchButton.addEventListener("click", async function (e) { e.preventDefault(); let patientSearchFirstname = document.getElementById('patient-search-firstname') let cp_first_name = patientSearchFirstname.value; let url = baseURL + 'patientsearchquery/' + cp_first_name; const response = await fetch(url, { method: 'get', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' } }); var data = response.json(); let patientList = await data; patient = patientList; if (response.status === 200) { let patientSearchResultTemplate = document.querySelector("#search-result-template").innerHTML; let patientSearchResultTemplateFunction = Handlebars.compile(patientSearchResultTemplate); let patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient); let contentPartial = document.getElementById('patient-search-table'); contentPartial.innerHTML = patientSearchResultTemplateObject; if (Handlebars.Utils.isArray(patient)) { console.log("Array"); } else { console.log("Not"); } console.log(patient); } else { alert("HTTP-Error: " + response.status); } }); I can see the data from the API and I'm verifying that Handlebars sees it as an Array. It seems to break when it enters the #each helper. I've tried to shift the context with ../ and I've tried every variation I can think of the coax the data into the template. I was concerned that being in an event handler tied to a button click, that the "this" context was breaking. I moved the code outside of the event handler and "this" seemed to be correct in Chrome but the behavior did not change. Here is the array data in Chrome: When paused on a breakpoint in Chrome, I can see that the patient data is present when being passed to the template. I know it's something dumb but my head hurts from banging it against the wall. This has happened on two different templates. Granted, they were similar, but I've tried numerous variations and it still isn't loading. Thanks for any help you might offer. Does anybody see anything obvious? Addendum: I changed the code to pass the property and I can see it in Chrome now. It still doesn't show up in Handlebars. this.patients shows the data in the console. Why won't it render the variable?
[ "The {{#each patient}} in your template anticipates that the data that you pass to your template function has a property named patient and that the value of this property is iterable - like an Array.\nHowever, it appears that you are simply passing an Array directly to your template function, and that Array does not have a patient property, and so the #each loop never executes.\nOne way to make this work would be to pass an Object to your template function and to assign to that Object a key, patient, with its value being your Array of patients.\nThis would require changing:\nlet patientSearchResultTemplateObject = patientSearchResultTemplateFunction(patient);\n\nto:\nlet patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient: patient });\n\nOr use the shorthand:\nlet patientSearchResultTemplateObject = patientSearchResultTemplateFunction({ patient });\n\nNote: As patient is an Array of Patient Objects, if I were on your team, I would urge you to add an \"s\" to its name to make it plural.\n", "Ultimately, the problem was that the data was seen Handlebars as a Sequelizer Object. It was unable to access the prototype due to a security update in Handlebars 4.6.0.\nRather than using \"allowInsecurePrototypeAccess\" which is a widely suggested fix but one that seems like unsound advice, I made a deep copy of the data by using JSON.stringify() and JSON.parse() and Handlebars was able to access it.\nIt was a context error, just not the one I was expecting.\n" ]
[ 1, 0 ]
[]
[]
[ "express", "express_handlebars", "handlebars.js", "javascript", "node.js" ]
stackoverflow_0074651606_express_express_handlebars_handlebars.js_javascript_node.js.txt
Q: Restart all k8s pods in cluster? What is the best way to restart all pods in a cluster? I was thinking that setting a cronjob task within kubernetes to do this on a normal basis and make sure that the cluster is load balanced evenly, but what is the best practice to do this on a normal basis? Also, what is the best way to do this as a one-time task? A: This is a bad idea. Check out https://github.com/kubernetes-sigs/descheduler instead to do it selectively and with actual analysis :) But that said, kubectl delete pod --all --all-namespaces or similar. A: If you want to run it from the CronJob, it means you need to have admin's kubeconfig inside for connecting to the kube-api from the POD. For me it's a risk because anyone who connects to the POD gets your kubeconfig. So I prefer to run it from the local machine via kubectl command. For sure - all PODs for me mean the Control Plane's components and all Deployments, Statefulsets, and DaemonSets. You can choose delete pod or rollout restart (kubectl cheetsheet). I prefer the second way because it restarts POD after POD and keeps the HA of the applications. Because I today solved a similar issue so I wrote my own script which you can find out below. Nothing special - it asks you about K8s context and without the --restart parameter it dry-runs all restart commands. :] #! /bin/env bash # Help [[ ${1} == "--help" ]] && echo "Usage: $0 [--restart]" && exit 0 # Run restart process if [[ ${1} != "" ]]; then if [[ ${1} == "--restart" ]]; then RUN_RESTART="true" else echo "This parameter is strange, check it: ${}" exit 1 fi fi ### ### VARIABLES ### SLEEP=10 KUBECTL="kubectl" ### ### CONFIRM CONTEXT ### echo -e "\nConfirm your context: $(${KUBECTL} config current-context): [enter / ctrl+c]" echo -e "~~~~~~~~~~~~~~~~~~~~~~~\n" read ### ### RESTART ALL K8s SERVICES ### echo -e "\n\n>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<" echo ">>> RESTART ALL K8s SERVICES <<<" echo ">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<" CONTROL_PLANE=$(${KUBECTL} get node -l node-role=master -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}') for master in ${CONTROL_PLANE}; do echo "Master: ${master}" echo "~~~~~~~~~~~~~~~~~~~~~" CP_PODS=$(${KUBECTL} -n kube-system get pods --field-selector spec.nodeName=${master} -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}' | grep -E -- 'etcd|^kube-') for pod in ${CP_PODS}; do CP_RESTART="${KUBECTL} -n kube-system delete pod ${pod}" if [[ ${RUN_RESTART} == "true" ]]; then echo " * [$(date '+%F %T')] Run command: ${CP_RESTART}" ${CP_RESTART} && echo sleep ${SLEEP} else echo " * ${CP_RESTART}" fi done echo -e "~~~~~~~~~~~~~~~~~~~~~~~\n\n" done ### ### RESTART ALL Deployments, ReplicaSets and DaemonSets ### echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" echo ">>> RESTART ALL Deployments, StatefullSets and DaemonSets <<<" echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" for ns in $(${KUBECTL} get ns -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}'); do # Check if in the namespace are PODs # PODS=$(${KUBECTL} -n ${ns} get pod -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}') # echo ">>> ${ns}: $PODS" # if [[ "${PODS}" != "" ]]; then # ns="ms" echo "Namespace: $ns" echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" echo " >> Deployments:" for deployment in $(${KUBECTL} -n $ns get deployments.apps -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}'); do DEPL_RESTART="${KUBECTL} -n ${ns} rollout restart deployments.apps ${deployment}" if [[ ${RUN_RESTART} == "true" ]]; then echo " * [$(date '+%F %T')] Run command: ${DEPL_RESTART}" ${DEPL_RESTART} && echo sleep ${SLEEP} else echo " * ${DEPL_RESTART}" fi done echo " >> StatefulSets:" for rs in $(${KUBECTL} -n $ns get statefulset -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}'); do RS_RESTART="${KUBECTL} -n ${ns} rollout restart statefulset ${rs}" if [[ ${RUN_RESTART} == "true" ]]; then echo " * [$(date '+%F %T')] Run command: ${RS_RESTART}" ${RS_RESTART} && echo sleep ${SLEEP} else echo " * ${RS_RESTART}" fi done echo " >> DaemonSets:" for ds in $(${KUBECTL} -n $ns get daemonsets.apps -o jsonpath='{range .items[*]}{@.metadata.name}{"\n"}'); do DS_RESTART="${KUBECTL} -n ${ns} rollout restart daemonsets.apps ${ds}" if [[ ${RUN_RESTART} == "true" ]]; then echo " * [$(date '+%F %T')] Run command: ${DS_RESTART}" ${DS_RESTART} && echo sleep ${SLEEP} else echo " * ${DS_RESTART}" fi done echo -e "~~~~~~~~~~~~~~~~~~~~~~~\n\n" done A: This has been working well for me. for ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do for kind in deploy daemonset statefulset; do kubectl get "${kind}" -n "${ns}" -o name | xargs -I {} kubectl rollout restart {} -n "${ns}" done done
Restart all k8s pods in cluster?
What is the best way to restart all pods in a cluster? I was thinking that setting a cronjob task within kubernetes to do this on a normal basis and make sure that the cluster is load balanced evenly, but what is the best practice to do this on a normal basis? Also, what is the best way to do this as a one-time task?
[ "This is a bad idea. Check out https://github.com/kubernetes-sigs/descheduler instead to do it selectively and with actual analysis :)\nBut that said, kubectl delete pod --all --all-namespaces or similar.\n", "If you want to run it from the CronJob, it means you need to have admin's kubeconfig inside for connecting to the kube-api from the POD. For me it's a risk because anyone who connects to the POD gets your kubeconfig. So I prefer to run it from the local machine via kubectl command.\nFor sure - all PODs for me mean the Control Plane's components and all Deployments, Statefulsets, and DaemonSets.\nYou can choose delete pod or rollout restart (kubectl cheetsheet). I prefer the second way because it restarts POD after POD and keeps the HA of the applications.\nBecause I today solved a similar issue so I wrote my own script which you can find out below. Nothing special - it asks you about K8s context and without the --restart parameter it dry-runs all restart commands. :]\n#! /bin/env bash\n\n# Help\n[[ ${1} == \"--help\" ]] && echo \"Usage: $0 [--restart]\" && exit 0\n\n# Run restart process\nif [[ ${1} != \"\" ]]; then\n if [[ ${1} == \"--restart\" ]]; then\n RUN_RESTART=\"true\" \n else\n echo \"This parameter is strange, check it: ${}\"\n exit 1\n fi\nfi\n\n###\n### VARIABLES\n###\nSLEEP=10\nKUBECTL=\"kubectl\"\n\n###\n### CONFIRM CONTEXT\n###\necho -e \"\\nConfirm your context: $(${KUBECTL} config current-context): [enter / ctrl+c]\"\necho -e \"~~~~~~~~~~~~~~~~~~~~~~~\\n\"\n\nread\n\n###\n### RESTART ALL K8s SERVICES\n###\necho -e \"\\n\\n>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<\"\necho \">>> RESTART ALL K8s SERVICES <<<\"\necho \">>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<\"\nCONTROL_PLANE=$(${KUBECTL} get node -l node-role=master -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}')\nfor master in ${CONTROL_PLANE}; do\n echo \"Master: ${master}\"\n echo \"~~~~~~~~~~~~~~~~~~~~~\"\n CP_PODS=$(${KUBECTL} -n kube-system get pods --field-selector spec.nodeName=${master} -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}' | grep -E -- 'etcd|^kube-')\n\n for pod in ${CP_PODS}; do\n CP_RESTART=\"${KUBECTL} -n kube-system delete pod ${pod}\"\n if [[ ${RUN_RESTART} == \"true\" ]]; then\n echo \" * [$(date '+%F %T')] Run command: ${CP_RESTART}\"\n ${CP_RESTART} && echo\n sleep ${SLEEP}\n else\n echo \" * ${CP_RESTART}\"\n fi\n done\n echo -e \"~~~~~~~~~~~~~~~~~~~~~~~\\n\\n\"\ndone\n\n###\n### RESTART ALL Deployments, ReplicaSets and DaemonSets\n###\necho \">>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\"\necho \">>> RESTART ALL Deployments, StatefullSets and DaemonSets <<<\"\necho \">>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\"\nfor ns in $(${KUBECTL} get ns -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}'); do \n # Check if in the namespace are PODs\n # PODS=$(${KUBECTL} -n ${ns} get pod -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}')\n # echo \">>> ${ns}: $PODS\"\n # if [[ \"${PODS}\" != \"\" ]]; then\n # ns=\"ms\"\n echo \"Namespace: $ns\"\n echo \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n\n echo \" >> Deployments:\"\n for deployment in $(${KUBECTL} -n $ns get deployments.apps -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}'); do\n DEPL_RESTART=\"${KUBECTL} -n ${ns} rollout restart deployments.apps ${deployment}\"\n if [[ ${RUN_RESTART} == \"true\" ]]; then\n echo \" * [$(date '+%F %T')] Run command: ${DEPL_RESTART}\"\n ${DEPL_RESTART} && echo\n sleep ${SLEEP}\n else\n echo \" * ${DEPL_RESTART}\"\n fi\n done\n\n echo \" >> StatefulSets:\"\n for rs in $(${KUBECTL} -n $ns get statefulset -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}'); do\n RS_RESTART=\"${KUBECTL} -n ${ns} rollout restart statefulset ${rs}\"\n if [[ ${RUN_RESTART} == \"true\" ]]; then \n echo \" * [$(date '+%F %T')] Run command: ${RS_RESTART}\"\n ${RS_RESTART} && echo\n sleep ${SLEEP}\n else\n echo \" * ${RS_RESTART}\"\n fi\n done\n \n echo \" >> DaemonSets:\"\n for ds in $(${KUBECTL} -n $ns get daemonsets.apps -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}'); do\n DS_RESTART=\"${KUBECTL} -n ${ns} rollout restart daemonsets.apps ${ds}\"\n if [[ ${RUN_RESTART} == \"true\" ]]; then\n echo \" * [$(date '+%F %T')] Run command: ${DS_RESTART}\"\n ${DS_RESTART} && echo\n sleep ${SLEEP}\n else\n echo \" * ${DS_RESTART}\"\n fi\n done\n echo -e \"~~~~~~~~~~~~~~~~~~~~~~~\\n\\n\"\ndone\n\n", "This has been working well for me.\nfor ns in $(kubectl get ns -o jsonpath='{.items[*].metadata.name}'); do \n for kind in deploy daemonset statefulset; do\n kubectl get \"${kind}\" -n \"${ns}\" -o name | xargs -I {} kubectl rollout restart {} -n \"${ns}\"\n done\ndone\n\n" ]
[ 8, 0, 0 ]
[]
[]
[ "cron", "kubernetes", "load_balancing" ]
stackoverflow_0061002336_cron_kubernetes_load_balancing.txt
Q: Lazy calculate and store entity children Is there a kotlin or room utility to lazily calculate and store children rows? Of course a transient property with by lazy doesn't work in my case because my entities are not stored anywhere in memory, new entities are pulled on each query. A: In this case, you can use a regular property and initialize it every time the entity is accessed or queried. For example, if you have a Parent entity that has a list of Child entities, you can define the children property as a regular property and initialize it every time the Parent entity is accessed or queried. Here is an example of how you can do this: @Entity data class Parent( @PrimaryKey val id: Long, val name: String ) { val children: List<Child> get() { // Here you can do any expensive computation to initialize the property // For example, you could fetch the data from a database or a web service return listOf( Child(1, id, "Child 1"), Child(2, id, "Child 2") ) } } @Entity data class Child( @PrimaryKey val id: Long, val parentId: Long, val name: String ) In this example, the children property is defined as a regular property with a get accessor. Every time the children property is accessed, the get accessor is called, and it performs the expensive computation to initialize the property. Alternatively, you can use the @Relation annotation to define the relationship between the Parent and Child entities, and Room will automatically manage the data for you. Here is an example of how you can do this: @Entity data class Parent( @PrimaryKey val id: Long, val name: String ) @Entity data class Child( @PrimaryKey val id: Long, val parentId: Long, val name: String ) data class ParentWithChildren( @Embedded val parent: Parent, @Relation( parentColumn = "id", entityColumn = "parentId" ) val children: List<Child> ) In this example, the ParentWithChildren class represents a Parent entity along with its children Child entities. The @Relation annotation specifies the relationship between the parent and child entities by defining the parentColumn and entityColumn properties. Room will automatically manage the data for the children property, and you can use it to access the child rows for a given parent.
Lazy calculate and store entity children
Is there a kotlin or room utility to lazily calculate and store children rows? Of course a transient property with by lazy doesn't work in my case because my entities are not stored anywhere in memory, new entities are pulled on each query.
[ "In this case, you can use a regular property and initialize it every time the entity is accessed or queried.\nFor example, if you have a Parent entity that has a list of Child entities, you can define the children property as a regular property and initialize it every time the Parent entity is accessed or queried. Here is an example of how you can do this:\n@Entity\ndata class Parent(\n @PrimaryKey val id: Long,\n val name: String\n) {\n val children: List<Child>\n get() {\n // Here you can do any expensive computation to initialize the property\n // For example, you could fetch the data from a database or a web service\n return listOf(\n Child(1, id, \"Child 1\"),\n Child(2, id, \"Child 2\")\n )\n }\n}\n\n@Entity\ndata class Child(\n @PrimaryKey val id: Long,\n val parentId: Long,\n val name: String\n)\n\nIn this example, the children property is defined as a regular property with a get accessor. Every time the children property is accessed, the get accessor is called, and it performs the expensive computation to initialize the property.\nAlternatively, you can use the @Relation annotation to define the relationship between the Parent and Child entities, and Room will automatically manage the data for you. Here is an example of how you can do this:\n@Entity\ndata class Parent(\n @PrimaryKey val id: Long,\n val name: String\n)\n\n@Entity\ndata class Child(\n @PrimaryKey val id: Long,\n val parentId: Long,\n val name: String\n)\n\ndata class ParentWithChildren(\n @Embedded val parent: Parent,\n @Relation(\n parentColumn = \"id\",\n entityColumn = \"parentId\"\n )\n val children: List<Child>\n)\n\nIn this example, the ParentWithChildren class represents a Parent entity along with its children Child entities. The @Relation annotation specifies the relationship between the parent and child entities by defining the parentColumn and entityColumn properties. Room will automatically manage the data for the children property, and you can use it to access the child rows for a given parent.\n" ]
[ 0 ]
[]
[]
[ "android_room", "kotlin" ]
stackoverflow_0074671455_android_room_kotlin.txt
Q: Attribute Error: Countvectorizer has no attribute load_specials I have been trying very long but unable to fix the below error Error File "C:\amnpawar\AIenv\lib\site-packages\gensim\models\deprecated\doc2vec.py", line 91, in load_old_doc2vec old_model = Doc2Vec.load(*args, **kwargs) File "C:\amnpawar\AIenv\lib\site-packages\gensim\models\deprecated\word2vec.py", line 1617, in load model = super(Word2Vec, cls).load(*args, **kwargs) File "C:\amnpawar\AIenv\lib\site-packages\gensim\models\deprecated\old_saveload.py", line 88, in load obj._load_specials(fname, mmap, compress, subname) AttributeError: 'CountVectorizer' object has no attribute '_load_specials' A: Indeed you've been struggling with this for a long time, but the answer is essentially the same as was given when you asked a version of it in September, and I answered: https://stackoverflow.com/a/73660204/130288 Don't try to use any Gensim .load() method to load a non-Gensim saved object. CountVectorizer isn't a Gensim class. This error suggests the file you're trying to load here is a pickle-serialization of a CountVectorizer object, not a Gensim Doc2Vec object. Looking at the code from your previous question, it's likely the initial error you made was using pickle.dump() to write the CountVectorizer into the same filename as the earlier Doc2Vec model.save(). So, that file no longer contains a Doc2Vec object. Whatever was saved initially has been overwritten. If you want to load this file, use the same pickle.load() as was in your initial question code, but the loaded object you get won't be a Doc2Vec model, it'll be a CountVectorizer. To load a Doc2Vec model, you'll need to use a different file that actually contains a Doc2Vec model. (If you don't have any, because your original model file was overwritten when you saved the CountVectorizer to it, you'll need to train another Doc2Vec model.)
Attribute Error: Countvectorizer has no attribute load_specials
I have been trying very long but unable to fix the below error Error File "C:\amnpawar\AIenv\lib\site-packages\gensim\models\deprecated\doc2vec.py", line 91, in load_old_doc2vec old_model = Doc2Vec.load(*args, **kwargs) File "C:\amnpawar\AIenv\lib\site-packages\gensim\models\deprecated\word2vec.py", line 1617, in load model = super(Word2Vec, cls).load(*args, **kwargs) File "C:\amnpawar\AIenv\lib\site-packages\gensim\models\deprecated\old_saveload.py", line 88, in load obj._load_specials(fname, mmap, compress, subname) AttributeError: 'CountVectorizer' object has no attribute '_load_specials'
[ "Indeed you've been struggling with this for a long time, but the answer is essentially the same as was given when you asked a version of it in September, and I answered: https://stackoverflow.com/a/73660204/130288\nDon't try to use any Gensim .load() method to load a non-Gensim saved object.\nCountVectorizer isn't a Gensim class. This error suggests the file you're trying to load here is a pickle-serialization of a CountVectorizer object, not a Gensim Doc2Vec object.\nLooking at the code from your previous question, it's likely the initial error you made was using pickle.dump() to write the CountVectorizer into the same filename as the earlier Doc2Vec model.save(). So, that file no longer contains a Doc2Vec object. Whatever was saved initially has been overwritten.\nIf you want to load this file, use the same pickle.load() as was in your initial question code, but the loaded object you get won't be a Doc2Vec model, it'll be a CountVectorizer.\nTo load a Doc2Vec model, you'll need to use a different file that actually contains a Doc2Vec model. (If you don't have any, because your original model file was overwritten when you saved the CountVectorizer to it, you'll need to train another Doc2Vec model.)\n" ]
[ 0 ]
[]
[]
[ "doc2vec", "nlp", "python_3.x" ]
stackoverflow_0074656582_doc2vec_nlp_python_3.x.txt
Q: Execution context: What is the Code Component (Thread of Execution)? I have read that the execution context is composed for two components: the Memory Component and the Code Component (or Thread of Execution). But, is this true or Thread of Execution is "thing" that exists outside execution context? I found nothing in ECMAScript Documentation. (I googled a lot for this...) A: The Code Component (or Thread of Execution) is the sequence of instructions that the JavaScript engine executes in order to carry out the instructions of a specific program. It is part of the execution context, which also includes the Memory Component (the memory space in which the program's data is stored). The Code Component is not a separate "thing" from the execution context, but rather it is one of the components that make up the execution context.
Execution context: What is the Code Component (Thread of Execution)?
I have read that the execution context is composed for two components: the Memory Component and the Code Component (or Thread of Execution). But, is this true or Thread of Execution is "thing" that exists outside execution context? I found nothing in ECMAScript Documentation. (I googled a lot for this...)
[ "The Code Component (or Thread of Execution) is the sequence of instructions that the JavaScript engine executes in order to carry out the instructions of a specific program. It is part of the execution context, which also includes the Memory Component (the memory space in which the program's data is stored). The Code Component is not a separate \"thing\" from the execution context, but rather it is one of the components that make up the execution context.\n" ]
[ 0 ]
[]
[]
[ "ecmascript_6", "executioncontext", "javascript" ]
stackoverflow_0074671461_ecmascript_6_executioncontext_javascript.txt
Q: React Router need help routing I'm a beginner front-end dev and I try to make an imaginary website. I'm learning to react router now. So when I try to click on the home/about or contact button, It doesn't open it. What am I doing wrong? here's my code below : my App code : import React from 'react'; import './App.css'; import Navibar from './Components/Navibar'; import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'; import Home from './Components/Home'; import About from './Components/About'; import Contact from './Components/Contact'; let App = () => { return ( <Router> <div className="App"> <Navibar/> <div className="content"> <Switch> <Route exact path="/"> <Home/> </Route> <Route exact path="/About"> <About/> </Route> <Route exact path="Contact"> <Contact/> </Route> </Switch> </div> </div> </Router> ); } export default App; and here's my navbar code : import React from 'react'; import {Nav, Navbar, Container} from 'react-bootstrap'; import {Link} from 'react-router-dom'; let Navibar = () => { return ( <> <Navbar bg="dark" variant="dark"> <Container> <Navbar.Brand href="#home">My Portfolio</Navbar.Brand> <Nav className="me-auto"> <Link to="/">Home</Link> <Link to="#about">About me</Link> <Link to="#contact">Contact</Link> </Nav> </Container> </Navbar> </> ); } export default Navibar; and here's my Home (the home/about and contact codes are the same) code : import React from 'react'; let Home = () => { return ( <> <h2>Home</h2> </> ); } export default Home; I need help from a professional, because I'm getting stuck in this :) A: There seems to be a few issues with your code. Here are a few suggestions to help you fix them: In your Navibar component, you are using the # symbol in the href attribute of the Link elements. This is not correct, because the # symbol is used to link to an anchor within the same page, not to a different route. Instead, you should use the to attribute to specify the route that you want to link to. For example: <Link to="/about">About me</Link> In your App component, the Route elements that render the About and Contact components have the exact attribute set to false, which means that they will match any path that starts with the specified path. In this case, you want the Route elements to only match the exact path, so you should set the exact attribute to true, like this: <Route exact path="/about"> <About /> </Route> <Route exact path="/contact"> <Contact /> </Route> In your App component, the Route element that renders the Home component is missing the exact attribute. As a result, this Route will match any path, which means that the Home component will be rendered for all routes. You should add the exact attribute to this Route element, like this: <Route exact path="/"> <Home /> </Route> After making these changes, your code should work as expected. I hope this helps!
React Router need help routing
I'm a beginner front-end dev and I try to make an imaginary website. I'm learning to react router now. So when I try to click on the home/about or contact button, It doesn't open it. What am I doing wrong? here's my code below : my App code : import React from 'react'; import './App.css'; import Navibar from './Components/Navibar'; import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'; import Home from './Components/Home'; import About from './Components/About'; import Contact from './Components/Contact'; let App = () => { return ( <Router> <div className="App"> <Navibar/> <div className="content"> <Switch> <Route exact path="/"> <Home/> </Route> <Route exact path="/About"> <About/> </Route> <Route exact path="Contact"> <Contact/> </Route> </Switch> </div> </div> </Router> ); } export default App; and here's my navbar code : import React from 'react'; import {Nav, Navbar, Container} from 'react-bootstrap'; import {Link} from 'react-router-dom'; let Navibar = () => { return ( <> <Navbar bg="dark" variant="dark"> <Container> <Navbar.Brand href="#home">My Portfolio</Navbar.Brand> <Nav className="me-auto"> <Link to="/">Home</Link> <Link to="#about">About me</Link> <Link to="#contact">Contact</Link> </Nav> </Container> </Navbar> </> ); } export default Navibar; and here's my Home (the home/about and contact codes are the same) code : import React from 'react'; let Home = () => { return ( <> <h2>Home</h2> </> ); } export default Home; I need help from a professional, because I'm getting stuck in this :)
[ "There seems to be a few issues with your code. Here are a few suggestions to help you fix them:\nIn your Navibar component, you are using the # symbol in the href attribute of the Link elements. This is not correct, because the # symbol is used to link to an anchor within the same page, not to a different route. Instead, you should use the to attribute to specify the route that you want to link to. For example:\n<Link to=\"/about\">About me</Link>\n\nIn your App component, the Route elements that render the About and Contact components have the exact attribute set to false, which means that they will match any path that starts with the specified path. In this case, you want the Route elements to only match the exact path, so you should set the exact attribute to true, like this:\n<Route exact path=\"/about\">\n <About />\n</Route>\n<Route exact path=\"/contact\">\n <Contact />\n</Route>\n\nIn your App component, the Route element that renders the Home component is missing the exact attribute. As a result, this Route will match any path, which means that the Home component will be rendered for all routes. You should add the exact attribute to this Route element, like this:\n<Route exact path=\"/\">\n <Home />\n</Route>\n\nAfter making these changes, your code should work as expected. I hope this helps!\n" ]
[ 1 ]
[]
[]
[ "react_router", "reactjs" ]
stackoverflow_0074671485_react_router_reactjs.txt
Q: ts-node unable to compile JSX tags I am trying to compile JSX tags into HTML and then flushing them into an HTML file but somehow ts-node fails to compile the following piece of code. private index = (request: Request, response: Response) => { // const component = React.createElement(Index, {key: 1, name: "Aman Sharma"}) // this works const component = <Index key={1} name="Aman Sharma" /> // throws error const html = ReactDOMServer.renderToString(component) fs.writeFileSync('website/index.html', html); response.status(200).send(); } This is the error being thrown. I have included "jsx": "react" in my tsconfig.json. My configuration is as follows: { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": [ "es2015", "dom" ], "moduleResolution": "node", "sourceMap": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "outDir": "build", "jsx": "react", "allowJs": true }, "include": [ "src/**/*.{ts,tsx}" ], "exclude": [ "node_modules" ] } A: This fixed the issue for me "jsx": "react-jsx",
ts-node unable to compile JSX tags
I am trying to compile JSX tags into HTML and then flushing them into an HTML file but somehow ts-node fails to compile the following piece of code. private index = (request: Request, response: Response) => { // const component = React.createElement(Index, {key: 1, name: "Aman Sharma"}) // this works const component = <Index key={1} name="Aman Sharma" /> // throws error const html = ReactDOMServer.renderToString(component) fs.writeFileSync('website/index.html', html); response.status(200).send(); } This is the error being thrown. I have included "jsx": "react" in my tsconfig.json. My configuration is as follows: { "compilerOptions": { "target": "es6", "module": "commonjs", "lib": [ "es2015", "dom" ], "moduleResolution": "node", "sourceMap": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "outDir": "build", "jsx": "react", "allowJs": true }, "include": [ "src/**/*.{ts,tsx}" ], "exclude": [ "node_modules" ] }
[ "This fixed the issue for me\n\"jsx\": \"react-jsx\",\n\n" ]
[ 1 ]
[]
[]
[ "express", "node.js", "reactjs", "typescript" ]
stackoverflow_0065454961_express_node.js_reactjs_typescript.txt
Q: Invoke-command with sending scriptblock param I have a script block $test = { param( $path ) other stuff here...} I assume I need to use Invoke-Command -ScriptBlock $test but how do I pass what the $path param should be ? A: You can pass the value for the $path parameter when using Invoke-Command by using the -ArgumentList parameter and providing a list of the values for the parameters in the script block, in the correct order. For example, if you want to pass the value C:\test for the $path parameter in the script block above, you could use the following command: Invoke-Command -ScriptBlock $test -ArgumentList C:\test This would pass the value C:\test as the value for the $path parameter in the script block, which you can then use in your script. Note that you may need to enclose the value for the $path parameter in quotes if it contains spaces or other special characters. For example, if the value for the $path parameter was C:\my test folder, you would need to use the following command instead: Invoke-Command -ScriptBlock $test -ArgumentList "C:\my test folder" A: To invoke script blocks with parameters (locally, in the context of the current user): do not use Invoke-Command (see this answer for more information). use &, the call operator. $test = { param($path) "[$path]" # diagnostic output. } # Note: # * Target parameter -path is *positionally implied* # * To be explicit, call: & $test -path 'my -path value' & $test 'my -path value'
Invoke-command with sending scriptblock param
I have a script block $test = { param( $path ) other stuff here...} I assume I need to use Invoke-Command -ScriptBlock $test but how do I pass what the $path param should be ?
[ "You can pass the value for the $path parameter when using Invoke-Command by using the -ArgumentList parameter and providing a list of the values for the parameters in the script block, in the correct order. For example, if you want to pass the value C:\\test for the $path parameter in the script block above, you could use the following command:\nInvoke-Command -ScriptBlock $test -ArgumentList C:\\test\n\nThis would pass the value C:\\test as the value for the $path parameter in the script block, which you can then use in your script.\nNote that you may need to enclose the value for the $path parameter in quotes if it contains spaces or other special characters. For example, if the value for the $path parameter was C:\\my test folder, you would need to use the following command instead:\nInvoke-Command -ScriptBlock $test -ArgumentList \"C:\\my test folder\"\n\n", "\nTo invoke script blocks with parameters (locally, in the context of the current user):\n\ndo not use Invoke-Command (see this answer for more information).\n\nuse &, the call operator.\n\n\n$test = { \n param($path)\n \"[$path]\" # diagnostic output.\n}\n\n# Note: \n# * Target parameter -path is *positionally implied*\n# * To be explicit, call: & $test -path 'my -path value' \n& $test 'my -path value' \n\n" ]
[ 0, 0 ]
[]
[]
[ "powershell" ]
stackoverflow_0074671374_powershell.txt
Q: Cuda program starts but won't process nor stop Hi I'm new to programming with Cuda and I'm facing a problem. At random my programs start but won't process nor exit when trying to stop it. I'm running on an Ubuntu system. When this occurs there is no console output (also no output before any Cuda code) from the program itself nor an error message. If I try to stop the program in vscode I don't get an exiting message and if try to shutdown my computer I get the message: system-shutdown[1]: Waiting for process: "Program name" It also happens at random. Sometimes the program runs and exits perfectly once, sometimes twice or three times but mostly after that I'm facing this problem. I also made sure I'm freeing my memory correctly. Any ideas? A: It sounds like you may be encountering a deadlock situation in your Cuda program. This can happen when multiple threads try to access the same resource, such as a variable or a block of memory, at the same time and end up waiting for each other to finish before they can continue. To fix this issue, you can try using mutexes or other synchronization mechanisms to ensure that only one thread can access the shared resource at a time. You can also try using the cudaDeviceSynchronize function to force all threads to wait until the device has completed all previously requested tasks before continuing. Additionally, make sure you are properly allocating and freeing memory in your Cuda program. Improper memory management can cause unpredictable behavior and can lead to deadlock situations. If you're still having trouble, it might be helpful to post some code so that others can take a look and offer more specific advice.
Cuda program starts but won't process nor stop
Hi I'm new to programming with Cuda and I'm facing a problem. At random my programs start but won't process nor exit when trying to stop it. I'm running on an Ubuntu system. When this occurs there is no console output (also no output before any Cuda code) from the program itself nor an error message. If I try to stop the program in vscode I don't get an exiting message and if try to shutdown my computer I get the message: system-shutdown[1]: Waiting for process: "Program name" It also happens at random. Sometimes the program runs and exits perfectly once, sometimes twice or three times but mostly after that I'm facing this problem. I also made sure I'm freeing my memory correctly. Any ideas?
[ "It sounds like you may be encountering a deadlock situation in your Cuda program. This can happen when multiple threads try to access the same resource, such as a variable or a block of memory, at the same time and end up waiting for each other to finish before they can continue.\nTo fix this issue, you can try using mutexes or other synchronization mechanisms to ensure that only one thread can access the shared resource at a time. You can also try using the cudaDeviceSynchronize function to force all threads to wait until the device has completed all previously requested tasks before continuing.\nAdditionally, make sure you are properly allocating and freeing memory in your Cuda program. Improper memory management can cause unpredictable behavior and can lead to deadlock situations.\nIf you're still having trouble, it might be helpful to post some code so that others can take a look and offer more specific advice.\n" ]
[ 0 ]
[]
[]
[ "cuda" ]
stackoverflow_0074671463_cuda.txt
Q: Docker push: Force Push All Layers? Does docker push possess a --force flag which forces all layers to be pushed to the repository, regardless of whether the repository believes those layers are unchanged? Thank you!
Docker push: Force Push All Layers?
Does docker push possess a --force flag which forces all layers to be pushed to the repository, regardless of whether the repository believes those layers are unchanged? Thank you!
[]
[]
[ "No, there's no --force option to docker push. You can see the options by running docker push --help.\nThe only reason to force push blobs is if the registry is broken or you've encountered a sha256 hash collision within your repository. I've yet to see a hash collision in app my time using docker. And if the registry is broken, you can delete the affected images from the server and push them again, but I'd put more effort into preventing whatever is corrupting your registry.\nIf this is an X-Y problem, and you're just not seeing your changes, use unique tags to ensure your image is being pulled. If your builds are being cached, try building with --no-cache. And realize the container images are based on a content addressable store, so you won't have different content represented by the same digest.\n" ]
[ -1 ]
[ "docker", "docker_build", "docker_container", "docker_push", "google_container_registry" ]
stackoverflow_0074669116_docker_docker_build_docker_container_docker_push_google_container_registry.txt
Q: counting occurrences between 1 and 10 of an array I have an initial_array with numbers between 10 and 1, in descending order. initial_array = np.array ([10,10,7,4,2]) I want an output_array which counts the number of occurrences between 1 and 10. output_array = [ 0 1 0 1 0 0 1 0 0 2] A: Here is one possible solution using the np.bincount function: import numpy as np # create initial array with numbers between 10 and 1, in descending order initial_array = np.array([10, 10, 7, 4, 2]) # create output array that counts the number of occurrences between 1 and 10 output_array = np.bincount(initial_array, minlength=11) # print output array print(output_array) This produces the following output: [0 1 0 1 0 0 1 0 0 2] Note that the minlength parameter of the np.bincount function determines the size of the output array, which should be equal to the maximum value in the initial array plus one (11 in this case, since the maximum value is 10). If you don't specify this parameter, the output array will only have as many elements as the maximum value in the initial array. For example, if you remove the minlength parameter from the code above, the output will be: [0 1 0 1 0 0 1 0 0 2]
counting occurrences between 1 and 10 of an array
I have an initial_array with numbers between 10 and 1, in descending order. initial_array = np.array ([10,10,7,4,2]) I want an output_array which counts the number of occurrences between 1 and 10. output_array = [ 0 1 0 1 0 0 1 0 0 2]
[ "Here is one possible solution using the np.bincount function:\nimport numpy as np\n\n# create initial array with numbers between 10 and 1, in descending order\ninitial_array = np.array([10, 10, 7, 4, 2])\n\n# create output array that counts the number of occurrences between 1 and 10\noutput_array = np.bincount(initial_array, minlength=11)\n\n# print output array\nprint(output_array)\n\nThis produces the following output:\n[0 1 0 1 0 0 1 0 0 2]\n\nNote that the minlength parameter of the np.bincount function determines the size of the output array, which should be equal to the maximum value in the initial array plus one (11 in this case, since the maximum value is 10). If you don't specify this parameter, the output array will only have as many elements as the maximum value in the initial array.\nFor example, if you remove the minlength parameter from the code above, the output will be:\n[0 1 0 1 0 0 1 0 0 2]\n\n" ]
[ 2 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074671493_arrays_python.txt
Q: comparing array contents for counter purposes I'm trying to set up a comparison between an array and a given string. The idea being, that if i started building structures with multiple objects in them, that i could test for a key word in said structure and set up a counter to see how often that element is contained within that structure. Though this doesnt seem to work, as the terminal output i get is the "ohnoo". Hence I'm thinking that there is something wrong with the comparison in line 8. The compiler sees nothing wrong with the following code, so its hard to find a solution by myself. Here's a simple piece of code i tried to test this idea with. #include <stdio.h> #include <string.h> char string1[10] = "Automatic"; int main() { if(string1 == "Automatic") { printf("huzzah\n"); } else{ printf("ohnoo\n"); } } A: Strings in C cannot be compared in this way. Rather use strcmp. Otherwise, using == you are determining if they point to the same location in memory, rather than whether their contents are the same. #include <stdio.h> #include <string.h> char string1[10] = "Automatic"; int main() { if (strcmp(string1, "Automatic") == 0) { printf("huzzah\n"); } else{ printf("ohnoo\n"); } }
comparing array contents for counter purposes
I'm trying to set up a comparison between an array and a given string. The idea being, that if i started building structures with multiple objects in them, that i could test for a key word in said structure and set up a counter to see how often that element is contained within that structure. Though this doesnt seem to work, as the terminal output i get is the "ohnoo". Hence I'm thinking that there is something wrong with the comparison in line 8. The compiler sees nothing wrong with the following code, so its hard to find a solution by myself. Here's a simple piece of code i tried to test this idea with. #include <stdio.h> #include <string.h> char string1[10] = "Automatic"; int main() { if(string1 == "Automatic") { printf("huzzah\n"); } else{ printf("ohnoo\n"); } }
[ "Strings in C cannot be compared in this way. Rather use strcmp. Otherwise, using == you are determining if they point to the same location in memory, rather than whether their contents are the same.\n#include <stdio.h>\n#include <string.h>\n\nchar string1[10] = \"Automatic\";\n\nint main()\n{\n if (strcmp(string1, \"Automatic\") == 0)\n {\n printf(\"huzzah\\n\");\n }\n else{\n printf(\"ohnoo\\n\");\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "c", "string_comparison", "struct" ]
stackoverflow_0074671376_arrays_c_string_comparison_struct.txt
Q: How do i put numpy.float64 data into dataframe? Im having 5 differents dataframes with values like this: tanggal komoditas harga 1 Beras Sembako 12000 2 Beras Sembako 12000 ... Beras Sembako ... 31 Beras Sembako 11000 (the only difference between each dataframes is on the 'komoditas' columns values is having different names) Im using this loop to get the mean values for each of 5 dataframes that is used for z in dfs: for x in tanggal: mean = z.loc[z['tanggal'] == x, 'harga'].mean() rata = [mean] print(rata) dfs contains 5 different sets of dataframes that im trying to get the mean value from. tanggal is set of range from (1, 31) after trying to run it. im getting result as numpy.float64 data like this: [13916.666666666666][13916.666666666666][13895.833333333334] ... [13901.041666666666] Im trying to convert these values into a dataframe using this df_rata = pd.DataFrame(rata, columns =['Harga Rata']) but when i did it only one value showed up like this: Harga Rata 0 13901.041667 when i tried to define rata length using len(rata) it only showed result as only 1 value is stored inside the variable. Is there something that i did wrong? I'm very new to this and still learning, an explanation would be much appreciated. Thanks! A: Mark Ransom pointed out the issue in a comment. The fix is to append mean to rata in the loop: rata = [] for z in dfs: for x in tanggal: mean = z.loc[z['tanggal'] == x, 'harga'].mean() rata.append(mean) At this point, rata will be a list such that len(rata) == len(tanggal)*len(dfs) and the mean of harga across tanggal in the first, second, etc data frame is in rata[0 : len(tanggal)], rata[len(tanggal) : 2*len(tanggal)], etc respectively. A side comment, if your data is only a single list (like rata), consider using pandas.Series instead.
How do i put numpy.float64 data into dataframe?
Im having 5 differents dataframes with values like this: tanggal komoditas harga 1 Beras Sembako 12000 2 Beras Sembako 12000 ... Beras Sembako ... 31 Beras Sembako 11000 (the only difference between each dataframes is on the 'komoditas' columns values is having different names) Im using this loop to get the mean values for each of 5 dataframes that is used for z in dfs: for x in tanggal: mean = z.loc[z['tanggal'] == x, 'harga'].mean() rata = [mean] print(rata) dfs contains 5 different sets of dataframes that im trying to get the mean value from. tanggal is set of range from (1, 31) after trying to run it. im getting result as numpy.float64 data like this: [13916.666666666666][13916.666666666666][13895.833333333334] ... [13901.041666666666] Im trying to convert these values into a dataframe using this df_rata = pd.DataFrame(rata, columns =['Harga Rata']) but when i did it only one value showed up like this: Harga Rata 0 13901.041667 when i tried to define rata length using len(rata) it only showed result as only 1 value is stored inside the variable. Is there something that i did wrong? I'm very new to this and still learning, an explanation would be much appreciated. Thanks!
[ "Mark Ransom pointed out the issue in a comment. The fix is to append mean to rata in the loop:\nrata = []\nfor z in dfs:\n for x in tanggal:\n mean = z.loc[z['tanggal'] == x, 'harga'].mean()\n rata.append(mean)\n\nAt this point, rata will be a list such that len(rata) == len(tanggal)*len(dfs) and the mean of harga across tanggal in the first, second, etc data frame is in rata[0 : len(tanggal)], rata[len(tanggal) : 2*len(tanggal)], etc respectively.\nA side comment, if your data is only a single list (like rata), consider using pandas.Series instead.\n" ]
[ 0 ]
[]
[]
[ "arrays", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074667526_arrays_dataframe_numpy_pandas_python.txt
Q: Python Azure Can't Create Blob Container: This request is not authorized to perform this operation I'm trying to create a blob container within a Azure storage account with Azure's python API. def create_storage_container(storageAccountName: str, containerName: str): print(f"Creating storage container '{containerName}' in storage account '{storageAccountName}'") credentials = DefaultAzureCredential() url=F"https://{storageAccountName}.blob.core.windows.net" blobClient = BlobServiceClient(account_url=url, credential=credentials) containerClient = blobClient.get_container_client(containerName) containerClient.create_container() On create_container() I get the error: Exception has occurred: HttpResponseError This request is not authorized to perform this operation. RequestId:8a3f8af1-101e-0075-3351-074949000000 Time:2022-12-03T20:00:25.5236364Z ErrorCode:AuthorizationFailure Content: AuthorizationFailureThis request is not authorized to perform this operation. RequestId:8a3f8af1-101e-0075-3351-074949000000 Time:2022-12-03T20:00:25.5236364Z The storage account was created like so: # Creates a storage account if it does not already exist. # Returns the name of the storage account. def create_storage_account(resourceGroupName: str, location: str, subscriptionId: str, storageAccountName: str): credentials = AzureCliCredential() storageClient = StorageManagementClient(credentials, subscriptionId, "2018-02-01") # Why does this have creation powers for storage accounts instead of the ResourceManagementClient? params = { "sku": { "name": "Standard_LRS", "tier": "Standard" }, "kind": "StorageV2", "location": location, "supportsHttpsTrafficOnly": True } result = storageClient.storage_accounts.begin_create(resourceGroupName, storageAccountName, params) # type:ignore storageAccount = result.result(120) print(f"Done creating storage account with name: {storageAccount.name}") The storage accounts that are generated like this seem to have completely open network access, so I wouldn't think that would be an issue. How can I fix this error or create a storage container in another way programatically? Thanks A: Check the RBAC roles your user is assigned to for the storage account. The default ones don’t always enable you to view data and sounds like it’s causing your problems.
Python Azure Can't Create Blob Container: This request is not authorized to perform this operation
I'm trying to create a blob container within a Azure storage account with Azure's python API. def create_storage_container(storageAccountName: str, containerName: str): print(f"Creating storage container '{containerName}' in storage account '{storageAccountName}'") credentials = DefaultAzureCredential() url=F"https://{storageAccountName}.blob.core.windows.net" blobClient = BlobServiceClient(account_url=url, credential=credentials) containerClient = blobClient.get_container_client(containerName) containerClient.create_container() On create_container() I get the error: Exception has occurred: HttpResponseError This request is not authorized to perform this operation. RequestId:8a3f8af1-101e-0075-3351-074949000000 Time:2022-12-03T20:00:25.5236364Z ErrorCode:AuthorizationFailure Content: AuthorizationFailureThis request is not authorized to perform this operation. RequestId:8a3f8af1-101e-0075-3351-074949000000 Time:2022-12-03T20:00:25.5236364Z The storage account was created like so: # Creates a storage account if it does not already exist. # Returns the name of the storage account. def create_storage_account(resourceGroupName: str, location: str, subscriptionId: str, storageAccountName: str): credentials = AzureCliCredential() storageClient = StorageManagementClient(credentials, subscriptionId, "2018-02-01") # Why does this have creation powers for storage accounts instead of the ResourceManagementClient? params = { "sku": { "name": "Standard_LRS", "tier": "Standard" }, "kind": "StorageV2", "location": location, "supportsHttpsTrafficOnly": True } result = storageClient.storage_accounts.begin_create(resourceGroupName, storageAccountName, params) # type:ignore storageAccount = result.result(120) print(f"Done creating storage account with name: {storageAccount.name}") The storage accounts that are generated like this seem to have completely open network access, so I wouldn't think that would be an issue. How can I fix this error or create a storage container in another way programatically? Thanks
[ "Check the RBAC roles your user is assigned to for the storage account. The default ones don’t always enable you to view data and sounds like it’s causing your problems.\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_python_sdk", "python" ]
stackoverflow_0074670530_azure_azure_python_sdk_python.txt
Q: Typescript decorator for function, not method. Possible? I'm trying to add a custom TypeScript decorator in a function which is not included in a class and it seems that the compiler is complaining no matter what I do. Any thoughts? Is it possible? A: add a custom TypeScript decorator in a function Not to a raw function. The main issue is dealing with hoisting of functions. Any attempt to wrap a function in another function breaks the hoist. Support Targets A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration. Docs: https://www.typescriptlang.org/docs/handbook/decorators.html#decorators A: Isn't possible because the method decorator use the PropertyDescriptor and this one is only possible to use in classes. But, there is a lib that you can use the method decorators in functions, but without the sintax @myDecorator. The decorator has the same sintax, you can use exist method decorators in functions https://www.npmjs.com/package/pure-function-decorator But, instead this: class Somethind { @log myMethod() { //.... You can use in this way const myFunction = fnDecorator([log], () => { /*....*/}); And has the same result
Typescript decorator for function, not method. Possible?
I'm trying to add a custom TypeScript decorator in a function which is not included in a class and it seems that the compiler is complaining no matter what I do. Any thoughts? Is it possible?
[ "\nadd a custom TypeScript decorator in a function\n\nNot to a raw function. The main issue is dealing with hoisting of functions. Any attempt to wrap a function in another function breaks the hoist.\nSupport Targets\n\nA Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.\n\nDocs: https://www.typescriptlang.org/docs/handbook/decorators.html#decorators\n", "Isn't possible because the method decorator use the PropertyDescriptor and this one is only possible to use in classes.\nBut, there is a lib that you can use the method decorators in functions, but without the sintax @myDecorator. The decorator has the same sintax, you can use exist method decorators in functions\nhttps://www.npmjs.com/package/pure-function-decorator\nBut, instead this:\nclass Somethind {\n @log\n myMethod() { //....\n\nYou can use in this way\nconst myFunction = fnDecorator([log], () => { /*....*/});\n\nAnd has the same result\n" ]
[ 36, 0 ]
[]
[]
[ "decorator", "typescript" ]
stackoverflow_0037518913_decorator_typescript.txt
Q: How to make sure URLConnection is valid and will successfully connect in Java? how can you ensure URL you receive from users is a valid url and not just a http://nothing.com my code looks like this: String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com URL url = new URL(urlFromUser); // this might fail URLConnection urlConnection = url.openConnection(); and try catch is not enough, i want to make sure the site is real A: One way to check if a URL is valid is to use the java.net.URL class to attempt to create a URL object from the user-provided input. If the URL is invalid, the URL constructor will throw a MalformedURLException. You can catch this exception and handle it accordingly. Here's an example of how you might implement this: String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com try { URL url = new URL(urlFromUser); URLConnection urlConnection = url.openConnection(); // If we reached this point, it means the URL is valid and we can use the connection } catch (MalformedURLException e) { // The URL is not valid. You can either show an error message to the user or // try to fix the URL and create a new URL object. } Another option is to use the java.net.HttpURLConnection class to try to connect to the URL and check the response code. If the response code is in the range 200-299, it means the connection was successful and the URL is valid. Here's an example of how you might do this: String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com try { URL url = new URL(urlFromUser); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { // The connection was successful and the URL is valid } else { // The connection was not successful. The URL might be invalid or there might be // some other issue with the connection (e.g. the server is down). } } catch (MalformedURLException e) { // The URL is not valid. You can either show an error message to the user or // try to fix the URL and create a new URL object. } catch (IOException e) { // There was an IO error while trying to open the connection. This could be caused by // various factors, such as network issues or issues with the server. } It's important to note that even if the URL is valid and the connection is successful, there's no guarantee that the website or server at the other end of the connection will return the expected content or behave as expected. You'll need to handle any errors or unexpected behavior that might occur when using the connection. A: you can also use: if(new InetSocketAddress(urlFromUser, 80).isUnresolved()) { // URL is a not a valid server address } else { // URL is valid }
How to make sure URLConnection is valid and will successfully connect in Java?
how can you ensure URL you receive from users is a valid url and not just a http://nothing.com my code looks like this: String urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com URL url = new URL(urlFromUser); // this might fail URLConnection urlConnection = url.openConnection(); and try catch is not enough, i want to make sure the site is real
[ "One way to check if a URL is valid is to use the java.net.URL class to attempt to create a URL object from the user-provided input. If the URL is invalid, the URL constructor will throw a MalformedURLException. You can catch this exception and handle it accordingly.\nHere's an example of how you might implement this:\nString urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n URLConnection urlConnection = url.openConnection();\n // If we reached this point, it means the URL is valid and we can use the connection\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n}\n\nAnother option is to use the java.net.HttpURLConnection class to try to connect to the URL and check the response code. If the response code is in the range 200-299, it means the connection was successful and the URL is valid. Here's an example of how you might do this:\nString urlFromUser = getUrlFromUser(); // might return: http://www.notARealSite.com\n\ntry {\n URL url = new URL(urlFromUser);\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n int responseCode = connection.getResponseCode();\n\n if (responseCode >= 200 && responseCode < 300) {\n // The connection was successful and the URL is valid\n } else {\n // The connection was not successful. The URL might be invalid or there might be\n // some other issue with the connection (e.g. the server is down).\n }\n} catch (MalformedURLException e) {\n // The URL is not valid. You can either show an error message to the user or \n // try to fix the URL and create a new URL object.\n} catch (IOException e) {\n // There was an IO error while trying to open the connection. This could be caused by\n // various factors, such as network issues or issues with the server.\n}\n\nIt's important to note that even if the URL is valid and the connection is successful, there's no guarantee that the website or server at the other end of the connection will return the expected content or behave as expected. You'll need to handle any errors or unexpected behavior that might occur when using the connection.\n", "you can also use:\nif(new InetSocketAddress(urlFromUser, 80).isUnresolved()) {\n // URL is a not a valid server address\n}\nelse {\n // URL is valid\n}\n\n" ]
[ 1, -1 ]
[]
[]
[ "connection", "java", "url" ]
stackoverflow_0074671472_connection_java_url.txt
Q: Firestore get all Documents between two dates query(meetingsCollection, where("start", "in", today), orderBy("start", "asc") I'd like a Firestore query, so that I can fetch all documents between 02/12/2022 - 00:00:00.000 && 03/12/2022 00:00:00.000, ordered by the Date property start, so that I can bucketsize my firestore data request and limit overreads, then use said documents to visually filter accordingly via the front-end. Can you assist me with this? A: How to get start and end of day in Javascript? const start = new Date(); start.setUTCHours(0,0,0,0); const end = new Date(); end.setUTCHours(23,59,59,999); Firestore query by date range query( meetingsCollection, where("start", ">=", start), where("start", "<=", end) orderBy("start", "asc") ) A: db.collection("collection_name") .where("start", ">=", "02/12/2022 00:00:00.000") .where("start", "<=", "03/12/2022 00:00:00.000") .orderBy("start") .get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { // doc.data() contains the data for the document }); }); A: For anyone looking for the actual solution =>> const now = new Date(); const getDateFormatted = (date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate().toString().padStart(2, "0"); return `${year}-${month}-${day}`; } const startNow = new Date(`${getDateFormatted(now)}T00:00:00.000z`); //2021-09-01T00:00:00.000Z const endNow = new Date(`${getDateFormatted(now)}T23:59:59.000z`); const nowEvents = ref([]); const getNowEvents = async () => { onSnapshot(myEvents(startNow, endNow), (querySnapshot) => { let tmpEvents = []; querySnapshot.forEach((doc) => { let event = { id: doc.id, ...doc.data(), }; tmpEvents.push(event); }); nowEvents.value = tmpEvents; }); }
Firestore get all Documents between two dates
query(meetingsCollection, where("start", "in", today), orderBy("start", "asc") I'd like a Firestore query, so that I can fetch all documents between 02/12/2022 - 00:00:00.000 && 03/12/2022 00:00:00.000, ordered by the Date property start, so that I can bucketsize my firestore data request and limit overreads, then use said documents to visually filter accordingly via the front-end. Can you assist me with this?
[ "How to get start and end of day in Javascript?\nconst start = new Date();\nstart.setUTCHours(0,0,0,0);\n\nconst end = new Date();\nend.setUTCHours(23,59,59,999);\n\nFirestore query by date range\nquery(\n meetingsCollection,\n where(\"start\", \">=\", start),\n where(\"start\", \"<=\", end)\n orderBy(\"start\", \"asc\")\n)\n\n", " db.collection(\"collection_name\")\n .where(\"start\", \">=\", \"02/12/2022 00:00:00.000\")\n .where(\"start\", \"<=\", \"03/12/2022 00:00:00.000\")\n .orderBy(\"start\")\n .get()\n .then((querySnapshot) => {\n querySnapshot.forEach((doc) => {\n // doc.data() contains the data for the document\n });\n });\n\n", "For anyone looking for the actual solution =>>\nconst now = new Date();\n\nconst getDateFormatted = (date) => {\n const year = date.getFullYear();\n const month = date.getMonth() + 1;\n const day = date.getDate().toString().padStart(2, \"0\");\n return `${year}-${month}-${day}`;\n} \n\nconst startNow = new Date(`${getDateFormatted(now)}T00:00:00.000z`); //2021-09-01T00:00:00.000Z\nconst endNow = new Date(`${getDateFormatted(now)}T23:59:59.000z`);\n\nconst nowEvents = ref([]);\n\nconst getNowEvents = async () => {\n onSnapshot(myEvents(startNow, endNow), (querySnapshot) => {\n let tmpEvents = [];\n querySnapshot.forEach((doc) => {\n let event = {\n id: doc.id,\n ...doc.data(),\n };\n tmpEvents.push(event);\n });\n nowEvents.value = tmpEvents;\n });\n}\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "firebase", "google_cloud_firestore", "javascript" ]
stackoverflow_0074662002_firebase_google_cloud_firestore_javascript.txt
Q: Bit Operation in C I am new in C and this is for a school project. I am implementing the Skinny Block Cipher in C. My code: unsigned char *bits[8]; // this array holds 1 byte of data. ... call in another func to convert hex to bit. unsigned int four = bits[4] - '0'; // value 0 unsigned int seven = bits[7] - '0'; // value 1 unsigned int six = bits[6] - '0'; // value 1 four = four ^ ~(seven | six); // eq 1; Now, my question Do I have to convert the char to int every time to run the bit operation? What will happen if I do it using unsigned char? If I store the value for eq - 1 on an unsigned int, the value is fe which is wrong (according to an online bit calculator), on the other hand, if I store the result in an unsigned char, the value is -2 which is correct. What's the difference? I am kind of lost here. bits[8] is a pointer and I tried to do the eq 1 using indexes from bits pointer, like bits[4], etc but my VSCode throws an error and I don't understand why. Obviously, I have some gaps in my knowledge. I am using my Python knowledge to go through this. I don't know if I am giving all the information that's needed. Hit me up for extras! TIA. I updated the code unsigned char bits[9]; It converts a3 into 010100011. A: unsigned char *bits[8]; // this array holds 1 byte of data. No, it is an array of 8 pointers to char. unsigned int four = bits[4] - '0'; // value 0 This will not work as you subtract the integer '0' from the pointer. If you want to keep the string representation of the number in the binary form you need to define an array of 9 chars char bits[9] = "10010110"; Then you can do the operations as in your code. Do I have to convert the char to int every time to run the bit operation? What will happen if I do it using unsigned char? If you want to keep it as a string then - yes. unsigned char x = 0x96; unsigned int four = !!(x & (1 << 4)); unsigned int seven = !!(x & (1 << 7)); unsigned int six = !!(x & (1 << 6));
Bit Operation in C
I am new in C and this is for a school project. I am implementing the Skinny Block Cipher in C. My code: unsigned char *bits[8]; // this array holds 1 byte of data. ... call in another func to convert hex to bit. unsigned int four = bits[4] - '0'; // value 0 unsigned int seven = bits[7] - '0'; // value 1 unsigned int six = bits[6] - '0'; // value 1 four = four ^ ~(seven | six); // eq 1; Now, my question Do I have to convert the char to int every time to run the bit operation? What will happen if I do it using unsigned char? If I store the value for eq - 1 on an unsigned int, the value is fe which is wrong (according to an online bit calculator), on the other hand, if I store the result in an unsigned char, the value is -2 which is correct. What's the difference? I am kind of lost here. bits[8] is a pointer and I tried to do the eq 1 using indexes from bits pointer, like bits[4], etc but my VSCode throws an error and I don't understand why. Obviously, I have some gaps in my knowledge. I am using my Python knowledge to go through this. I don't know if I am giving all the information that's needed. Hit me up for extras! TIA. I updated the code unsigned char bits[9]; It converts a3 into 010100011.
[ "\n unsigned char *bits[8]; // this array holds 1 byte of data.\n\n\nNo, it is an array of 8 pointers to char.\n\nunsigned int four = bits[4] - '0'; // value 0\n\nThis will not work as you subtract the integer '0' from the pointer.\nIf you want to keep the string representation of the number in the binary form you need to define an array of 9 chars\nchar bits[9] = \"10010110\";\n\nThen you can do the operations as in your code.\n\nDo I have to convert the char to int every time to run the bit\noperation? What will happen if I do it using unsigned char?\n\nIf you want to keep it as a string then - yes.\nunsigned char x = 0x96;\n\nunsigned int four = !!(x & (1 << 4)); \nunsigned int seven = !!(x & (1 << 7));\nunsigned int six = !!(x & (1 << 6));\n\n" ]
[ 0 ]
[]
[]
[ "bit", "bit_manipulation", "c" ]
stackoverflow_0074671404_bit_bit_manipulation_c.txt
Q: Attaching information per file and commit in git How would I attach some information per single file and commit in git? My use case is as follows: I am used to assign "quality levels" to specific files of a project - like "complete", "checked", "reviewed". Let's stick with "checked" for the rest of this question. Let's further assume my project consists of files A, B, and C. Finally, let's use plain two-digit, increasing numbers to identify commits. In the beginning of the project, none of the files is checked. At commit 03, I decide that A is worth getting a "checked", so we have: File Checked Recent A 03 03 B 03 C 03 Column "Checked" denotes the commit when a file got checked, column "Recent" denotes the most recent commit that touched a file. Work continues to commit 05, now C gets checked: File Checked Recent A 03 04 B 05 C 05 05 (Please note that file A got modified by commit 04!) At this point I'd like to have a report about the current check status of my project, with the following outcome: ! A (03 -> 04) - B = C Meaning: Differences from commit 03 to 04 are unchecked in A B is completely unchecked C is completely checked I review the diffs on file A from commit 03 to 04, find some typo, fix the typo, commit the change, and mark the new commit 06 "checked" on A, resulting in the following picture: File Checked Recent A 06 06 B 05 C 05 05 and in the following report: = A - B = C In CVS, tags can be (ab)used to achieve such a per-file quality reporting. In git, I have been using side-car files per project that track quality status per file and commit, but that feels awkward and is quite some overhead to maintain. So how could this be achieved in git in a more natural way? A: In git universe you achieve this with branches and pull requests. File Checked Recent Git universe A 03 04 File in a topic (feature) branch B 05 File in a topic (feature) branch C 05 05 File has been merged into an important branch (often called main) Which version of the file has been reviewed doesn't need to be explicitly recorded because differences are seen during the merge process. The merge process is often is done via a Pull Request process provided by a tool running on top of git (Azure DevOps, GitLab, GitHub, BitBucket etc.) Please note you may have multiple levels of maturity of a code change. For example: featureX->develop->main. Git is very flexible in supporting different branching strategies; there are few popular established branching strategies each with its benefits and pain points. Since you're new to git you may benefit from using an established workflow rather than invent your own. Here are few popular names: Git Flow GitHub Flow GitLab Flow
Attaching information per file and commit in git
How would I attach some information per single file and commit in git? My use case is as follows: I am used to assign "quality levels" to specific files of a project - like "complete", "checked", "reviewed". Let's stick with "checked" for the rest of this question. Let's further assume my project consists of files A, B, and C. Finally, let's use plain two-digit, increasing numbers to identify commits. In the beginning of the project, none of the files is checked. At commit 03, I decide that A is worth getting a "checked", so we have: File Checked Recent A 03 03 B 03 C 03 Column "Checked" denotes the commit when a file got checked, column "Recent" denotes the most recent commit that touched a file. Work continues to commit 05, now C gets checked: File Checked Recent A 03 04 B 05 C 05 05 (Please note that file A got modified by commit 04!) At this point I'd like to have a report about the current check status of my project, with the following outcome: ! A (03 -> 04) - B = C Meaning: Differences from commit 03 to 04 are unchecked in A B is completely unchecked C is completely checked I review the diffs on file A from commit 03 to 04, find some typo, fix the typo, commit the change, and mark the new commit 06 "checked" on A, resulting in the following picture: File Checked Recent A 06 06 B 05 C 05 05 and in the following report: = A - B = C In CVS, tags can be (ab)used to achieve such a per-file quality reporting. In git, I have been using side-car files per project that track quality status per file and commit, but that feels awkward and is quite some overhead to maintain. So how could this be achieved in git in a more natural way?
[ "In git universe you achieve this with branches and pull requests.\n\n\n\n\nFile\nChecked\nRecent\nGit universe\n\n\n\n\nA\n03\n04\nFile in a topic (feature) branch\n\n\nB\n\n05\nFile in a topic (feature) branch\n\n\nC\n05\n05\nFile has been merged into an important branch (often called main)\n\n\n\n\nWhich version of the file has been reviewed doesn't need to be explicitly recorded because differences are seen during the merge process. The merge process is often is done via a Pull Request process provided by a tool running on top of git (Azure DevOps, GitLab, GitHub, BitBucket etc.)\nPlease note you may have multiple levels of maturity of a code change. For example: featureX->develop->main.\nGit is very flexible in supporting different branching strategies; there are few popular established branching strategies each with its benefits and pain points.\nSince you're new to git you may benefit from using an established workflow rather than invent your own. Here are few popular names:\n\nGit Flow\nGitHub Flow\nGitLab Flow\n\n" ]
[ 0 ]
[]
[]
[ "git", "version_control" ]
stackoverflow_0074671296_git_version_control.txt
Q: Python code to do breadth-first discovery of a non-binary tree My problem: I have a known root node that I'm starting with and a specific other target node that I'm trying to find the shortest path to. I'm trying to write Python code to implement the Iterative Deepening Breadth-First Search algo, up to some max depth (say, 5 vertices). However, there are two features that (I believe) make this problem unlike virtually all the other SO questions and/or online tutorials I've been able to find so far: I do not yet know the structure of the tree at all: all I know is that both the root and target nodes exist, as do many other unknown nodes. The root and target nodes could be separated by one vertice, by 5, by 10, etc. Also, the tree is not binary: any node can have none, one, or many sibling nodes. When I successfully find a path from the root node to the target node, I need to return the shortest path between them. (Most of the solutions I've seen involve returning the entire traversal order required to locate a node, which I don't need.) How would I go about implementing this? My immediate thought was to try some form of recursion, but that seems much better-suited to Depth-First Search. TLDR: In the example tree below (apologies for ugly design), I want to traverse it from Root to Target in alphabetical order. (This should result in the algorithm skipping the letters K and L, since it will have found the Target node immediately after J.) I want the function to return: [Root, B, E, H, Target] A: You're basically looking for the Dijkstra algorithm. Dijkstra's algorithm adapts Breadth First Search to let you find the shortest path to your target. In order to retrieve the shortest path from the origin to a node, all that needs to be stored is the parent for each node discovered Let's say this is your tree node: class TreeNode: def __init__(self, value, children=None, parent=None): self.value = value self.parent = parent self.children = [] if children is None else children This function returns the path from the tree root node to the target node: from queue import Queue def path_root2target(root_node, target_value): def build_path(target_node): path = [target_node] while path[-1].parent is not None: path.append(path[-1].parent) return path[::-1] q = Queue() q.put(root_node) while not q.empty(): node = q.get() if node.value == target_value: return build_path(node) for child in node.children: child.parent = node q.put(child) raise ValueError('Target node not found') Example: >>> D = TreeNode('D') >>> A = TreeNode('A', [D]) >>> B = TreeNode('B') >>> C = TreeNode('C') >>> R = TreeNode('R', [A, B, C]) >>> path_root2target(R, 'E') ValueError: Target node not found >>> [node.value for node in path_root2target(R, 'D')] ['R', 'A', 'D'] If you want to return the node values (instead of the nodes themselves, then just modify the build_path function accordingly. A: As crazy as this sounds, I also asked ChatGPT to help me with this problem and, after I requested that it tweak its output in a few ways, here's what it came up with (comments included!), with just a couple small edits by me to replicate the tree from my diagram. (I verified it works.) # Import the necessary modules import queue # Define a TreeNode class to represent each node in the tree class TreeNode: def __init__(self, value, children=[]): self.value = value self.children = children # Define a function to perform the search def iterative_deepening_bfs(tree, target): # Set the initial depth to 0 depth = 0 # Create an infinite loop while True: # Create a queue to store the nodes at the current depth q = queue.Queue() # Add the root node to the queue q.put(tree) # Create a set to track which nodes have been visited visited = set() # Create a dictionary to store the paths to each visited node paths = {tree: [tree]} # Create a variable to track whether the target has been found found = False # Create a loop to process the nodes at the current depth while not q.empty(): # Get the next node from the queue node = q.get() # If the node has not been visited yet, process it if node not in visited: # Check if the node is the target if node == target: # Set the found variable to a tuple containing the depth and path to the target, and break out of the loop found = (depth, paths[node]) break # Add the node to the visited set visited.add(node) # Add the node's children to the queue for child in node.children: q.put(child) paths[child] = paths[node] + [child] # If the target was found, return the depth and path to the target if found: return found # Increment the depth and continue the loop depth += 1 root = TreeNode("Root") nodeA = TreeNode("A") nodeB = TreeNode("B") nodeC = TreeNode("C") nodeD = TreeNode("D") nodeE = TreeNode("E") nodeF = TreeNode("F") nodeG = TreeNode("G") nodeH = TreeNode("H") nodeI = TreeNode("I") nodeJ = TreeNode("J") nodeK = TreeNode("K") nodeL = TreeNode("L") target = TreeNode("Target") root.children = [nodeA, nodeB, nodeC] nodeA.children = [nodeD] nodeB.children = [nodeE, nodeF] nodeC.children = [nodeG] nodeE.children = [nodeH] nodeF.children = [nodeI] nodeG.children = [nodeJ] nodeH.children = [target] nodeI.children = [nodeK] nodeJ.children = [nodeL] # Assign the root node to the tree variable tree = root # Call the iterative_deepening_bfs function to search for the target node result = iterative_deepening_bfs(tree, target) # Print the depth and path to the target node print(f"The target was found at depth {result[0]} with path [{', '.join([str(node.value) for node in result[1]])}]")
Python code to do breadth-first discovery of a non-binary tree
My problem: I have a known root node that I'm starting with and a specific other target node that I'm trying to find the shortest path to. I'm trying to write Python code to implement the Iterative Deepening Breadth-First Search algo, up to some max depth (say, 5 vertices). However, there are two features that (I believe) make this problem unlike virtually all the other SO questions and/or online tutorials I've been able to find so far: I do not yet know the structure of the tree at all: all I know is that both the root and target nodes exist, as do many other unknown nodes. The root and target nodes could be separated by one vertice, by 5, by 10, etc. Also, the tree is not binary: any node can have none, one, or many sibling nodes. When I successfully find a path from the root node to the target node, I need to return the shortest path between them. (Most of the solutions I've seen involve returning the entire traversal order required to locate a node, which I don't need.) How would I go about implementing this? My immediate thought was to try some form of recursion, but that seems much better-suited to Depth-First Search. TLDR: In the example tree below (apologies for ugly design), I want to traverse it from Root to Target in alphabetical order. (This should result in the algorithm skipping the letters K and L, since it will have found the Target node immediately after J.) I want the function to return: [Root, B, E, H, Target]
[ "You're basically looking for the Dijkstra algorithm. Dijkstra's algorithm adapts Breadth First Search to let you find the shortest path to your target. In order to retrieve the shortest path from the origin to a node, all that needs to be stored is the parent for each node discovered\nLet's say this is your tree node:\nclass TreeNode:\n def __init__(self, value, children=None, parent=None):\n self.value = value\n self.parent = parent\n self.children = [] if children is None else children\n\nThis function returns the path from the tree root node to the target node:\nfrom queue import Queue\n\ndef path_root2target(root_node, target_value):\n def build_path(target_node):\n path = [target_node]\n while path[-1].parent is not None:\n path.append(path[-1].parent)\n return path[::-1]\n q = Queue()\n q.put(root_node)\n while not q.empty():\n node = q.get()\n if node.value == target_value:\n return build_path(node)\n for child in node.children:\n child.parent = node\n q.put(child)\n raise ValueError('Target node not found')\n\nExample:\n>>> D = TreeNode('D')\n>>> A = TreeNode('A', [D])\n>>> B = TreeNode('B')\n>>> C = TreeNode('C')\n>>> R = TreeNode('R', [A, B, C])\n>>> path_root2target(R, 'E')\nValueError: Target node not found\n>>> [node.value for node in path_root2target(R, 'D')]\n['R', 'A', 'D']\n\nIf you want to return the node values (instead of the nodes themselves, then just modify the build_path function accordingly.\n", "As crazy as this sounds, I also asked ChatGPT to help me with this problem and, after I requested that it tweak its output in a few ways, here's what it came up with (comments included!), with just a couple small edits by me to replicate the tree from my diagram. (I verified it works.)\n# Import the necessary modules\nimport queue\n\n# Define a TreeNode class to represent each node in the tree\nclass TreeNode:\n def __init__(self, value, children=[]):\n self.value = value\n self.children = children\n\n\n# Define a function to perform the search\ndef iterative_deepening_bfs(tree, target):\n # Set the initial depth to 0\n depth = 0\n\n # Create an infinite loop\n while True:\n # Create a queue to store the nodes at the current depth\n q = queue.Queue()\n\n # Add the root node to the queue\n q.put(tree)\n\n # Create a set to track which nodes have been visited\n visited = set()\n\n # Create a dictionary to store the paths to each visited node\n paths = {tree: [tree]}\n\n # Create a variable to track whether the target has been found\n found = False\n\n # Create a loop to process the nodes at the current depth\n while not q.empty():\n # Get the next node from the queue\n node = q.get()\n\n # If the node has not been visited yet, process it\n if node not in visited:\n # Check if the node is the target\n if node == target:\n # Set the found variable to a tuple containing the depth and path to the target, and break out of the loop\n found = (depth, paths[node])\n break\n\n # Add the node to the visited set\n visited.add(node)\n\n # Add the node's children to the queue\n for child in node.children:\n q.put(child)\n paths[child] = paths[node] + [child]\n\n # If the target was found, return the depth and path to the target\n if found:\n return found\n\n # Increment the depth and continue the loop\n depth += 1\n\n\nroot = TreeNode(\"Root\")\nnodeA = TreeNode(\"A\")\nnodeB = TreeNode(\"B\")\nnodeC = TreeNode(\"C\")\nnodeD = TreeNode(\"D\")\nnodeE = TreeNode(\"E\")\nnodeF = TreeNode(\"F\")\nnodeG = TreeNode(\"G\")\nnodeH = TreeNode(\"H\")\nnodeI = TreeNode(\"I\")\nnodeJ = TreeNode(\"J\")\nnodeK = TreeNode(\"K\")\nnodeL = TreeNode(\"L\")\ntarget = TreeNode(\"Target\")\n\nroot.children = [nodeA, nodeB, nodeC]\nnodeA.children = [nodeD]\nnodeB.children = [nodeE, nodeF]\nnodeC.children = [nodeG]\nnodeE.children = [nodeH]\nnodeF.children = [nodeI]\nnodeG.children = [nodeJ]\nnodeH.children = [target]\nnodeI.children = [nodeK]\nnodeJ.children = [nodeL]\n\n# Assign the root node to the tree variable\ntree = root\n\n\n\n# Call the iterative_deepening_bfs function to search for the target node\nresult = iterative_deepening_bfs(tree, target)\n\n# Print the depth and path to the target node\nprint(f\"The target was found at depth {result[0]} with path [{', '.join([str(node.value) for node in result[1]])}]\")\n\n" ]
[ 1, 0 ]
[]
[]
[ "breadth_first_search", "graph_theory", "python", "tree" ]
stackoverflow_0074669889_breadth_first_search_graph_theory_python_tree.txt
Q: ESM import a .node addon I am trying to import a .node binary addon in an ESM & Node Typescript based context. However, when I try to do this I get the following error "error TS2307: Cannot find module './addon.node' or its corresponding type declarations." I've looked online for several solutions, these are my versions: NodeJS: v16.14.1 ts-node: v10.7.0 Typescript: 4.6.3 This is my current approach for importing: import addon from "./addon.node"; Just to note, because of my configuration I am limited to only using import. Thanks in advance for any support. A: Node.js import doesn’t support .node files. To import such files in an ESM context, you need to use createRequire: import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); const addon = require('./addon.node'); You could also import the .node file in a CommonJS file that an ESM file then imports. // addon.cjs module.exports = require('./addon.node'); // main.js import addon from './addon.cjs'; Finally, you could create an ESM loader that adds support for .node files to import, by wrapping the createRequire method into a loader (untested): import { cwd } from 'node:process'; import { pathToFileURL } from 'node:url'; const baseURL = pathToFileURL(`${cwd()}/`).href; export async function resolve(specifier, context, nextResolve) { if (specifier.endsWith('.node')) { const { parentURL = baseURL } = context; // Node.js normally errors on unknown file extensions, so return a URL for // specifiers ending in `.node`. return { shortCircuit: true, url: new URL(specifier, parentURL).href, }; } // Let Node.js handle all other specifiers. return nextResolve(specifier); } export async function load(url, context, nextLoad) { if (url.endsWith('.node')) { const source = ` import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; const require = createRequire(import.meta.url); const path = fileURLToPath(${url}); export default require(path);`; return { format: 'module', shortCircuit: true, source, }; } // Let Node.js handle all other URLs. return nextLoad(url); }
ESM import a .node addon
I am trying to import a .node binary addon in an ESM & Node Typescript based context. However, when I try to do this I get the following error "error TS2307: Cannot find module './addon.node' or its corresponding type declarations." I've looked online for several solutions, these are my versions: NodeJS: v16.14.1 ts-node: v10.7.0 Typescript: 4.6.3 This is my current approach for importing: import addon from "./addon.node"; Just to note, because of my configuration I am limited to only using import. Thanks in advance for any support.
[ "Node.js import doesn’t support .node files. To import such files in an ESM context, you need to use createRequire:\nimport { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);\n\nconst addon = require('./addon.node');\n\nYou could also import the .node file in a CommonJS file that an ESM file then imports.\n// addon.cjs\nmodule.exports = require('./addon.node');\n\n// main.js\nimport addon from './addon.cjs';\n\nFinally, you could create an ESM loader that adds support for .node files to import, by wrapping the createRequire method into a loader (untested):\nimport { cwd } from 'node:process';\nimport { pathToFileURL } from 'node:url';\n\nconst baseURL = pathToFileURL(`${cwd()}/`).href;\n\nexport async function resolve(specifier, context, nextResolve) {\n if (specifier.endsWith('.node')) {\n const { parentURL = baseURL } = context;\n\n // Node.js normally errors on unknown file extensions, so return a URL for\n // specifiers ending in `.node`.\n return {\n shortCircuit: true,\n url: new URL(specifier, parentURL).href,\n };\n }\n\n // Let Node.js handle all other specifiers.\n return nextResolve(specifier);\n}\n\nexport async function load(url, context, nextLoad) {\n if (url.endsWith('.node')) {\n const source = `\n import { createRequire } from 'node:module';\n import { fileURLToPath } from 'node:url';\n const require = createRequire(import.meta.url);\n const path = fileURLToPath(${url});\n export default require(path);`;\n\n return {\n format: 'module',\n shortCircuit: true,\n source,\n };\n }\n\n // Let Node.js handle all other URLs.\n return nextLoad(url);\n}\n\n" ]
[ 0 ]
[]
[]
[ "node.js", "typescript" ]
stackoverflow_0071819037_node.js_typescript.txt
Q: How to avoid Segmentation fault in pycocotools during decoding of RLE Here is a sample of decoding corrupted RLE: from pycocotools import mask # pycocotools version is 2.0.2 mask.decode({'size': [1024, 1024], 'counts': "OeSOk0[l0VOaSOn0kh0cNmYO'"}) As result it fails with Segmentation fault (core dumped) It looks like this: Python 3.6.15 (default) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> from pycocotools import mask >>> mask.decode({'size': [1024, 1024], 'counts': "OeSOk0[l0VOaSOn0kh0cNmYO'"}) Segmentation fault (core dumped) Questions: Is the way to validate RLE(Run-length encoding) before putting it in into mask.decode? (I think it's not possible, but still) Is the way to handle signal.SIGSEGV and continue executing of code? A: This issue is solved by updating pycocotools to version 2.0.5
How to avoid Segmentation fault in pycocotools during decoding of RLE
Here is a sample of decoding corrupted RLE: from pycocotools import mask # pycocotools version is 2.0.2 mask.decode({'size': [1024, 1024], 'counts': "OeSOk0[l0VOaSOn0kh0cNmYO'"}) As result it fails with Segmentation fault (core dumped) It looks like this: Python 3.6.15 (default) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> from pycocotools import mask >>> mask.decode({'size': [1024, 1024], 'counts': "OeSOk0[l0VOaSOn0kh0cNmYO'"}) Segmentation fault (core dumped) Questions: Is the way to validate RLE(Run-length encoding) before putting it in into mask.decode? (I think it's not possible, but still) Is the way to handle signal.SIGSEGV and continue executing of code?
[ "This issue is solved by updating pycocotools to version 2.0.5\n" ]
[ 0 ]
[]
[]
[ "pycocotools", "python", "rle" ]
stackoverflow_0073491138_pycocotools_python_rle.txt
Q: Docker container error: "javax.mail.MessagingException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate);" I am trying to read mails with my JAR file. I am running this jar inside a container. When running I face the below exception. javax.mail.MessagingException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate); nested exception is: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate) at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) What may be the reason for this exception? Do I need to expose any port in container? (I already exposed port 587). Is there a way to check if the mail server is reachable from the container? A: The first thing to check is whether the port is open and reachable from the container. You can do this by running the command "telnet " from inside the container. If the port is open, then the next step is to check the protocol and cipher suites used by the mail server. You can do this by running the command "openssl s_client -connect " from inside the container. This should provide information about the protocol and cipher suites used by the mail server. Once you have this information, you can make sure that your Java code is using the correct protocol and cipher suites to connect to the mail server.
Docker container error: "javax.mail.MessagingException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate);"
I am trying to read mails with my JAR file. I am running this jar inside a container. When running I face the below exception. javax.mail.MessagingException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate); nested exception is: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate) at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670) at javax.mail.Service.connect(Service.java:295) at javax.mail.Service.connect(Service.java:176) What may be the reason for this exception? Do I need to expose any port in container? (I already exposed port 587). Is there a way to check if the mail server is reachable from the container?
[ "The first thing to check is whether the port is open and reachable from the container. You can do this by running the command \"telnet \" from inside the container. If the port is open, then the next step is to check the protocol and cipher suites used by the mail server. You can do this by running the command \"openssl s_client -connect \" from inside the container. This should provide information about the protocol and cipher suites used by the mail server. Once you have this information, you can make sure that your Java code is using the correct protocol and cipher suites to connect to the mail server.\n" ]
[ 0 ]
[]
[]
[ "containers", "docker", "jakarta_mail", "java" ]
stackoverflow_0067742776_containers_docker_jakarta_mail_java.txt
Q: Why does `if` change the scope of this variable If I have something like this Case 1: if str, err := m.something(); err != nil { return err } fmt.Println(str) //str is undefined variable Case 2: str, err := m.something(); fmt.Println(str) //str is ok My question is why does the scope of the variable str change when its used in a format like this if str, err := m.something(); err != nil { return err //str scope ends } A: Because if statements (and for, and switch) are implicit blocks, according to the language spec, and := is for both declaration and assignment. If you want str to be available after the if, you could declare the variables first, and then assign to them in the if statement: var s string var err error if str, err = m.something(); err != nil // ...
Why does `if` change the scope of this variable
If I have something like this Case 1: if str, err := m.something(); err != nil { return err } fmt.Println(str) //str is undefined variable Case 2: str, err := m.something(); fmt.Println(str) //str is ok My question is why does the scope of the variable str change when its used in a format like this if str, err := m.something(); err != nil { return err //str scope ends }
[ "Because if statements (and for, and switch) are implicit blocks, according to the language spec, and := is for both declaration and assignment. If you want str to be available after the if, you could declare the variables first, and then assign to them in the if statement:\nvar s string\nvar err error\n\nif str, err = m.something(); err != nil\n// ...\n\n" ]
[ 2 ]
[]
[]
[ "go" ]
stackoverflow_0074671438_go.txt
Q: Is there a way in R to read multiple excel files, change columns to character, and then merge them? New-ish to R and I feel like this has a simple solution, but I can't figure it out. I have 59 excel files that I want to combine. However, 4 of the columns have a mix of dates and NA's (depending on if the study animal is a migrant or not) so R won't let me combine them because some are numeric and some are character. I was hoping to read all of the excel files into R, convert those 4 columns in each file to as.character, and then merge them all. I figured a loop could do this. Anything I find online has me typing out the name for each read file, which I don't really want to do for 59 files. And once I do have them read into R and those columns converted, can I merge them from R easily? Sorry if this is simple, but I'm not sure what to do that would make this easier. A: Yes, you can use a loop to read multiple Excel files into R and convert the columns you want to character. Once you have read all of the files into R, you can use the merge() function to combine them. Here is an example of how you could do this: # create a vector of file names filenames <- c("file1.xlsx", "file2.xlsx", "file3.xlsx", ...) # create an empty list to store the data frames df_list <- list() # loop through the file names for (f in filenames) { # read in the Excel file df <- read_excel(f) # convert the columns you want to character df[, c("col1", "col2", "col3", "col4")] <- as.character(df[, c("col1", "col2", "col3", "col4")]) # add the data frame to the list df_list[[f]] <- df } # use merge() to combine the data frames in the list final_df <- merge(df_list[[1]], df_list[[2]], ...) This code will read each Excel file, convert the specified columns to character, and then add the resulting data frame to a list. After all of the files have been processed, the merge() function is used to combine the data frames in the list into a single data frame. A: You can do this quickly using lapply. It was unclear exactly how you wanted to combine the files (a true merge by a common variable, or append the rows, or append the columns). Either way, I do not believe you need to change anything to as.character for any of the below approaches (2A - 2C) to work: library(readxl) # 1. Read in all excel files in a folder given a specific filepath filepath <- "your/file/path/" file_list <- list.files(path = filepath, pattern='*.xlsx') df_list <- lapply(file_list, read_excel) # 2a. Merge data (assuming a unique identifier, i.e "studyid") final_data <- Reduce(function(...) merge(..., by = "studyid", all = TRUE), df_list) # 2b. If all files have the same columns, append to one long dataset final_data <- do.call(rbind, df_list) # 2c. If you want to make a wide dataset (append all columns) final_data <- do.call(cbind, df_list)
Is there a way in R to read multiple excel files, change columns to character, and then merge them?
New-ish to R and I feel like this has a simple solution, but I can't figure it out. I have 59 excel files that I want to combine. However, 4 of the columns have a mix of dates and NA's (depending on if the study animal is a migrant or not) so R won't let me combine them because some are numeric and some are character. I was hoping to read all of the excel files into R, convert those 4 columns in each file to as.character, and then merge them all. I figured a loop could do this. Anything I find online has me typing out the name for each read file, which I don't really want to do for 59 files. And once I do have them read into R and those columns converted, can I merge them from R easily? Sorry if this is simple, but I'm not sure what to do that would make this easier.
[ "Yes, you can use a loop to read multiple Excel files into R and convert the columns you want to character. Once you have read all of the files into R, you can use the merge() function to combine them. Here is an example of how you could do this:\n# create a vector of file names\nfilenames <- c(\"file1.xlsx\", \"file2.xlsx\", \"file3.xlsx\", ...)\n\n# create an empty list to store the data frames\ndf_list <- list()\n\n# loop through the file names\nfor (f in filenames) {\n \n # read in the Excel file\n df <- read_excel(f)\n \n # convert the columns you want to character\n df[, c(\"col1\", \"col2\", \"col3\", \"col4\")] <- as.character(df[, c(\"col1\", \"col2\", \"col3\", \"col4\")])\n \n # add the data frame to the list\n df_list[[f]] <- df\n}\n\n# use merge() to combine the data frames in the list\nfinal_df <- merge(df_list[[1]], df_list[[2]], ...)\n\nThis code will read each Excel file, convert the specified columns to character, and then add the resulting data frame to a list. After all of the files have been processed, the merge() function is used to combine the data frames in the list into a single data frame.\n", "You can do this quickly using lapply. It was unclear exactly how you wanted to combine the files (a true merge by a common variable, or append the rows, or append the columns). Either way, I do not believe you need to change anything to as.character for any of the below approaches (2A - 2C) to work:\nlibrary(readxl)\n\n# 1. Read in all excel files in a folder given a specific filepath\nfilepath <- \"your/file/path/\"\nfile_list <- list.files(path = filepath, pattern='*.xlsx')\ndf_list <- lapply(file_list, read_excel)\n\n# 2a. Merge data (assuming a unique identifier, i.e \"studyid\")\nfinal_data <- Reduce(function(...) merge(..., by = \"studyid\", all = TRUE), df_list)\n\n# 2b. If all files have the same columns, append to one long dataset\nfinal_data <- do.call(rbind, df_list)\n\n# 2c. If you want to make a wide dataset (append all columns)\nfinal_data <- do.call(cbind, df_list)\n\n" ]
[ 0, 0 ]
[]
[]
[ "loops", "merge", "r", "readxl" ]
stackoverflow_0074670837_loops_merge_r_readxl.txt
Q: Why is my else clause not working in Django? I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working. I tried putting the else clause in the search.html page, but it keeps giving me errors and it seems when I try to fix the errors, nothing really happens, it stays the same. I expect the search_error.html page to appear when the user inputs a product name that is not in the database. Though I keep getting for example, when I type "hello," the page appears with "Search results for hello." But it should result the search_error.html page. I also tried currently a else clause in my views.py, but it shows the same thing. I think my else clause isn't working and I don't know why. My views.py: def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products}) else: return render(request, 'epharmacyweb/search_error.html') def search_error(request): return render(request, 'epharmacyweb/search_error.html') My urls.py under URLPatterns: path('search/', views.search, name='search'), path('search_error/', views.search_error, name='search_error'), My search.html page: {% if searched %} <div class="pb-3 h3">Search Results for {{ searched }}</div> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-5 g-3"> {% for product in products %} <div class="col"> <div class="card shadow-sm"> <img class="img-fluid" alt="Responsive image" src="{{ product.image.url }}"> <div class="card-body"> <p class="card-text"> <a class="text-dark text-decoration-none" href="{{ product.get_absolute_url }}">{{ product.title }}</a> </p> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted"></small> </div> </div> </div> </div> {% endfor %} </div> <br></br> {% else %} <h1>You haven't searched anything yet...</h1> {% endif %} A: I think you want to check if products = Product.objects.filter(title__icontains=searched) is returning results instead of checking if "searched" is in the GET arguments. To check if the database returned results you can you exists() https://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.query.QuerySet.exists A: Your if is returning true because the term 'searched' is in fact in the request.GET dictionary. That doesn't mean that there is a product in your database with the value request.GET['searched'], which might be "hello" when you type in "hello". request.GET is a dictionary with a key of 'searched' and a value of "hello". You can also use get(), which will either get the value of request['searched'] or return None, so you do not have to check it with an if at all. Now to check if the database has the value of the search term, you can check the queryset: def search(request): # Return the value or None searched = request.GET.get('searched') products = Product.objects.filter(title__icontains=searched) # Check if there are any products with the search term: if products: return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products}) else: return render(request, 'epharmacyweb/search_error.html')
Why is my else clause not working in Django?
I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working. I tried putting the else clause in the search.html page, but it keeps giving me errors and it seems when I try to fix the errors, nothing really happens, it stays the same. I expect the search_error.html page to appear when the user inputs a product name that is not in the database. Though I keep getting for example, when I type "hello," the page appears with "Search results for hello." But it should result the search_error.html page. I also tried currently a else clause in my views.py, but it shows the same thing. I think my else clause isn't working and I don't know why. My views.py: def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products}) else: return render(request, 'epharmacyweb/search_error.html') def search_error(request): return render(request, 'epharmacyweb/search_error.html') My urls.py under URLPatterns: path('search/', views.search, name='search'), path('search_error/', views.search_error, name='search_error'), My search.html page: {% if searched %} <div class="pb-3 h3">Search Results for {{ searched }}</div> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-5 g-3"> {% for product in products %} <div class="col"> <div class="card shadow-sm"> <img class="img-fluid" alt="Responsive image" src="{{ product.image.url }}"> <div class="card-body"> <p class="card-text"> <a class="text-dark text-decoration-none" href="{{ product.get_absolute_url }}">{{ product.title }}</a> </p> <div class="d-flex justify-content-between align-items-center"> <small class="text-muted"></small> </div> </div> </div> </div> {% endfor %} </div> <br></br> {% else %} <h1>You haven't searched anything yet...</h1> {% endif %}
[ "I think you want to check if products = Product.objects.filter(title__icontains=searched) is returning results instead of checking if \"searched\" is in the GET arguments.\nTo check if the database returned results you can you exists()\nhttps://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.query.QuerySet.exists\n", "Your if is returning true because the term 'searched' is in fact in the request.GET dictionary. That doesn't mean that there is a product in your database with the value request.GET['searched'], which might be \"hello\" when you type in \"hello\". request.GET is a dictionary with a key of 'searched' and a value of \"hello\". You can also use get(), which will either get the value of request['searched'] or return None, so you do not have to check it with an if at all.\nNow to check if the database has the value of the search term, you can check the queryset:\ndef search(request):\n \n # Return the value or None\n searched = request.GET.get('searched')\n\n products = Product.objects.filter(title__icontains=searched)\n\n # Check if there are any products with the search term:\n if products:\n return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products})\n else:\n return render(request, 'epharmacyweb/search_error.html')\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074671375_django_python.txt
Q: Apache Beam Python DoFn process method and keyword arguments I am using Apache Beam SDK 2.43.0 with Python 3.8 and I am seeing some behaviour in the example below that I do not understand. If I run the snippet as given, I get the error: ... File "apache_beam\runners\common.py", line 983, in apache_beam.runners.common.PerWindowInvoker._invoke_process_per_window TypeError: process() got multiple values for argument 'some_side_input' [while running 'use side input'] If I use beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar)) instead of beam.ParDo(UseSideInput(), some_side_input=beam.pvalue.AsSingleton(pcollect_bar)), i.e. use a positional argument for the some_side_input parameter instead of a keyword argument, the pipeline runs as expected. Similarly, if I use the UseSideInputNoTimestamp DoFn, which does not have the timestamp parameter in the process method, the pipeline runs and allows some_side_input to be supplied as a keyword argument. Another option is to specify the process method as process(self, element, timestamp=beam.DoFn.TimestampParam, some_side_input=None) and the snippet runs as is allowing a keyword argument. But, I am then providing a default value just to allow for the keyword argument. Just wondering, is this error expected and if so what is the reason for it? import apache_beam as beam import time class UseSideInput(beam.DoFn): def process(self, element, some_side_input, timestamp=beam.DoFn.TimestampParam): yield f"{element}~{some_side_input}~{timestamp.to_rfc3339()}" class UseSideInputNoTimestamp(beam.DoFn): def process(self, element, some_side_input): yield f"{element}~{some_side_input}" with beam.Pipeline() as p: pcollect_bar = p | "create bar" >> beam.Create(["bar"]) ( p | "create foo" >> beam.Create(["foo"]) | "add timestamp" >> beam.Map(lambda element: beam.window.TimestampedValue(element, int(time.time()))) # | "use side input" >> beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar)) <-- works # | "use side input no ts" >> beam.ParDo(UseSideInputNoTimestamp(), # some_side_input=beam.pvalue.AsSingleton(pcollect_bar)) <-- works | "use side input" >> beam.ParDo(UseSideInput(), some_side_input=beam.pvalue.AsSingleton(pcollect_bar)) | "print" >> beam.Map(print) ) A: From what I understood, the behaviour is if you have only the side input parameter, you can pass it with a keyword argument or positional argument, but if you have multiple parameters, you have to use positional arguments : Only side input argument : def test_side_input(self): import apache_beam as beam import time class UseSideInput(beam.DoFn): def process(self, element, some_side_input, *args, **kwargs): yield f"{element}~{some_side_input}" with beam.Pipeline() as p: pcollect_bar = p | "create bar" >> beam.Create(["bar"]) ( p | "create foo" >> beam.Create(["foo"]) | "add timestamp" >> beam.Map( lambda element: beam.window.TimestampedValue(element, int(time.time()))) | "use side input one arg positional" >> beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar)) # | "use side input one arg param" >> beam.ParDo(UseSideInput(), # some_side_input=beam.pvalue.AsSingleton(pcollect_bar)) | "print" >> beam.Map(print) ) Multiple arguments : def test_side_input(self): import apache_beam as beam import time class UseSideInput(beam.DoFn): def process(self, element, some_side_input, other, timestamp=beam.DoFn.TimestampParam, *args, **kwargs): yield f"{element}~{some_side_input}~{timestamp.to_rfc3339()}" with beam.Pipeline() as p: pcollect_bar = p | "create bar" >> beam.Create(["bar"]) ( p | "create foo" >> beam.Create(["foo"]) | "add timestamp" >> beam.Map( lambda element: beam.window.TimestampedValue(element, int(time.time()))) | "use side input" >> beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar), 0) | "print" >> beam.Map(print) ) In the second example, I have 2 arguments : some_side_input and other According to the documentation : 4.5.3. Accessing additional parameters in your DoFn, the timestamp allows to access to the timestamp of element and needs to have a default value with beam.DoFn.TimestampParam : import apache_beam as beam class ProcessRecord(beam.DoFn): def process(self, element, timestamp=beam.DoFn.TimestampParam): # access timestamp of element. pass This timestamp argument is not considered like other usual arguments. You also have an alternative for side inputs and use methods as functions in Map or FlatMap (built in Beam DoFn) and in this case the keyword arguments works everytime : def test_other(self): import apache_beam as beam import time def to_element(element, some_side_input, other): return f"{element}~{some_side_input}~{other}" with beam.Pipeline() as p: pcollect_bar = p | "create bar" >> beam.Create(["bar"]) ( p | "create foo" >> beam.Create(["foo"]) | "add timestamp" >> beam.Map( lambda element: beam.window.TimestampedValue(element, int(time.time()))) | "use side input" >> beam.Map(to_element, some_side_input=beam.pvalue.AsSingleton(pcollect_bar), other=0) | "print" >> beam.Map(print) )
Apache Beam Python DoFn process method and keyword arguments
I am using Apache Beam SDK 2.43.0 with Python 3.8 and I am seeing some behaviour in the example below that I do not understand. If I run the snippet as given, I get the error: ... File "apache_beam\runners\common.py", line 983, in apache_beam.runners.common.PerWindowInvoker._invoke_process_per_window TypeError: process() got multiple values for argument 'some_side_input' [while running 'use side input'] If I use beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar)) instead of beam.ParDo(UseSideInput(), some_side_input=beam.pvalue.AsSingleton(pcollect_bar)), i.e. use a positional argument for the some_side_input parameter instead of a keyword argument, the pipeline runs as expected. Similarly, if I use the UseSideInputNoTimestamp DoFn, which does not have the timestamp parameter in the process method, the pipeline runs and allows some_side_input to be supplied as a keyword argument. Another option is to specify the process method as process(self, element, timestamp=beam.DoFn.TimestampParam, some_side_input=None) and the snippet runs as is allowing a keyword argument. But, I am then providing a default value just to allow for the keyword argument. Just wondering, is this error expected and if so what is the reason for it? import apache_beam as beam import time class UseSideInput(beam.DoFn): def process(self, element, some_side_input, timestamp=beam.DoFn.TimestampParam): yield f"{element}~{some_side_input}~{timestamp.to_rfc3339()}" class UseSideInputNoTimestamp(beam.DoFn): def process(self, element, some_side_input): yield f"{element}~{some_side_input}" with beam.Pipeline() as p: pcollect_bar = p | "create bar" >> beam.Create(["bar"]) ( p | "create foo" >> beam.Create(["foo"]) | "add timestamp" >> beam.Map(lambda element: beam.window.TimestampedValue(element, int(time.time()))) # | "use side input" >> beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar)) <-- works # | "use side input no ts" >> beam.ParDo(UseSideInputNoTimestamp(), # some_side_input=beam.pvalue.AsSingleton(pcollect_bar)) <-- works | "use side input" >> beam.ParDo(UseSideInput(), some_side_input=beam.pvalue.AsSingleton(pcollect_bar)) | "print" >> beam.Map(print) )
[ "From what I understood, the behaviour is if you have only the side input parameter, you can pass it with a keyword argument or positional argument, but if you have multiple parameters, you have to use positional arguments :\n\nOnly side input argument :\n\ndef test_side_input(self):\n import apache_beam as beam\n import time\n \n\n class UseSideInput(beam.DoFn):\n def process(self, element, some_side_input, *args, **kwargs):\n yield f\"{element}~{some_side_input}\"\n\n with beam.Pipeline() as p:\n pcollect_bar = p | \"create bar\" >> beam.Create([\"bar\"])\n\n (\n p\n | \"create foo\" >> beam.Create([\"foo\"])\n | \"add timestamp\" >> beam.Map(\n lambda element: beam.window.TimestampedValue(element, int(time.time())))\n | \"use side input one arg positional\" >> beam.ParDo(UseSideInput(), beam.pvalue.AsSingleton(pcollect_bar))\n # | \"use side input one arg param\" >> beam.ParDo(UseSideInput(),\n # some_side_input=beam.pvalue.AsSingleton(pcollect_bar))\n | \"print\" >> beam.Map(print)\n )\n\n\nMultiple arguments :\n\ndef test_side_input(self):\n import apache_beam as beam\n import time\n\n class UseSideInput(beam.DoFn):\n def process(self, element, some_side_input, other, timestamp=beam.DoFn.TimestampParam, *args, **kwargs):\n yield f\"{element}~{some_side_input}~{timestamp.to_rfc3339()}\"\n\n with beam.Pipeline() as p:\n pcollect_bar = p | \"create bar\" >> beam.Create([\"bar\"])\n\n (\n p\n | \"create foo\" >> beam.Create([\"foo\"])\n | \"add timestamp\" >> beam.Map(\n lambda element: beam.window.TimestampedValue(element, int(time.time())))\n | \"use side input\" >> beam.ParDo(UseSideInput(),\n beam.pvalue.AsSingleton(pcollect_bar),\n 0)\n | \"print\" >> beam.Map(print)\n )\n\nIn the second example, I have 2 arguments : some_side_input and other\nAccording to the documentation : 4.5.3. Accessing additional parameters in your DoFn, the timestamp allows to access to the timestamp of element and needs to have a default value with beam.DoFn.TimestampParam :\nimport apache_beam as beam\n\nclass ProcessRecord(beam.DoFn):\n\n def process(self, element, timestamp=beam.DoFn.TimestampParam):\n # access timestamp of element.\n pass\n\nThis timestamp argument is not considered like other usual arguments.\nYou also have an alternative for side inputs and use methods as functions in Map or FlatMap (built in Beam DoFn) and in this case the keyword arguments works everytime :\ndef test_other(self):\n import apache_beam as beam\n import time\n\n def to_element(element, some_side_input, other):\n return f\"{element}~{some_side_input}~{other}\"\n\n with beam.Pipeline() as p:\n pcollect_bar = p | \"create bar\" >> beam.Create([\"bar\"])\n\n (\n p\n | \"create foo\" >> beam.Create([\"foo\"])\n | \"add timestamp\" >> beam.Map(\n lambda element: beam.window.TimestampedValue(element, int(time.time())))\n | \"use side input\" >> beam.Map(to_element,\n some_side_input=beam.pvalue.AsSingleton(pcollect_bar),\n other=0)\n | \"print\" >> beam.Map(print)\n )\n\n" ]
[ 1 ]
[]
[]
[ "apache_beam", "parameter_passing", "python" ]
stackoverflow_0074670833_apache_beam_parameter_passing_python.txt
Q: For every index, Find Largest element smaller that the current element to the right of the index in an unsorted array I have an unsorted array. example: arr = [5, 6, 7, 8, 4, 5, 6]. My goal is to do the following: for every index i: find j such that, 1. j > i and 2. arr[j] < arr[i] and 3. arr[j] is largest among all the numbers (smaller than arr[i]) between [i+1 till end]. 4. If there are multiple such j's, answer should be the lowest j. 5. If no such element exists, return -1 input: [5, 6, 7, 8, 4, 5, 6] ouput: [4, 5, 6, 6, -1, -1, -1] Brute Force Time: O(N^2): We can run 2 loops, basically for every index, traverse right and find the desired index if any. Using Balanced Binary Search Tree Time: O(Nlog(N)): We can build a balanced BST and for every node, compute the inOrder predecessor. Brute force is too expensive and Second approach is slightly complex. Can there be another approach using a different data structure like Stack or something to achieve our goal. NOTE: I could not find similar question on SO, if this is a duplicate question, please provide link to original one. EDIT 1: It was my bad to assume that implementation of both the approaches were very straightforward. So I am providing solution for the second approach. Using Balanced Binary Search Tree: class Node { left: Node; right: Node; val: number; } function addNodeToBBST(root: Node, val: numver): Node { // return newly added node ... any standard implementation AVL or RedBlack ... } function findNextLargestElement(arr: []) { const result = new Array<number>(arr.length); result[arr.length-1] = -1; const root = initializeTree(arr[0]); for(let i = arr.length - 2; i >= 0; i--) { const node = addNodeToBBST(arr[i], root); // O(Long(N)) const pre = inOrderPredecessor(node, root); // O(Long(N)) result[i] = pre && val.val || -1; } return result; } function inOrderPredecessor(node: Node, root: Node) { if (root == null) { return; } if (root == node) { if (root.left != null) { let tmp = root.left; while (tmp.right) tmp = tmp.right; pre = tmp; } return pre; } if(root.val > node.val) { return inOrderPredecessor(root->left, node) ; } else { if(root->right && !root->right.left) { return root; } return inOrderPredecessor(root->right, node); } } A: To solve this problem using a stack, we can iterate over the elements of the array from left to right, and maintain a stack of elements that are smaller than the current element. At each step, we can push the current element onto the stack, and then pop elements from the stack until we find an element that is smaller than the current element. The last element that we pop from the stack is the element that satisfies the given conditions, and we can return its index as the result. For example, suppose we have the following array: [5, 4, 3, 2, 1] Initialize an empty stack then iterate and push all elements onto it. At this point, the stack contains the elements [5, 4, 3, 2, 1]. We can then pop elements from the stack until we find an element that is smaller than the current element (1). The last element that we pop from the stack is 2, which satisfies the given conditions (it is smaller than 1 and it is the largest among all the numbers smaller than 1 between [i+1 till end]). Therefore, we can return the index of 2 (which is 3) as the result. Overall, this approach would take O(n) time, because we need to iterate over the array once and perform a constant number of operations for each element. This is faster than other methods, such as sorting, which would take O(n log n) time in the worst case.
For every index, Find Largest element smaller that the current element to the right of the index in an unsorted array
I have an unsorted array. example: arr = [5, 6, 7, 8, 4, 5, 6]. My goal is to do the following: for every index i: find j such that, 1. j > i and 2. arr[j] < arr[i] and 3. arr[j] is largest among all the numbers (smaller than arr[i]) between [i+1 till end]. 4. If there are multiple such j's, answer should be the lowest j. 5. If no such element exists, return -1 input: [5, 6, 7, 8, 4, 5, 6] ouput: [4, 5, 6, 6, -1, -1, -1] Brute Force Time: O(N^2): We can run 2 loops, basically for every index, traverse right and find the desired index if any. Using Balanced Binary Search Tree Time: O(Nlog(N)): We can build a balanced BST and for every node, compute the inOrder predecessor. Brute force is too expensive and Second approach is slightly complex. Can there be another approach using a different data structure like Stack or something to achieve our goal. NOTE: I could not find similar question on SO, if this is a duplicate question, please provide link to original one. EDIT 1: It was my bad to assume that implementation of both the approaches were very straightforward. So I am providing solution for the second approach. Using Balanced Binary Search Tree: class Node { left: Node; right: Node; val: number; } function addNodeToBBST(root: Node, val: numver): Node { // return newly added node ... any standard implementation AVL or RedBlack ... } function findNextLargestElement(arr: []) { const result = new Array<number>(arr.length); result[arr.length-1] = -1; const root = initializeTree(arr[0]); for(let i = arr.length - 2; i >= 0; i--) { const node = addNodeToBBST(arr[i], root); // O(Long(N)) const pre = inOrderPredecessor(node, root); // O(Long(N)) result[i] = pre && val.val || -1; } return result; } function inOrderPredecessor(node: Node, root: Node) { if (root == null) { return; } if (root == node) { if (root.left != null) { let tmp = root.left; while (tmp.right) tmp = tmp.right; pre = tmp; } return pre; } if(root.val > node.val) { return inOrderPredecessor(root->left, node) ; } else { if(root->right && !root->right.left) { return root; } return inOrderPredecessor(root->right, node); } }
[ "To solve this problem using a stack, we can iterate over the elements of the array from left to right, and maintain a stack of elements that are smaller than the current element. At each step, we can push the current element onto the stack, and then pop elements from the stack until we find an element that is smaller than the current element. The last element that we pop from the stack is the element that satisfies the given conditions, and we can return its index as the result.\nFor example, suppose we have the following array: [5, 4, 3, 2, 1]\nInitialize an empty stack then iterate and push all elements onto it.\nAt this point, the stack contains the elements [5, 4, 3, 2, 1]. We can then pop elements from the stack until we find an element that is smaller than the current element (1). The last element that we pop from the stack is 2, which satisfies the given conditions (it is smaller than 1 and it is the largest among all the numbers smaller than 1 between [i+1 till end]). Therefore, we can return the index of 2 (which is 3) as the result.\nOverall, this approach would take O(n) time, because we need to iterate over the array once and perform a constant number of operations for each element. This is faster than other methods, such as sorting, which would take O(n log n) time in the worst case.\n" ]
[ 0 ]
[]
[]
[ "algorithm", "arrays", "data_structures", "search", "sorting" ]
stackoverflow_0074665552_algorithm_arrays_data_structures_search_sorting.txt