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: How do I decompose() a reoccurring row in a table that I find located in an html page using Python? The row is a duplicate of the header row. The row occurs over and over again randomly, and I do not want it in the data set (naturally). I think the HTML page has it there to remind the viewer what column attributes they are looking at as they scroll down. Below is a sample of one of the row elements I want delete: <tr class ="thead" data-row="25> Here is another one: <tr class="thead" data-row="77"> They occur randomly, but if there's any way we could make a loop that can iterate and find the first cell in the row and determine that it is in fact the row we want to delete? Because they are identical each time. The first cell is always "Player", identifying the attribute. Below is an example of what that looks like as an HTML element. <th aria-label="Player" data-stat="player" scope="col" class=" poptip sort_default_asc center">Player</th> Maybe I can create a loop that iterates through each row and determines if that first cell says "Player". If it does, then delete that whole row. Is that possible? Here is my code so far: from bs4 import BeautifulSoup import pandas as pd import requests import string years = list(range(2023, 2024)) alphabet = list(string.ascii_lowercase) url_namegather = 'https://www.basketball-reference.com/players/a' lastname_a = 'a' url = url_namegather.format(lastname_a) data = requests.get(url) with open("player_names/lastname_a.html".format(lastname_a), "w+", encoding="utf-8") as f: f.write(data.text) with open("player_names/lastname_a.html", encoding="utf-8") as f: page = f.read() soup = BeautifulSoup(page, "html.parser") A: You can read the table directly using pandas. You may need to install lxml package though. df = pd.read_html('https://www.basketball-reference.com/players/a')[0] df This will get data without any duplicated header rows.
How do I decompose() a reoccurring row in a table that I find located in an html page using Python?
The row is a duplicate of the header row. The row occurs over and over again randomly, and I do not want it in the data set (naturally). I think the HTML page has it there to remind the viewer what column attributes they are looking at as they scroll down. Below is a sample of one of the row elements I want delete: <tr class ="thead" data-row="25> Here is another one: <tr class="thead" data-row="77"> They occur randomly, but if there's any way we could make a loop that can iterate and find the first cell in the row and determine that it is in fact the row we want to delete? Because they are identical each time. The first cell is always "Player", identifying the attribute. Below is an example of what that looks like as an HTML element. <th aria-label="Player" data-stat="player" scope="col" class=" poptip sort_default_asc center">Player</th> Maybe I can create a loop that iterates through each row and determines if that first cell says "Player". If it does, then delete that whole row. Is that possible? Here is my code so far: from bs4 import BeautifulSoup import pandas as pd import requests import string years = list(range(2023, 2024)) alphabet = list(string.ascii_lowercase) url_namegather = 'https://www.basketball-reference.com/players/a' lastname_a = 'a' url = url_namegather.format(lastname_a) data = requests.get(url) with open("player_names/lastname_a.html".format(lastname_a), "w+", encoding="utf-8") as f: f.write(data.text) with open("player_names/lastname_a.html", encoding="utf-8") as f: page = f.read() soup = BeautifulSoup(page, "html.parser")
[ "You can read the table directly using pandas. You may need to install lxml package though.\n\ndf = pd.read_html('https://www.basketball-reference.com/players/a')[0]\ndf\n\nThis will get data without any duplicated header rows.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074680578_python.txt
Q: Dev Proxy from webpack dev server to flask backend connection refused I've been working on a react app and I wanted to get hot re-loading going so I set up a webpack dev server. It's working great. It runs on localhost:8080 and the hot re-loading works perfectly. Great, now I just need to set up a proxy to route requests from 8080 to my flask server running on 5000 right? Cool so I added a proxy field to my webpack.config.js 27 devServer: { 28 static: './static/dist', 29 proxy: { 30 '/': 'http://localhost:5000', 31 secure:false, 32 } 33 }, But when I re-run npm run start "start": "webpack serve --open --mode=development" I get all of these connection refused errors. My flask is up and running fine and I can query the api routes directly and have data be returned. [webpack-dev-server] [HPM] Error occurred while proxying request localhost:8080/all_users to http://localhost:5000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors) I followed the URL and the only advice there was that this error usually occurs when the external system is down. Since mine isn't, I'm pretty confused. Any help would be greatly appreciated. A: I have no idea why but changing 'http://localhost:5000' to 'http://127.0.0.1:5000' solved my problem. If anyone knows I'd still be curious why this fixed it. I can go to 'http://localhost:5000' in my browser and query my backend just fine.
Dev Proxy from webpack dev server to flask backend connection refused
I've been working on a react app and I wanted to get hot re-loading going so I set up a webpack dev server. It's working great. It runs on localhost:8080 and the hot re-loading works perfectly. Great, now I just need to set up a proxy to route requests from 8080 to my flask server running on 5000 right? Cool so I added a proxy field to my webpack.config.js 27 devServer: { 28 static: './static/dist', 29 proxy: { 30 '/': 'http://localhost:5000', 31 secure:false, 32 } 33 }, But when I re-run npm run start "start": "webpack serve --open --mode=development" I get all of these connection refused errors. My flask is up and running fine and I can query the api routes directly and have data be returned. [webpack-dev-server] [HPM] Error occurred while proxying request localhost:8080/all_users to http://localhost:5000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors) I followed the URL and the only advice there was that this error usually occurs when the external system is down. Since mine isn't, I'm pretty confused. Any help would be greatly appreciated.
[ "I have no idea why but changing 'http://localhost:5000' to 'http://127.0.0.1:5000' solved my problem.\nIf anyone knows I'd still be curious why this fixed it. I can go to 'http://localhost:5000' in my browser and query my backend just fine.\n" ]
[ 0 ]
[]
[]
[ "flask", "proxy", "webpack", "webpack_dev_server" ]
stackoverflow_0074622418_flask_proxy_webpack_webpack_dev_server.txt
Q: Can't instantiate abstract class Service with abstract method command_line_args I am trying to make my first program using Python to download the meme from one of the sites and it was working well after that it started throwing problems that I do not know how to solve from urllib import request import undetected_chromedriver as UC from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.service import Service from undetected_chromedriver._compat import ChromeDriverManager post = "az28zPm" #this 6 digit value is the unique id for the meme options = Options() options.headless = True url = "https://9gag.com/gag/" + post driver = UC.Chrome(service=Service(ChromeDriverManager().install()),options=options) driver.get(url) if not os.path.isdir("Attachments/" + post): os.makedirs("Attachments/" + post) try: video_link = driver.find_element( By.XPATH, '//*[@id]/div[2]/div[1]/a/div/video/source[1]').get_attribute('src') request.urlretrieve(video_link, "Attachments/" + post + "/" + "Meme.mp4") except: image_link = driver.find_element( By.XPATH,'//*[@id]/div[2]/div[1]/a/div/picture/img').get_attribute('src') request.urlretrieve(image_link, "Attachments/" + post + "/" + "Meme.jpg") A: change common in 5th line to chrome if you have: TypeError: Can't instantiate abstract class Service with abstract method command_line_args. before: from selenium.webdriver.common.service import Service after: from selenium.webdriver.chrome.service import Service
Can't instantiate abstract class Service with abstract method command_line_args
I am trying to make my first program using Python to download the meme from one of the sites and it was working well after that it started throwing problems that I do not know how to solve from urllib import request import undetected_chromedriver as UC from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.service import Service from undetected_chromedriver._compat import ChromeDriverManager post = "az28zPm" #this 6 digit value is the unique id for the meme options = Options() options.headless = True url = "https://9gag.com/gag/" + post driver = UC.Chrome(service=Service(ChromeDriverManager().install()),options=options) driver.get(url) if not os.path.isdir("Attachments/" + post): os.makedirs("Attachments/" + post) try: video_link = driver.find_element( By.XPATH, '//*[@id]/div[2]/div[1]/a/div/video/source[1]').get_attribute('src') request.urlretrieve(video_link, "Attachments/" + post + "/" + "Meme.mp4") except: image_link = driver.find_element( By.XPATH,'//*[@id]/div[2]/div[1]/a/div/picture/img').get_attribute('src') request.urlretrieve(image_link, "Attachments/" + post + "/" + "Meme.jpg")
[ "change common in 5th line to chrome if you have:\nTypeError: Can't instantiate abstract class Service with abstract method command_line_args.\nbefore:\nfrom selenium.webdriver.common.service import Service\n\nafter:\nfrom selenium.webdriver.chrome.service import Service\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074645457_python.txt
Q: Pod init & Pod install Failure - iOS Xcode beta 14.0 I have issue while I tried to do pod init or pod install, getting following errors. Using Xcode 14 beta & OS version 12.4. Since after Xcode and OS update have issues, pod install Ignoring ffi-1.15.5 because its extensions are not built. Try: gem pristine ffi --version 1.15.5 Ignoring executable-hooks-1.6.1 because its extensions are not built. Try: gem pristine executable-hooks --version 1.6.1 Ignoring gem-wrappers-1.4.0 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.4.0 Analyzing dependencies [!] Smart quotes were detected and ignored in your Podfile. To avoid issues in the future, you should not use TextEdit for editing it. If you are not using TextEdit, you should turn off smart quotes in your editor of choice. /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface/error_report.rb:34:in `force_encoding': can't modify frozen String (FrozenError) from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface/error_report.rb:34:in `report' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:66:in `report_error' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:396:in `handle_exception' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:337:in `rescue in run' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:324:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:52:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/bin/pod:55:in `<top (required)>' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `load' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `<main>' /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/xcodeproj-1.21.0/lib/xcodeproj/project.rb:228:in `initialize_from_file': [Xcodeproj] Unknown object version (56). (RuntimeError) from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/xcodeproj-1.21.0/lib/xcodeproj/project.rb:113:in `open' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1190:in `block (2 levels) in inspect_targets_to_integrate' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1189:in `each' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1189:in `block in inspect_targets_to_integrate' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface.rb:64:in `section' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1184:in `inspect_targets_to_integrate' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:106:in `analyze' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:416:in `analyze' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:241:in `block in resolve_dependencies' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface.rb:64:in `section' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:240:in `resolve_dependencies' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:161:in `install!' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command/install.rb:52:in `run' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:334:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:52:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/bin/pod:55:in `<top (required)>' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `load' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `<main>' I have several solutions like, uninstall cocoa pods and reinstalled. I tried brew update as well brew update brew install fastlane fastlane install_plugins None of them worked out for me. Still getting above errors. A: I changed the Project Format from Xcode 14.0 to Xcode 13.0 and it worked for me. A: This may be the issue: Smart quotes were detected and ignored in your Podfile. Try to check your Podfile in some text editor like vscode, vim or nano and substitute all the quotes with new ones A: I was not able to fix the issue in Xcode beta, tried to change the path sudo xcode-select cocoapods uninstalled and reinstalled, gem installed, brew everything but nothing worked. Then changed the version Xcode beta 14.0 to Xcode 13.4. After that tried, sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer then pod deintegrated pod deintegrate finally pod install then started working... A: post_install do |installer| installer.generated_projects.each do |project| project.targets.each do |target| target.build_configurations.each do |config| config.build_settings["DEVELOPMENT_TEAM"] = "Your Team ID" end end end end A: It worked for me for xcode 14 beta. sudo xcode-select -switch /Applications/Xcode-beta.app/Contents/Developer A: Change project compatibility to 13.0 - worked for me :) right here
Pod init & Pod install Failure - iOS Xcode beta 14.0
I have issue while I tried to do pod init or pod install, getting following errors. Using Xcode 14 beta & OS version 12.4. Since after Xcode and OS update have issues, pod install Ignoring ffi-1.15.5 because its extensions are not built. Try: gem pristine ffi --version 1.15.5 Ignoring executable-hooks-1.6.1 because its extensions are not built. Try: gem pristine executable-hooks --version 1.6.1 Ignoring gem-wrappers-1.4.0 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.4.0 Analyzing dependencies [!] Smart quotes were detected and ignored in your Podfile. To avoid issues in the future, you should not use TextEdit for editing it. If you are not using TextEdit, you should turn off smart quotes in your editor of choice. /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface/error_report.rb:34:in `force_encoding': can't modify frozen String (FrozenError) from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface/error_report.rb:34:in `report' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:66:in `report_error' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:396:in `handle_exception' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:337:in `rescue in run' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:324:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:52:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/bin/pod:55:in `<top (required)>' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `load' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `<main>' /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/xcodeproj-1.21.0/lib/xcodeproj/project.rb:228:in `initialize_from_file': [Xcodeproj] Unknown object version (56). (RuntimeError) from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/xcodeproj-1.21.0/lib/xcodeproj/project.rb:113:in `open' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1190:in `block (2 levels) in inspect_targets_to_integrate' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1189:in `each' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1189:in `block in inspect_targets_to_integrate' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface.rb:64:in `section' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:1184:in `inspect_targets_to_integrate' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer/analyzer.rb:106:in `analyze' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:416:in `analyze' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:241:in `block in resolve_dependencies' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/user_interface.rb:64:in `section' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:240:in `resolve_dependencies' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/installer.rb:161:in `install!' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command/install.rb:52:in `run' from /Users/azeemazeez/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/claide-1.1.0/lib/claide/command.rb:334:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/lib/cocoapods/command.rb:52:in `run' from /usr/local/Cellar/cocoapods/1.11.3/libexec/gems/cocoapods-1.11.3/bin/pod:55:in `<top (required)>' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `load' from /usr/local/Cellar/cocoapods/1.11.3/libexec/bin/pod:23:in `<main>' I have several solutions like, uninstall cocoa pods and reinstalled. I tried brew update as well brew update brew install fastlane fastlane install_plugins None of them worked out for me. Still getting above errors.
[ "I changed the Project Format from Xcode 14.0 to Xcode 13.0 and it worked for me.\n\n\n", "This may be the issue:\nSmart quotes were detected and ignored in your Podfile.\n\nTry to check your Podfile in some text editor like vscode, vim or nano and substitute all the quotes with new ones\n", "I was not able to fix the issue in Xcode beta, tried to change the path sudo xcode-select cocoapods uninstalled and reinstalled, gem installed, brew everything but nothing worked.\nThen changed the version Xcode beta 14.0 to Xcode 13.4.\nAfter that tried,\nsudo xcode-select -switch /Applications/Xcode.app/Contents/Developer\n\nthen pod deintegrated\npod deintegrate\n\nfinally\npod install\n\nthen started working...\n", "post_install do |installer|\n installer.generated_projects.each do |project|\n project.targets.each do |target|\n target.build_configurations.each do |config|\n config.build_settings[\"DEVELOPMENT_TEAM\"] = \"Your Team ID\"\n end\n end\n end\nend\n\n", "It worked for me for xcode 14 beta.\nsudo xcode-select -switch /Applications/Xcode-beta.app/Contents/Developer\n\n", "Change project compatibility to 13.0 - worked for me :)\nright here\n" ]
[ 23, 1, 1, 0, 0, 0 ]
[]
[]
[ "cocoapods", "ios", "iphone", "swift" ]
stackoverflow_0072724819_cocoapods_ios_iphone_swift.txt
Q: Chrome Extension Service Worker not Supporting Importing Other JS Files or NPM Packages I am developing a Chrome Extension with React. In my service worker file, background.js, I need to import another JS file, which for simplicity, only exports an empty {} for now. background.js import store from './testImport'; console.log("Hello Service Worker.") testImport.js export default {} but with no success. I get this error: I searched for my problem, and most solutions suggested to add "type": "module" to manifest.json: "background": { "service_worker": "background.js", "type": "module" }, I did that and I got a new very vague error message: An unknown error occurred when fetching the script. I tried replacing the import with a require: const store = require('./testImport'); console.log("Hello Service Worker.") But these results in another error: Uncaught ReferenceError: require is not defined Anyway, I don't think require is the solution anyway. Import statements should work, as I've seen them used by others within service worker files and it worked for them. The problem is there are quite a few resources on the internet on this issue and I feel I've exhuasted them all. Why don't import statements work in my service worker file? Am I doing something wrong? UPDATE @wOxxOm's suggestion to add ./ and .js when importing other JS modules works! However, I need to import NPM packages into the service worker, and I get this error: Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../" package.json { "name": "app", "version": "0.1.0", "private": true, "dependencies": { "@reduxjs/toolkit": "^1.8.3", "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^13.3.0", "@testing-library/user-event": "^13.5.0", "@types/jest": "^27.5.2", "@types/node": "^16.11.41", "@types/react": "^18.0.14", "@types/react-dom": "^18.0.5", "axios": "^0.27.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^8.0.2", "react-scripts": "5.0.1", "react-scroll": "^1.8.7", "typescript": "^4.7.4", "watch": "^1.0.2", "web-vitals": "^2.1.4", "webext-redux": "^2.1.9" }, "scripts": { "start": "react-scripts start", "build": "INLINE_RUNTIME_CHUNK=false react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "watch": "watch 'npm run build' src" }, "watch": { "build": "src/" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@types/chrome": "0.0.193", "@types/react-scroll": "^1.8.3", "autoprefixer": "^10.4.7", "npm-watch": "^0.11.0", "postcss": "^8.4.14", "tailwindcss": "^3.1.3" } } A: When you run npm command. NPM replace package name to real path. You need to just find real path so that chrome browser will find it. Real path like this: /node_modules/pkg-name/dist/main.js Method 1. Create path.js file and add this line. const fullPath = await import.meta.resolve("magic-string"); const path = fullPath?.match(/(\/node_modules.*)/)[0]; console.log(path); then add this line inside scripts in package.json and run npm run path. "path": "node --experimental-import-meta-resolve path.js", copy console output text. Replace package name with this copied path. Method 2 Install other npm package to find and replace npm packages' virtual path to real path so that chrome browser will find it. Install Path-fixxer Add this line in path.js import setAllPkgPath from "path-fixxer"; setAllPkgPath(); then run command : npm run path. Now open browser to test it. Note: It only work with esm npm packages.
Chrome Extension Service Worker not Supporting Importing Other JS Files or NPM Packages
I am developing a Chrome Extension with React. In my service worker file, background.js, I need to import another JS file, which for simplicity, only exports an empty {} for now. background.js import store from './testImport'; console.log("Hello Service Worker.") testImport.js export default {} but with no success. I get this error: I searched for my problem, and most solutions suggested to add "type": "module" to manifest.json: "background": { "service_worker": "background.js", "type": "module" }, I did that and I got a new very vague error message: An unknown error occurred when fetching the script. I tried replacing the import with a require: const store = require('./testImport'); console.log("Hello Service Worker.") But these results in another error: Uncaught ReferenceError: require is not defined Anyway, I don't think require is the solution anyway. Import statements should work, as I've seen them used by others within service worker files and it worked for them. The problem is there are quite a few resources on the internet on this issue and I feel I've exhuasted them all. Why don't import statements work in my service worker file? Am I doing something wrong? UPDATE @wOxxOm's suggestion to add ./ and .js when importing other JS modules works! However, I need to import NPM packages into the service worker, and I get this error: Uncaught TypeError: Failed to resolve module specifier "axios". Relative references must start with either "/", "./", or "../" package.json { "name": "app", "version": "0.1.0", "private": true, "dependencies": { "@reduxjs/toolkit": "^1.8.3", "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^13.3.0", "@testing-library/user-event": "^13.5.0", "@types/jest": "^27.5.2", "@types/node": "^16.11.41", "@types/react": "^18.0.14", "@types/react-dom": "^18.0.5", "axios": "^0.27.2", "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^8.0.2", "react-scripts": "5.0.1", "react-scroll": "^1.8.7", "typescript": "^4.7.4", "watch": "^1.0.2", "web-vitals": "^2.1.4", "webext-redux": "^2.1.9" }, "scripts": { "start": "react-scripts start", "build": "INLINE_RUNTIME_CHUNK=false react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "watch": "watch 'npm run build' src" }, "watch": { "build": "src/" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "@types/chrome": "0.0.193", "@types/react-scroll": "^1.8.3", "autoprefixer": "^10.4.7", "npm-watch": "^0.11.0", "postcss": "^8.4.14", "tailwindcss": "^3.1.3" } }
[ "When you run npm command. NPM replace package name to real path.\nYou need to just find real path so that chrome browser will find it.\nReal path like this:\n/node_modules/pkg-name/dist/main.js\n\nMethod 1.\nCreate path.js file and add this line.\nconst fullPath = await import.meta.resolve(\"magic-string\");\nconst path = fullPath?.match(/(\\/node_modules.*)/)[0];\nconsole.log(path);\n\nthen add this line inside scripts in package.json and run npm run path.\n\"path\": \"node --experimental-import-meta-resolve path.js\",\ncopy console output text. Replace package name with this copied path.\nMethod 2 \nInstall other npm package to find and replace \nnpm packages' virtual path to real path so that chrome browser will find it.\nInstall Path-fixxer\nAdd this line in path.js\nimport setAllPkgPath from \"path-fixxer\";\nsetAllPkgPath();\n\nthen run command : npm run path.\nNow open browser to test it.\nNote: It only work with esm npm packages.\n" ]
[ 0 ]
[]
[]
[ "google_chrome_extension", "reactjs" ]
stackoverflow_0073011178_google_chrome_extension_reactjs.txt
Q: Workbook_Open() execution for hidding / showing Sheets at Excel startup I have an application with two sheets. The First is a LOGIN sheet where users can login to have access to the second sheet : the Working Sheet. At the start of the application, i have the Working Sheet set to xlSheetHidden in the sub Workbook_Open(), keeping the LOGIN sheet always visible. Only when the user Login with correct name and pw that the Working sheet is set to xlSheetVisible from the Login Sub. My trouble is that when i save and close the application while the Working Sheet is active, at the next start of the application , the Working Sheet appears a fraction of second before been set to xlSheetHidden and disappearing. This is not very comfortable and i would like to avoid it. The Sub code as follow: Private Sub Workbook_Open() Application.ScreenUpdating = False Worksheets("Working Sheet").Visible = xlSheetHidden Application.ScreenUpdating = True End Sub I have tried to activate the LOGIN sheet before closing the application so that at the next start the working sheet won't appear but it doesn't work. I tried that same activation code within the Workbook_Open() sub but the codes in that sub execute after to showing and disappearance of the working sheet at the start of the application. I would appreciate if i could have an answer to this here. Private Sub Workbook_BeforeClose(Cancel As Boolean) Worksheets("LOGIN").Activate End Sub A: Why not have two different workbooks. The first looks after the login. The second is your real data and is password protected. The login workbook does the user validation and then opens the real data workbook.
Workbook_Open() execution for hidding / showing Sheets at Excel startup
I have an application with two sheets. The First is a LOGIN sheet where users can login to have access to the second sheet : the Working Sheet. At the start of the application, i have the Working Sheet set to xlSheetHidden in the sub Workbook_Open(), keeping the LOGIN sheet always visible. Only when the user Login with correct name and pw that the Working sheet is set to xlSheetVisible from the Login Sub. My trouble is that when i save and close the application while the Working Sheet is active, at the next start of the application , the Working Sheet appears a fraction of second before been set to xlSheetHidden and disappearing. This is not very comfortable and i would like to avoid it. The Sub code as follow: Private Sub Workbook_Open() Application.ScreenUpdating = False Worksheets("Working Sheet").Visible = xlSheetHidden Application.ScreenUpdating = True End Sub I have tried to activate the LOGIN sheet before closing the application so that at the next start the working sheet won't appear but it doesn't work. I tried that same activation code within the Workbook_Open() sub but the codes in that sub execute after to showing and disappearance of the working sheet at the start of the application. I would appreciate if i could have an answer to this here. Private Sub Workbook_BeforeClose(Cancel As Boolean) Worksheets("LOGIN").Activate End Sub
[ "Why not have two different workbooks. The first looks after the login. The second is your real data and is password protected. The login workbook does the user validation and then opens the real data workbook.\n" ]
[ 0 ]
[]
[]
[ "app_startup", "excel", "open_closed_principle", "spreadsheet" ]
stackoverflow_0074673714_app_startup_excel_open_closed_principle_spreadsheet.txt
Q: Lwt promise local storage, is it possible? I'm building an application using Lwt, and it would be nice for me to be able to have some sort of context, or promise local static storage for the life cycle of the promise. Is there any way to do this? Ideally it could be a simple Map that is available to each promise. Ideally it would be like: val get_lwt_context : 'a Lwt.t -> 'a Map.t This would return the storage context for promise t. Is this possible? Is there another library that implements this? A: There is indeed such a mechanism in Lwt, called implicit callback argument, see Documentation. It is considered deprecated, because it is too easy to make mistakes with it, but sometimes this is really useful for some things like logging for instance. Such a mechanism can't be implemented by a library outside of Lwt, this needs to be handled in some way by the scheduler.
Lwt promise local storage, is it possible?
I'm building an application using Lwt, and it would be nice for me to be able to have some sort of context, or promise local static storage for the life cycle of the promise. Is there any way to do this? Ideally it could be a simple Map that is available to each promise. Ideally it would be like: val get_lwt_context : 'a Lwt.t -> 'a Map.t This would return the storage context for promise t. Is this possible? Is there another library that implements this?
[ "There is indeed such a mechanism in Lwt, called implicit callback argument, see Documentation. It is considered deprecated, because it is too easy to make mistakes with it, but sometimes this is really useful for some things like logging for instance.\nSuch a mechanism can't be implemented by a library outside of Lwt, this needs to be handled in some way by the scheduler.\n" ]
[ 0 ]
[]
[]
[ "lwt", "ocaml" ]
stackoverflow_0074617394_lwt_ocaml.txt
Q: python -m build fails due to syntax error in `long_description` I am failing to get my README.rst file to be working for my long_description within the pyproject.toml file. I am unclear why (advice appreciated, thank you). I have a pyproject.toml file: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "growbuddies" version = "2022.12.0" readme = "README.rst" description = "Buddies to help maximize the growth of plants in your indoor garden." dependencies = [ "influxdb ~=5.3.1", "paho_mqtt ~=1.6.1", ] [project.urls] "Homepage" = "https://github.com/solarslurpi/GrowBuddies" [project.scripts] get-readings = "growbuddies.__main__:main" The [project] tables notes readme = "README.RST". At the same directory level as pyproject.toml, I have an EMPTY README.rst file. I run $ twine check dist/* and get: Checking dist/growbuddies-2022.11.28-py3-none-any.whl: FAILED ERROR `long_description` has syntax errors in markup and would not be rendered on PyPI. No content rendered from RST source. WARNING `long_description_content_type` missing. defaulting to `text/x-rst`. Checking dist/growbuddies-2022.12.0-py3-none-any.whl: FAILED ERROR `long_description` has syntax errors in markup and would not be rendered on PyPI. No content rendered from RST source. Checking dist/growbuddies-2022.11.28.tar.gz: PASSED with warnings WARNING `long_description_content_type` missing. defaulting to `text/x-rst`. WARNING `long_description` missing. Checking dist/growbuddies-2022.12.0.tar.gz: PASSED with warnings WARNING `long_description` missing.
python -m build fails due to syntax error in `long_description`
I am failing to get my README.rst file to be working for my long_description within the pyproject.toml file. I am unclear why (advice appreciated, thank you). I have a pyproject.toml file: [build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "growbuddies" version = "2022.12.0" readme = "README.rst" description = "Buddies to help maximize the growth of plants in your indoor garden." dependencies = [ "influxdb ~=5.3.1", "paho_mqtt ~=1.6.1", ] [project.urls] "Homepage" = "https://github.com/solarslurpi/GrowBuddies" [project.scripts] get-readings = "growbuddies.__main__:main" The [project] tables notes readme = "README.RST". At the same directory level as pyproject.toml, I have an EMPTY README.rst file. I run $ twine check dist/* and get: Checking dist/growbuddies-2022.11.28-py3-none-any.whl: FAILED ERROR `long_description` has syntax errors in markup and would not be rendered on PyPI. No content rendered from RST source. WARNING `long_description_content_type` missing. defaulting to `text/x-rst`. Checking dist/growbuddies-2022.12.0-py3-none-any.whl: FAILED ERROR `long_description` has syntax errors in markup and would not be rendered on PyPI. No content rendered from RST source. Checking dist/growbuddies-2022.11.28.tar.gz: PASSED with warnings WARNING `long_description_content_type` missing. defaulting to `text/x-rst`. WARNING `long_description` missing. Checking dist/growbuddies-2022.12.0.tar.gz: PASSED with warnings WARNING `long_description` missing.
[]
[]
[ "I changed to README.md for some reason, this worked.\n" ]
[ -1 ]
[ "pyproject.toml", "python", "restructuredtext" ]
stackoverflow_0074678194_pyproject.toml_python_restructuredtext.txt
Q: Unity Models Import Without Color When I try to import a model into Unity, the colors aren't imported with the model. I've attached pictures to show what is happening.Model Model When Imported In Unity I tried using different modeling programs and I expected the model to import with the correct colors but everything in the model was only one color. A: When you import a model, you get a folder called "Material". In that folder you should find the material your model is using. That folder however is empty cause the texture is not in your project. Try import your model texture and once its imported apply that texture to the model.
Unity Models Import Without Color
When I try to import a model into Unity, the colors aren't imported with the model. I've attached pictures to show what is happening.Model Model When Imported In Unity I tried using different modeling programs and I expected the model to import with the correct colors but everything in the model was only one color.
[ "When you import a model, you get a folder called \"Material\". In that folder you should find the material your model is using. That folder however is empty cause the texture is not in your project.\nTry import your model texture and once its imported apply that texture to the model.\n" ]
[ 0 ]
[]
[]
[ "unity3d" ]
stackoverflow_0074680654_unity3d.txt
Q: Center image if other image is not visible I'm trying to make simple UI in html. If one div is not visible, other should be centered to other div, it doesn't happend. if all is showned if 2 of divs are not visible my css and html: .playerStats{ position: absolute; bottom: 2px; left: 50%; transform: translate(-50%, -50%); } .hud { width: 300px; left: -15px; /* potrzebne */ display: flex; position: relative; justify-content: space-between; transition: all 1s ease; } .stat { border-radius: 50%; max-height: fit-content; max-width: fit-content; position: relative; overflow: hidden; padding: 2rem; background: rgb(20, 20, 20, 0.3); box-shadow: 0px 0px 15px rgb(0, 0, 0); transition: all 1s ease; transition: visibility 0.2s; transition: opacity 0.2s; } .hud .stat img { width: 50%; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); transition: all 1s ease; transition: visibility 0.2s; transition: opacity 0.2s; } .hud .stat .bg { height: 100%; width: 100%; left: 0; position: absolute; bottom: 0; box-shadow: 15px 15px 15px 15px rgb(115, 0, 230); transition: all 1s ease; transition: visibility 0.2s; transition: opacity 0.2s; } <body> <div class="playerStats"> <div class="hud"> <div class="stat" id="hp-stat"> <div class="bg" id="hp" style="background-color: rgb(115, 0, 230)"></div> <img src="res/hp.png"> </div> <div class="stat" id="panc-stat"> <div class="bg" id="panc" style="background-color: rgb(115, 0, 230)"></div> <img src="res/panc.png"> </div> <div class="stat" id="pluca-stat"> <div class="bg" id="pluca" style="background-color: rgb(115, 0, 230)"></div> <img src="res/pluca.png"> </div> <div class="stat" id="glos-stat"> <div class="bg" id="glos" style="background-color: rgb(115, 0, 230)"></div> <img src="res/glossredni.png"> </div> </div> </div> </body> I tried do something with overflow, but nothing works for me. Changing position from relative to other, makes weird things. as you can see, it doesn't center. idk much of centering stuff in css, so i'm writing it here xD A: There is nothing wrong with your markup or styling; when setting visibility: none, your element isn't removed from the normal document flow. The element is still there, just invisible. Try display: none instead.
Center image if other image is not visible
I'm trying to make simple UI in html. If one div is not visible, other should be centered to other div, it doesn't happend. if all is showned if 2 of divs are not visible my css and html: .playerStats{ position: absolute; bottom: 2px; left: 50%; transform: translate(-50%, -50%); } .hud { width: 300px; left: -15px; /* potrzebne */ display: flex; position: relative; justify-content: space-between; transition: all 1s ease; } .stat { border-radius: 50%; max-height: fit-content; max-width: fit-content; position: relative; overflow: hidden; padding: 2rem; background: rgb(20, 20, 20, 0.3); box-shadow: 0px 0px 15px rgb(0, 0, 0); transition: all 1s ease; transition: visibility 0.2s; transition: opacity 0.2s; } .hud .stat img { width: 50%; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); transition: all 1s ease; transition: visibility 0.2s; transition: opacity 0.2s; } .hud .stat .bg { height: 100%; width: 100%; left: 0; position: absolute; bottom: 0; box-shadow: 15px 15px 15px 15px rgb(115, 0, 230); transition: all 1s ease; transition: visibility 0.2s; transition: opacity 0.2s; } <body> <div class="playerStats"> <div class="hud"> <div class="stat" id="hp-stat"> <div class="bg" id="hp" style="background-color: rgb(115, 0, 230)"></div> <img src="res/hp.png"> </div> <div class="stat" id="panc-stat"> <div class="bg" id="panc" style="background-color: rgb(115, 0, 230)"></div> <img src="res/panc.png"> </div> <div class="stat" id="pluca-stat"> <div class="bg" id="pluca" style="background-color: rgb(115, 0, 230)"></div> <img src="res/pluca.png"> </div> <div class="stat" id="glos-stat"> <div class="bg" id="glos" style="background-color: rgb(115, 0, 230)"></div> <img src="res/glossredni.png"> </div> </div> </div> </body> I tried do something with overflow, but nothing works for me. Changing position from relative to other, makes weird things. as you can see, it doesn't center. idk much of centering stuff in css, so i'm writing it here xD
[ "There is nothing wrong with your markup or styling; when setting visibility: none, your element isn't removed from the normal document flow. The element is still there, just invisible. Try display: none instead.\n" ]
[ 2 ]
[]
[]
[ "center", "css", "html", "visible" ]
stackoverflow_0074680540_center_css_html_visible.txt
Q: How to assign a jest mock function to a function within a React component? I'm trying to write a test using jest for my login component. How can I test that the handleLogin function is called on clicking the 'log in' button in the form, when the handLogin function is not passed to the Login component as a prop? This is the code I currently have but I'm unsure how to assign the mockHandler to the handleLogin function. Login.js : const Login = () => { const [userName, setUserName] = useState('') const [password, setPassword] = useState('') const handleLogin = (event) => { event.preventDefault() try { loginService.login({userName, password}) setUserName('') setPassword('') } catch (exception) { // ... } } return ( <div> Log in <form onSubmit = {handleLogin}> <div> User name <input type="text" value={userName} autoComplete="on" onChange = {({target}) => setUserName(target.value)} /> </div> <div> Password <input type="password" value={password} autoComplete="on" onChange = {({target}) => setPassword(target.value)} /> </div> <button type="submit">log in</button> <div> forgot password </div> </form> </div> ) } export default Login Login.test.js : import React from 'react' import '@testing-library/jest-dom/extend-expect' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import Login from './Login' test('clicking button calls event handler once', () => { const mockHandler = jest.fn() render( <Login handleLogin={mockHandler}/> ) const user = userEvent.setup() const button = screen.getByText('log in') user.click(button) expect(mockHandler.mock.calls).toHaveLength(1) }) But as the handleLogin is not passed as props this doesn't work. Thanks. A: For testing that a function was called by clicking a button describe('button field element methods', () => { it('should trigger onClick function', async () => { await act(async () => { const onClick = jest.fn();//this is your mock function const { container } = render(<Button onClick={onClick} />); const vdsTag = container.querySelector('button'); fireEvent.click(vdsTag); // this is how you programtically click a button expect(onClick).toBeCalled(); // this is how you expect a function to be called }); }); }); So maybe change your code to: // import service mock function here // e.g. import {loginService} from './service'; const loginSpy = jest.spyOn(loginService , 'login'); const customTag=render(<Login />) const button = customTag.querySelector('button') fireEvent.click(button); expect(loginSpy).toBeCalled(); // You can also inject user name and pass, and make sure the spy is called with these values
How to assign a jest mock function to a function within a React component?
I'm trying to write a test using jest for my login component. How can I test that the handleLogin function is called on clicking the 'log in' button in the form, when the handLogin function is not passed to the Login component as a prop? This is the code I currently have but I'm unsure how to assign the mockHandler to the handleLogin function. Login.js : const Login = () => { const [userName, setUserName] = useState('') const [password, setPassword] = useState('') const handleLogin = (event) => { event.preventDefault() try { loginService.login({userName, password}) setUserName('') setPassword('') } catch (exception) { // ... } } return ( <div> Log in <form onSubmit = {handleLogin}> <div> User name <input type="text" value={userName} autoComplete="on" onChange = {({target}) => setUserName(target.value)} /> </div> <div> Password <input type="password" value={password} autoComplete="on" onChange = {({target}) => setPassword(target.value)} /> </div> <button type="submit">log in</button> <div> forgot password </div> </form> </div> ) } export default Login Login.test.js : import React from 'react' import '@testing-library/jest-dom/extend-expect' import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import Login from './Login' test('clicking button calls event handler once', () => { const mockHandler = jest.fn() render( <Login handleLogin={mockHandler}/> ) const user = userEvent.setup() const button = screen.getByText('log in') user.click(button) expect(mockHandler.mock.calls).toHaveLength(1) }) But as the handleLogin is not passed as props this doesn't work. Thanks.
[ "For testing that a function was called by clicking a button\n describe('button field element methods', () => {\nit('should trigger onClick function', async () => {\n await act(async () => {\n const onClick = jest.fn();//this is your mock function\n const { container } = render(<Button onClick={onClick} />);\n const vdsTag = container.querySelector('button');\n fireEvent.click(vdsTag); // this is how you programtically click a button\n expect(onClick).toBeCalled(); // this is how you expect a function to be called\n });\n });\n});\n\nSo maybe change your code to:\n // import service mock function here\n // e.g. import {loginService} from './service';\n const loginSpy = jest.spyOn(loginService , 'login');\n const customTag=render(<Login />)\n const button = customTag.querySelector('button')\n fireEvent.click(button);\n expect(loginSpy).toBeCalled();\n // You can also inject user name and pass, and make sure the spy \n is called with these values\n\n" ]
[ 0 ]
[ "I think you will find the answer in this : https://www.danywalls.com/how-to-mock-dependencies-with-jest\n" ]
[ -2 ]
[ "jestjs", "reactjs", "unit_testing" ]
stackoverflow_0072900904_jestjs_reactjs_unit_testing.txt
Q: Export Data from CloudKit I am interacting with the cloudkit dashboard and looking at data collected by my app. How can I export all the data from the dashboard (data-> csv or json) so that I can do some analytics on it? Thanks! A: I don't think Apple will ever provide an export feature. The system is capable to collecting more than 40 events per second. This could very quickly be massive amount of data. Instead there is a possibility to query the system via an API, so you can build an external website to query your results and possibly export your data from there. A: Here is how I export my iCloud data on my Mac using this wonderful DB browser called DB Browser for SQLite. I run my app on Simulator. The app syncs with iCloud and downloads both public and private databases. Once the sync is complete I have all the data on my simulator. The data is essentially in SQlite format stored in a file which I locate using command in my app: print("\(NSHomeDirectory())/Library/Application Support/") and the result is something like: /Users/zeeshan/Library/Developer/CoreSimulator/Devices/34A4ADC6-1B67-4339-B67F-C4B6DDA46B07/data/Containers/Data/Application/E8F9486B-B40B-47D0-84C1-1043241E68EA/Library/Application Support/ And here .sqlite file is saved. In my case I have two files, private.sqlie and public.sqlite which is how I have named them in my code. Now I open these files in DB Browser for SQLite. And then rest is simple, just export the opened file as you would do for any SQlite file. Attached are the screenshots.
Export Data from CloudKit
I am interacting with the cloudkit dashboard and looking at data collected by my app. How can I export all the data from the dashboard (data-> csv or json) so that I can do some analytics on it? Thanks!
[ "I don't think Apple will ever provide an export feature.\nThe system is capable to collecting more than 40 events per second. This could very quickly be massive amount of data.\nInstead there is a possibility to query the system via an API, so you can build an external website to query your results and possibly export your data from there.\n", "Here is how I export my iCloud data on my Mac using this wonderful DB browser called DB Browser for SQLite.\nI run my app on Simulator. The app syncs with iCloud and downloads both public and private databases. Once the sync is complete I have all the data on my simulator. The data is essentially in SQlite format stored in a file which I locate using command in my app:\nprint(\"\\(NSHomeDirectory())/Library/Application Support/\")\nand the result is something like:\n/Users/zeeshan/Library/Developer/CoreSimulator/Devices/34A4ADC6-1B67-4339-B67F-C4B6DDA46B07/data/Containers/Data/Application/E8F9486B-B40B-47D0-84C1-1043241E68EA/Library/Application Support/\nAnd here .sqlite file is saved. In my case I have two files, private.sqlie and public.sqlite which is how I have named them in my code.\nNow I open these files in DB Browser for SQLite. And then rest is simple, just export the opened file as you would do for any SQlite file.\nAttached are the screenshots.\n\n\n\n\n\n" ]
[ 2, 0 ]
[]
[]
[ "cloudkit", "cloudkit_web_services" ]
stackoverflow_0038616397_cloudkit_cloudkit_web_services.txt
Q: Nested loop to take input 5 times and display total and average hoursWorked = 0 researchAssistants = 3 for assisstant in range(researchAssistants): for day in range(5): if day == 0: hoursWorked += float(input("Enter hours for research assistant {0} for Day 1: ".format(assisstant+1))) if day == 1: hoursWorked += float(input("Enter hours for research assistant {0} for Day 2: ".format(assisstant+1))) if day == 2: hoursWorked += float(input("Enter hours for research assistant {0} for Day 3: ".format(assisstant+1))) if day == 3: hoursWorked += float(input("Enter hours for research assistant {0} for Day 4: ".format(assisstant+1))) if day == 4: hoursWorked += float(input("Enter hours for research assistant {0} for Day 5: ".format(assisstant+1))) print() print("Research assistant {0} worked in total".format(assisstant+1), hoursWorked, "hours") avgHoursWorked = hoursWorked / 5 if avgHoursWorked > 6: print("Research assistant {0} has an average number of hours per day above 6".format(assisstant+1) ) print() I want the code to take amount of hours worked per day in a 5-day work week for three employees. I then want it to summarize it to hours/week for each employee. If an employee's average number of hours per day is above 6, the program should flag this. So far I the program takes the input, and gives the total. But the average is wrong. I believe avgHoursWorked should be in the nested for loop - but this does not really work for me. I would rather want the input to be taken first, then display the totals and flag an avg. >6 at the end. Edit: Here is the output as per above code. Enter hours for research assistant 1 for Day 1: 5 Enter hours for research assistant 1 for Day 2: 5 Enter hours for research assistant 1 for Day 3: 5 Enter hours for research assistant 1 for Day 4: 5 Enter hours for research assistant 1 for Day 5: 5 Research assistant 1 worked in total 25.0 hours Enter hours for research assistant 2 for Day 1: 5 Enter hours for research assistant 2 for Day 2: 5 Enter hours for research assistant 2 for Day 3: 5 Enter hours for research assistant 2 for Day 4: 5 Enter hours for research assistant 2 for Day 5: 5 Research assistant 2 worked in total 50.0 hours Research assistant 2 has an average number of hours per day above 6 Enter hours for research assistant 3 for Day 1: 5 Enter hours for research assistant 3 for Day 2: 5 Enter hours for research assistant 3 for Day 3: 5 Enter hours for research assistant 3 for Day 4: 5 Enter hours for research assistant 3 for Day 5: 5 Research assistant 3 worked in total 75.0 hours Research assistant 3 has an average number of hours per day above 6 In this case, the hours worked are being added-up where they should really be per individual Research Assistant A: It sounds like you meant to reset hoursWorked for each assistant: researchAssistants = 3 for assisstant in range(researchAssistants): hoursWorked = 0 for day in range(5): ...
Nested loop to take input 5 times and display total and average
hoursWorked = 0 researchAssistants = 3 for assisstant in range(researchAssistants): for day in range(5): if day == 0: hoursWorked += float(input("Enter hours for research assistant {0} for Day 1: ".format(assisstant+1))) if day == 1: hoursWorked += float(input("Enter hours for research assistant {0} for Day 2: ".format(assisstant+1))) if day == 2: hoursWorked += float(input("Enter hours for research assistant {0} for Day 3: ".format(assisstant+1))) if day == 3: hoursWorked += float(input("Enter hours for research assistant {0} for Day 4: ".format(assisstant+1))) if day == 4: hoursWorked += float(input("Enter hours for research assistant {0} for Day 5: ".format(assisstant+1))) print() print("Research assistant {0} worked in total".format(assisstant+1), hoursWorked, "hours") avgHoursWorked = hoursWorked / 5 if avgHoursWorked > 6: print("Research assistant {0} has an average number of hours per day above 6".format(assisstant+1) ) print() I want the code to take amount of hours worked per day in a 5-day work week for three employees. I then want it to summarize it to hours/week for each employee. If an employee's average number of hours per day is above 6, the program should flag this. So far I the program takes the input, and gives the total. But the average is wrong. I believe avgHoursWorked should be in the nested for loop - but this does not really work for me. I would rather want the input to be taken first, then display the totals and flag an avg. >6 at the end. Edit: Here is the output as per above code. Enter hours for research assistant 1 for Day 1: 5 Enter hours for research assistant 1 for Day 2: 5 Enter hours for research assistant 1 for Day 3: 5 Enter hours for research assistant 1 for Day 4: 5 Enter hours for research assistant 1 for Day 5: 5 Research assistant 1 worked in total 25.0 hours Enter hours for research assistant 2 for Day 1: 5 Enter hours for research assistant 2 for Day 2: 5 Enter hours for research assistant 2 for Day 3: 5 Enter hours for research assistant 2 for Day 4: 5 Enter hours for research assistant 2 for Day 5: 5 Research assistant 2 worked in total 50.0 hours Research assistant 2 has an average number of hours per day above 6 Enter hours for research assistant 3 for Day 1: 5 Enter hours for research assistant 3 for Day 2: 5 Enter hours for research assistant 3 for Day 3: 5 Enter hours for research assistant 3 for Day 4: 5 Enter hours for research assistant 3 for Day 5: 5 Research assistant 3 worked in total 75.0 hours Research assistant 3 has an average number of hours per day above 6 In this case, the hours worked are being added-up where they should really be per individual Research Assistant
[ "It sounds like you meant to reset hoursWorked for each assistant:\nresearchAssistants = 3\n \nfor assisstant in range(researchAssistants):\n hoursWorked = 0\n for day in range(5):\n ...\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074680621_python.txt
Q: Is it valid to share unix socket files across (docker) containers in general? I'm having the issue (which seems to be common) that I'm dockerizing applications that run on one machine, and these applications, now, need to run in different containers (because that's the docker paradigm and how things should be done). Currently I'm having issues with postfix and dovecot... people have found this too painful that there are tons of containers running both dovecot and postfix in one container, and I'm doing my best to do this right, but the lack of inet protocol examples (over tcp) is just too painful to continue with this. Leave alone bad logging and things that just don't work. I digress. The question Is it correct to have shared docker volumes that have socket files shared across different containers, and expect them to communicate correctly? Are there limitations that I have to be aware of? Bonus: Out of curiosity, can this be extended to virtual machines? A: It is generally not recommended to share socket files across different Docker containers, as this can lead to issues with communication and synchronization between the containers. Each Docker container runs in its own isolated environment, and as such, it is not guaranteed that two containers will be able to communicate with each other using socket files. This is because the socket files are specific to each container and are not shared between them. If you need to communicate between two containers, it is better to use the built-in networking capabilities of Docker, such as network bridges or overlay networks. This will allow the containers to communicate with each other using the network, rather than relying on shared socket files. Regarding your curiosity about extending this to virtual machines, it is also not recommended to share socket files between different virtual machines. Each virtual machine runs in its own isolated environment, just like Docker containers, and as such, communication between virtual machines should also be done using networking capabilities. In summary, it is not recommended to share socket files between different Docker containers or virtual machines, as this can lead to communication issues. Instead, use the built-in networking capabilities of Docker or your virtualization software to enable communication between containers or virtual machines. A: A Unix socket can't cross VM or physical-host boundaries. If you're thinking about ever deploying this setup in a multi-host setup like Kubernetes, Docker Swarm, or even just having containers running on multiple hosts, you'll need to use some TCP-based setup instead. (Sharing files in these environments is tricky; sharing a Unix socket actually won't work.) If you're using Docker Desktop, also remember that runs a hidden Linux virtual machine, even on native Linux. That may limit your options. There are other setups that more directly use a VM; my day-to-day Docker turns out to be Minikube, for example, which runs a single-node Kubernetes cluster with a Docker daemon in a VM. I'd expect sharing a Unix socket to work only if the two containers are on the same physical system, and inside the same VM if appropriate, and with the same storage mounted into both (not necessarily in the same place). I'd expect putting the socket on a named Docker volume mounted into both containers to work. I'd probably expect a bind-mounted host directory to work only on a native Linux system not running Docker Desktop.
Is it valid to share unix socket files across (docker) containers in general?
I'm having the issue (which seems to be common) that I'm dockerizing applications that run on one machine, and these applications, now, need to run in different containers (because that's the docker paradigm and how things should be done). Currently I'm having issues with postfix and dovecot... people have found this too painful that there are tons of containers running both dovecot and postfix in one container, and I'm doing my best to do this right, but the lack of inet protocol examples (over tcp) is just too painful to continue with this. Leave alone bad logging and things that just don't work. I digress. The question Is it correct to have shared docker volumes that have socket files shared across different containers, and expect them to communicate correctly? Are there limitations that I have to be aware of? Bonus: Out of curiosity, can this be extended to virtual machines?
[ "It is generally not recommended to share socket files across different Docker containers, as this can lead to issues with communication and synchronization between the containers.\nEach Docker container runs in its own isolated environment, and as such, it is not guaranteed that two containers will be able to communicate with each other using socket files. This is because the socket files are specific to each container and are not shared between them.\nIf you need to communicate between two containers, it is better to use the built-in networking capabilities of Docker, such as network bridges or overlay networks. This will allow the containers to communicate with each other using the network, rather than relying on shared socket files.\nRegarding your curiosity about extending this to virtual machines, it is also not recommended to share socket files between different virtual machines. Each virtual machine runs in its own isolated environment, just like Docker containers, and as such, communication between virtual machines should also be done using networking capabilities.\nIn summary, it is not recommended to share socket files between different Docker containers or virtual machines, as this can lead to communication issues. Instead, use the built-in networking capabilities of Docker or your virtualization software to enable communication between containers or virtual machines.\n", "A Unix socket can't cross VM or physical-host boundaries. If you're thinking about ever deploying this setup in a multi-host setup like Kubernetes, Docker Swarm, or even just having containers running on multiple hosts, you'll need to use some TCP-based setup instead. (Sharing files in these environments is tricky; sharing a Unix socket actually won't work.)\nIf you're using Docker Desktop, also remember that runs a hidden Linux virtual machine, even on native Linux. That may limit your options. There are other setups that more directly use a VM; my day-to-day Docker turns out to be Minikube, for example, which runs a single-node Kubernetes cluster with a Docker daemon in a VM.\nI'd expect sharing a Unix socket to work only if the two containers are on the same physical system, and inside the same VM if appropriate, and with the same storage mounted into both (not necessarily in the same place). I'd expect putting the socket on a named Docker volume mounted into both containers to work. I'd probably expect a bind-mounted host directory to work only on a native Linux system not running Docker Desktop.\n" ]
[ 0, 0 ]
[]
[]
[ "containers", "docker", "linux", "sockets", "unix" ]
stackoverflow_0074677851_containers_docker_linux_sockets_unix.txt
Q: For Loop issues w examples this is apart of a larger problem, but I can't get the iteration portion to work. Why is it not running through the loop 100 times? reps <- 100 for(iters in 1:reps){ #create data y_1J <- sum(mu_1 + error_1) y_2J <- sum(mu_2 + error_1) y_3J <- sum(mu_3 + error_1) y_bar <- mean(y_1J + y_2J + y_3J) error <- rnorm(n, 0, sigma) YiJ <- y_bar + alpha_0 + error df1 <- data.frame(YiJ = YiJ, n = factor(n) } I also need it to run through different mu/n values, but I can't get the initial part to work so I figure there is something wrong w my looping???? A: You're missing a close ) bracket at the end of the loop. Additionally, it looks like you're trying to create a data frame inside the for loop. This means that each iteration of the loop will create a new data frame with the same name, overwriting the previous one. Instead, you could create an empty data frame outside the loop and append the new rows to it each iteration.
For Loop issues w examples
this is apart of a larger problem, but I can't get the iteration portion to work. Why is it not running through the loop 100 times? reps <- 100 for(iters in 1:reps){ #create data y_1J <- sum(mu_1 + error_1) y_2J <- sum(mu_2 + error_1) y_3J <- sum(mu_3 + error_1) y_bar <- mean(y_1J + y_2J + y_3J) error <- rnorm(n, 0, sigma) YiJ <- y_bar + alpha_0 + error df1 <- data.frame(YiJ = YiJ, n = factor(n) } I also need it to run through different mu/n values, but I can't get the initial part to work so I figure there is something wrong w my looping????
[ "You're missing a close ) bracket at the end of the loop.\nAdditionally, it looks like you're trying to create a data frame inside the for loop. This means that each iteration of the loop will create a new data frame with the same name, overwriting the previous one. Instead, you could create an empty data frame outside the loop and append the new rows to it each iteration.\n" ]
[ 2 ]
[]
[]
[ "r" ]
stackoverflow_0074680684_r.txt
Q: How to check if there is newLine YASM 8086 I've been working on the project. The main goal is to calculate how many words do not contain letters from 'a' to 'k'. Given file has [0;1000] lines. Every line contains 6 columns. The first two columns contain string with [1; 20] characters. Characters could be letters, numbers, and whitespaces. 3-5 columns contain integers in the range [-100; 100]. 6th column contains real numbers in the range [-9.99; 9.99] with only two digits after the decimal point. Each section I separated by a semicolon ';'. helloA;lB;lC;lD;lE;lF A11;bas morning;0;0;5;1.15 My problem is, that if there is a newLine at the end of the file, skip them, and sum up them in the final count. TASK: calculate how many words (the word is one or more symbols without ' '(space)) in the first two columns do not contain letters 'B' or 'C'. And print that integer number. I have tried to compare al with 0x20 and jump to the next section if it is smaller, but that didn't help me. What I have done so far ; Main .whileNotTheEndOfFile: mov si, 2 call procSkaitytiEilute ; Check the first two columns ;mov al, ';' mov di, line .skipSpaces: mov al, [di] inc di cmp al, ' ' je .skipSpaces cmp al, ';' je .q3 dec di .checkWord: mov bx, 1 .q1: mov al, [di] inc di cmp al, ' ' je .q2 cmp al, ';' je .q2 jmp .q8 .q8: cmp al, 20h jl .skipLine jmp .q7 .q7: cmp al, 'A' jl .q5 jmp .q4 .q4: cmp al, 'K' jae .q5 mov bx, 0 ; One or more invalid chars in current word jmp .q1 .q5: cmp al, 'a' jae .q6 jmp .q1 .q6: cmp al, 'k' jae .q1 mov bx, 0 jmp .q1 .q2: add [lineCount], bx ; BX=[0,1] Counting the 'good' words cmp al, ';' jne .skipSpaces .q3: dec si ; Next column? jnz .skipSpaces .skipLine: cmp [readLastLine], byte 0 je .whileNotTheEndOfFile ; Jeigu ne failo pabaiga, kartojame cikla .skipLine: sub [lineCount], 2 cmp [readLastLine], byte 0 je .whileNotTheEndOfFile ; Hexadecimal convertion to decimal mov dx, lineCount mov ax, [lineCount] call procUInt16ToStr call procPutStr macNewLine mov si, dx .writeToFile: lodsb cmp al, 0 jne .writeToFile sub si, dx lea cx, [si-1] mov bx, [writingDescriptor] mov ah, 40h int 21h ; Closing Files .end: mov bx, [writingDescriptor] call procFClose .rasymoKlaida: mov bx, [readingDescriptor] call procFClose exit %include 'yasmlib.asm' ; void procSkaitytiEilute() ; Read line to buffer ‘eilute’ procReadLine: push ax push bx push cx push si mov bx, [readingDescriptor] mov si, 0 .loop: call procFGetChar ; End if the end of file or error cmp ax, 0 je .endOfFile jc .endOfFile ; Putting symbol to buffer mov [line+si], cl inc si ; Check if there is \n? cmp cl, 0x0A je .endOfLine jmp .loop .endOfFile: mov [readLastLine], byte 1 .endOfLine: mov [line+si], byte '$' mov [lineLength], si pop si pop cx pop bx pop ax ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; section .data readingFile: db 'input.dat', 00 readingDescriptor: dw 0000 writingFile: times 128 db 00 writingDescriptor: dw 0000 readLastLine: db 00 line: db 64 times 66 db '$' lineLength: dw 0000 lineCount: times 128 db 00 **My file: ** XYZ;PPP;1;1;1;1.00 A11;bas aaa;0;0;5;1.15 My output: 4 Needed output: 2 (because good there are only 2 "good" words "XYZ" and "PPP"), my program counts 2 more words in newLine. A: It would appear that in contrast with the original task description your file can contain one or more empty lines as well. To deal with these empty lines (only containing the bytes 13 and 10), your idea to skip on codes below 32 is good, but it's in the wrong place. Below is the quick fix. Please notice that the ASCII codes are to be treated as unsigned numbers. Don't use the signed jl instruction on them. mov di, line mov al, [di] ; NEW cmp al, 32 ; NEW jb .skipLine ; NEW .skipSpaces: mov al, [di] inc di cmp al, ' ' je .skipSpaces cmp al, ';' je .q3 dec di .checkWord: mov bx, 1 .q1: mov al, [di] inc di cmp al, ' ' je .q2 cmp al, ';' je .q2 ! cmp al, 'A' ! jb .q1 ! cmp al, 'K' ! jbe .badChar ; [A,K] is bad ! cmp al, 'a' ! jb .q1 ! cmp al, 'k' ! ja .q1 ! .badChar: ; [a,k] is bad ! mov bx, 0 ; One or more invalid chars in current word jmp .q1 .q2: add [lineCount], bx ; BX=[0,1] Counting the 'good' words cmp al, ';' jne .skipSpaces .q3: dec si ; Next column? jnz .skipSpaces .skipLine: cmp [readLastLine], byte 0 je .whileNotTheEndOfFile The lines that I marked with an exclamation mark really should be: or al, 32 ; Make lowercase cmp al, 'a' jb .q1 cmp al, 'k' ja .q1 mov bx, 0 ; [A,K] and [a,k] are badChars Why does your program contain next redundant lines? ; Jeigu ne failo pabaiga, kartojame cikla .skipLine: sub [lineCount], 2 cmp [readLastLine], byte 0 je .whileNotTheEndOfFile
How to check if there is newLine YASM 8086
I've been working on the project. The main goal is to calculate how many words do not contain letters from 'a' to 'k'. Given file has [0;1000] lines. Every line contains 6 columns. The first two columns contain string with [1; 20] characters. Characters could be letters, numbers, and whitespaces. 3-5 columns contain integers in the range [-100; 100]. 6th column contains real numbers in the range [-9.99; 9.99] with only two digits after the decimal point. Each section I separated by a semicolon ';'. helloA;lB;lC;lD;lE;lF A11;bas morning;0;0;5;1.15 My problem is, that if there is a newLine at the end of the file, skip them, and sum up them in the final count. TASK: calculate how many words (the word is one or more symbols without ' '(space)) in the first two columns do not contain letters 'B' or 'C'. And print that integer number. I have tried to compare al with 0x20 and jump to the next section if it is smaller, but that didn't help me. What I have done so far ; Main .whileNotTheEndOfFile: mov si, 2 call procSkaitytiEilute ; Check the first two columns ;mov al, ';' mov di, line .skipSpaces: mov al, [di] inc di cmp al, ' ' je .skipSpaces cmp al, ';' je .q3 dec di .checkWord: mov bx, 1 .q1: mov al, [di] inc di cmp al, ' ' je .q2 cmp al, ';' je .q2 jmp .q8 .q8: cmp al, 20h jl .skipLine jmp .q7 .q7: cmp al, 'A' jl .q5 jmp .q4 .q4: cmp al, 'K' jae .q5 mov bx, 0 ; One or more invalid chars in current word jmp .q1 .q5: cmp al, 'a' jae .q6 jmp .q1 .q6: cmp al, 'k' jae .q1 mov bx, 0 jmp .q1 .q2: add [lineCount], bx ; BX=[0,1] Counting the 'good' words cmp al, ';' jne .skipSpaces .q3: dec si ; Next column? jnz .skipSpaces .skipLine: cmp [readLastLine], byte 0 je .whileNotTheEndOfFile ; Jeigu ne failo pabaiga, kartojame cikla .skipLine: sub [lineCount], 2 cmp [readLastLine], byte 0 je .whileNotTheEndOfFile ; Hexadecimal convertion to decimal mov dx, lineCount mov ax, [lineCount] call procUInt16ToStr call procPutStr macNewLine mov si, dx .writeToFile: lodsb cmp al, 0 jne .writeToFile sub si, dx lea cx, [si-1] mov bx, [writingDescriptor] mov ah, 40h int 21h ; Closing Files .end: mov bx, [writingDescriptor] call procFClose .rasymoKlaida: mov bx, [readingDescriptor] call procFClose exit %include 'yasmlib.asm' ; void procSkaitytiEilute() ; Read line to buffer ‘eilute’ procReadLine: push ax push bx push cx push si mov bx, [readingDescriptor] mov si, 0 .loop: call procFGetChar ; End if the end of file or error cmp ax, 0 je .endOfFile jc .endOfFile ; Putting symbol to buffer mov [line+si], cl inc si ; Check if there is \n? cmp cl, 0x0A je .endOfLine jmp .loop .endOfFile: mov [readLastLine], byte 1 .endOfLine: mov [line+si], byte '$' mov [lineLength], si pop si pop cx pop bx pop ax ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; section .data readingFile: db 'input.dat', 00 readingDescriptor: dw 0000 writingFile: times 128 db 00 writingDescriptor: dw 0000 readLastLine: db 00 line: db 64 times 66 db '$' lineLength: dw 0000 lineCount: times 128 db 00 **My file: ** XYZ;PPP;1;1;1;1.00 A11;bas aaa;0;0;5;1.15 My output: 4 Needed output: 2 (because good there are only 2 "good" words "XYZ" and "PPP"), my program counts 2 more words in newLine.
[ "It would appear that in contrast with the original task description your file can contain one or more empty lines as well.\nTo deal with these empty lines (only containing the bytes 13 and 10), your idea to skip on codes below 32 is good, but it's in the wrong place.\nBelow is the quick fix. Please notice that the ASCII codes are to be treated as unsigned numbers. Don't use the signed jl instruction on them.\n mov di, line\n mov al, [di] ; NEW\n cmp al, 32 ; NEW\n jb .skipLine ; NEW\n .skipSpaces:\n mov al, [di]\n inc di\n cmp al, ' '\n je .skipSpaces\n cmp al, ';'\n je .q3\n dec di\n .checkWord:\n mov bx, 1\n .q1:\n mov al, [di]\n inc di\n cmp al, ' '\n je .q2\n cmp al, ';'\n je .q2\n ! cmp al, 'A'\n ! jb .q1\n ! cmp al, 'K'\n ! jbe .badChar ; [A,K] is bad\n ! cmp al, 'a'\n ! jb .q1\n ! cmp al, 'k'\n ! ja .q1 \n ! .badChar: ; [a,k] is bad\n ! mov bx, 0 ; One or more invalid chars in current word\n jmp .q1\n .q2:\n add [lineCount], bx ; BX=[0,1] Counting the 'good' words\n cmp al, ';'\n jne .skipSpaces\n .q3:\n dec si ; Next column?\n jnz .skipSpaces\n .skipLine:\n cmp [readLastLine], byte 0\n je .whileNotTheEndOfFile\n\nThe lines that I marked with an exclamation mark really should be:\n or al, 32 ; Make lowercase\n cmp al, 'a'\n jb .q1\n cmp al, 'k'\n ja .q1\n mov bx, 0 ; [A,K] and [a,k] are badChars\n\nWhy does your program contain next redundant lines?\n\n ; Jeigu ne failo pabaiga, kartojame cikla\n .skipLine:\n sub [lineCount], 2\n cmp [readLastLine], byte 0\n je .whileNotTheEndOfFile\n\n\n" ]
[ 1 ]
[]
[]
[ "assembly", "string", "x86", "yasm" ]
stackoverflow_0074679234_assembly_string_x86_yasm.txt
Q: I want to use input::checked with :has but it doesn't work as you can see in my code i want to unhide span when input type checked is checked, but it doesnt work. Could you please help me? .share_div { width: 200px; height: 100px; left: 0.7rem; width: 50%; height: 100px; position: absolute; background-color: #aaa; border: 2px solid black; padding-inline: 10px; border-radius: 100vmax; } .share_div label { display: block; font-size: 0.85rem; color: black; margin-inline-start: 2rem; margin-block-start: 0.5rem; } #actuall_link { display: none; width: calc(100% - 5rem); height: 2.2rem; } #share_div:has(>input::checked) span { display: inline; } <div id="share_div" class="share_div"> <label for="checkbox_share">info</label> <input id="checkbox_share" type="checkbox"> <span id="actuall_link">unhide when checkbox is checked</span> </div> A: It's :checked, not ::checked. You're confusing pseduoelements with pseudoclasses. Also, you don't even need :has() in this case because the checkbox <input> is a preceding sibling of the <span>, so you only need #share_div > input[type=checkbox]:checked ~ span { } Solution 1: Using ~ (without :has()): .share_div { width: 200px; height: 100px; left: 0.7rem; width: 50%; height: 100px; position: absolute; background-color: #aaa; border: 2px solid black; padding-inline: 10px; border-radius: 100vmax; } .share_div label { display: block; font-size: 0.85rem; color: black; margin-inline-start: 2rem; margin-block-start: 0.5rem; } #actuall_link { display: none; width: calc(100% - 5rem); height: 2.2rem; } #share_div > input[type=checkbox]:checked ~ span { display: inline; } <div id="share_div" class="share_div"> <label for="checkbox_share">info</label> <input id="checkbox_share" type="checkbox"> <span id="actuall_link">unhide when checkbox is checked</span> </div> Solution 2: Using :has(): ...with display: revert;. .share_div { width: 200px; height: 100px; left: 0.7rem; width: 50%; height: 100px; position: absolute; background-color: #aaa; border: 2px solid black; padding-inline: 10px; border-radius: 100vmax; } .share_div label { display: block; font-size: 0.85rem; color: black; margin-inline-start: 2rem; margin-block-start: 0.5rem; } #actuall_link { display: none; width: calc(100% - 5rem); height: 2.2rem; } #share_div:has( > input[type=checkbox]:checked ) > span { display: revert; } <div id="share_div" class="share_div"> <label for="checkbox_share">info</label> <input id="checkbox_share" type="checkbox"> <span id="actuall_link">unhide when checkbox is checked</span> </div> A: I would also suggest: Remove the overly verbose attributes id and for. Wrap your elements into label Use the Adjacent sibling combinator + (or the General sibling combinator ~ if not an immediate next sibling) As already mentioned, it should be :checked, not a pseudo-element ::checked label .msg { display: none; } label input:checked + .msg { display: initial; } <label> info <input type="checkbox"> <span class="msg">Good job!</span> </label>
I want to use input::checked with :has but it doesn't work
as you can see in my code i want to unhide span when input type checked is checked, but it doesnt work. Could you please help me? .share_div { width: 200px; height: 100px; left: 0.7rem; width: 50%; height: 100px; position: absolute; background-color: #aaa; border: 2px solid black; padding-inline: 10px; border-radius: 100vmax; } .share_div label { display: block; font-size: 0.85rem; color: black; margin-inline-start: 2rem; margin-block-start: 0.5rem; } #actuall_link { display: none; width: calc(100% - 5rem); height: 2.2rem; } #share_div:has(>input::checked) span { display: inline; } <div id="share_div" class="share_div"> <label for="checkbox_share">info</label> <input id="checkbox_share" type="checkbox"> <span id="actuall_link">unhide when checkbox is checked</span> </div>
[ "It's :checked, not ::checked. You're confusing pseduoelements with pseudoclasses.\nAlso, you don't even need :has() in this case because the checkbox <input> is a preceding sibling of the <span>, so you only need #share_div > input[type=checkbox]:checked ~ span { }\n\nSolution 1: Using ~ (without :has()):\n\n\n.share_div {\n width: 200px;\n height: 100px;\n left: 0.7rem;\n width: 50%;\n height: 100px;\n position: absolute;\n background-color: #aaa;\n border: 2px solid black;\n padding-inline: 10px;\n border-radius: 100vmax;\n}\n\n.share_div label {\n display: block;\n font-size: 0.85rem;\n color: black;\n margin-inline-start: 2rem;\n margin-block-start: 0.5rem;\n}\n\n#actuall_link {\n display: none;\n width: calc(100% - 5rem);\n height: 2.2rem;\n}\n\n#share_div > input[type=checkbox]:checked ~ span {\n display: inline;\n}\n<div id=\"share_div\" class=\"share_div\">\n <label for=\"checkbox_share\">info</label>\n <input id=\"checkbox_share\" type=\"checkbox\">\n <span id=\"actuall_link\">unhide when checkbox is checked</span>\n</div>\n\n\n\nSolution 2: Using :has():\n...with display: revert;.\n\n\n.share_div {\n width: 200px;\n height: 100px;\n left: 0.7rem;\n width: 50%;\n height: 100px;\n position: absolute;\n background-color: #aaa;\n border: 2px solid black;\n padding-inline: 10px;\n border-radius: 100vmax;\n}\n\n.share_div label {\n display: block;\n font-size: 0.85rem;\n color: black;\n margin-inline-start: 2rem;\n margin-block-start: 0.5rem;\n}\n\n#actuall_link {\n display: none;\n width: calc(100% - 5rem);\n height: 2.2rem;\n}\n\n#share_div:has( > input[type=checkbox]:checked ) > span {\n display: revert;\n}\n<div id=\"share_div\" class=\"share_div\">\n <label for=\"checkbox_share\">info</label>\n <input id=\"checkbox_share\" type=\"checkbox\">\n <span id=\"actuall_link\">unhide when checkbox is checked</span>\n</div>\n\n\n\n", "I would also suggest:\n\nRemove the overly verbose attributes id and for.\nWrap your elements into label\nUse the Adjacent sibling combinator + (or the General sibling combinator ~ if not an immediate next sibling)\nAs already mentioned, it should be :checked, not a pseudo-element ::checked\n\n\n\nlabel .msg { display: none; }\nlabel input:checked + .msg { display: initial; }\n<label>\n info\n <input type=\"checkbox\">\n <span class=\"msg\">Good job!</span>\n</label>\n\n\n\n" ]
[ 1, 1 ]
[]
[]
[ "css", "html" ]
stackoverflow_0074680519_css_html.txt
Q: Compare and sort strings in String format using Comparator Task: Given array String[] dates = { "07-05-1990", "28-01-2010", "11-08-1990", "15-01-2010", "16-06-1970" }; I need to write Comparator that sorts this array in the following order: String[] expected = { "16-06-1970", "07-05-1990", "11-08-1990", "15-01-2010", "28-01-2010" }; I wrote this code but it is not working: import java.util.Comparator; public class DateSort implements Comparator<String>{ @Override public int compare(String str1, String str2) { if (str1.length() != 10 || str2.length() != 10) { throw new IllegalArgumentException("The string must be 10 characters long."); } Comparator<String> strComparator = Comparator.comparing(s -> s.substring(6, 9)) .thenComparing(s -> s.subtring(3, 5)) .thenComparing(s -> s.subtring(0, 2)); return strComparator; } } How can I fix this code in order to sort the given array according to the task? Condition: only Comparator must be used. Date and Time APIs cannot be used. We need to compare Strings in array using Comparator. We cannot parse String elements of the given array to Date. A: The problem with your code is that you are returning the Comparator object itself from the compare method. However, the compare method should return an int value that indicates whether the first string is less than, equal to, or greater than the second string. To do this, you need to use the compare method of the Comparator object that you have created. Here is how you can use your class to sort the given array: String[] dates = { "07-05-1990", "28-01-2010", "11-08-1990", "15-01-2010", "16-06-1970" }; Arrays.sort(dates, new DateSort()); After sorting, the dates array will be sorted in the order specified in the task.
Compare and sort strings in String format using Comparator
Task: Given array String[] dates = { "07-05-1990", "28-01-2010", "11-08-1990", "15-01-2010", "16-06-1970" }; I need to write Comparator that sorts this array in the following order: String[] expected = { "16-06-1970", "07-05-1990", "11-08-1990", "15-01-2010", "28-01-2010" }; I wrote this code but it is not working: import java.util.Comparator; public class DateSort implements Comparator<String>{ @Override public int compare(String str1, String str2) { if (str1.length() != 10 || str2.length() != 10) { throw new IllegalArgumentException("The string must be 10 characters long."); } Comparator<String> strComparator = Comparator.comparing(s -> s.substring(6, 9)) .thenComparing(s -> s.subtring(3, 5)) .thenComparing(s -> s.subtring(0, 2)); return strComparator; } } How can I fix this code in order to sort the given array according to the task? Condition: only Comparator must be used. Date and Time APIs cannot be used. We need to compare Strings in array using Comparator. We cannot parse String elements of the given array to Date.
[ "The problem with your code is that you are returning the Comparator object itself from the compare method. However, the compare method should return an int value that indicates whether the first string is less than, equal to, or greater than the second string. To do this, you need to use the compare method of the Comparator object that you have created.\nHere is how you can use your class to sort the given array:\nString[] dates = {\n \"07-05-1990\",\n \"28-01-2010\",\n \"11-08-1990\",\n \"15-01-2010\",\n \"16-06-1970\"\n};\n\nArrays.sort(dates, new DateSort());\n\nAfter sorting, the dates array will be sorted in the order specified in the task.\n" ]
[ 1 ]
[]
[]
[ "arrays", "comparator", "compare", "java", "string" ]
stackoverflow_0074680689_arrays_comparator_compare_java_string.txt
Q: Python - PRINT_ERRORS=0 or 1 I am new to python , I am executing a small code, I see below code written at the start of my code PRINT_ERRORS=0 if I run the code as it is, it works fine, however if I change the value to 1 if prints some errors, I want to understand what that line of code is doing there, can anyone help? I am not sure what should I expect from this line of code A: The line of code PRINT_ERRORS=0 is defining a variable called PRINT_ERRORS and setting its value to 0. This variable is likely being used later in the code to control whether or not error messages are printed during the execution of the code. For example, if the code contains a line like if PRINT_ERRORS: print(error_message), then setting PRINT_ERRORS to 0 will prevent the error message from being printed, while setting it to 1 will cause the error message to be printed. In general, this line of code is included in the code to give the user or developer the option to control whether or not error messages are printed during the execution of the code. This can be useful for debugging purposes, as it allows the user to see any error messages that may be generated while the code is running.
Python - PRINT_ERRORS=0 or 1
I am new to python , I am executing a small code, I see below code written at the start of my code PRINT_ERRORS=0 if I run the code as it is, it works fine, however if I change the value to 1 if prints some errors, I want to understand what that line of code is doing there, can anyone help? I am not sure what should I expect from this line of code
[ "The line of code PRINT_ERRORS=0 is defining a variable called PRINT_ERRORS and setting its value to 0. This variable is likely being used later in the code to control whether or not error messages are printed during the execution of the code.\nFor example, if the code contains a line like if PRINT_ERRORS: print(error_message), then setting PRINT_ERRORS to 0 will prevent the error message from being printed, while setting it to 1 will cause the error message to be printed.\nIn general, this line of code is included in the code to give the user or developer the option to control whether or not error messages are printed during the execution of the code. This can be useful for debugging purposes, as it allows the user to see any error messages that may be generated while the code is running.\n" ]
[ 1 ]
[]
[]
[ "exception", "nlp", "printing", "python", "sentiment_analysis" ]
stackoverflow_0074680695_exception_nlp_printing_python_sentiment_analysis.txt
Q: AJAX ModalPopupExtender & Gridview row values I've not really used the MPE before & currently have a need to, what I'm slightly confused about is losing reference to the initial control that triggers the function. I have a gridview with a dropdownlist and onselectedindexchanged set to call a function when a value has been selected, when processed one value i grab is the RowID into a variable, out of 9 list items only one requires the pop up (Ok = proceed & Cancel = Return) & when this is triggered I lose all reference to the given grid row which is referenced via; DropDownList ddlid = (DropDownList)sender; GridViewRow gvrow = (GridViewRow)ddlid.NamingContainer; RowID = (Int32.Parse(GridView1.DataKeys[gvrow.RowIndex].Values[0].ToString())); Can anyone shed any light or have an idea on how I can keep track of the gridview row? Thanks IchBinDicky A: One way to keep track of the gridview row would be to store the RowID value in a hidden field on the page, and then retrieve it in the function that is called by the Ok and Cancel buttons in the popup. Here is an example of how this could be implemented: First, add a hidden field to the page where the gridview is located, and set its Value attribute to the RowID value: <asp:HiddenField runat="server" id="hiddenRowID" value="<%= RowID %>" /> Then, in the function that is called by the Ok and Cancel buttons in the popup, retrieve the RowID value from the hidden field, like this: int rowID = int.Parse(hiddenRowID.Value); This way, you can access the RowID value in the function that is called by the Ok and Cancel buttons, even though the original context (i.e. the gridview row) is no longer available. Alternatively, you could also pass the RowID value as a parameter to the function that is called by the Ok and Cancel buttons, like this: functionName(RowID); // In the function that is called by the Ok and Cancel buttons: void functionName(int rowID) { // Use the rowID parameter here... } This would allow you to access the RowID value without using a hidden field.
AJAX ModalPopupExtender & Gridview row values
I've not really used the MPE before & currently have a need to, what I'm slightly confused about is losing reference to the initial control that triggers the function. I have a gridview with a dropdownlist and onselectedindexchanged set to call a function when a value has been selected, when processed one value i grab is the RowID into a variable, out of 9 list items only one requires the pop up (Ok = proceed & Cancel = Return) & when this is triggered I lose all reference to the given grid row which is referenced via; DropDownList ddlid = (DropDownList)sender; GridViewRow gvrow = (GridViewRow)ddlid.NamingContainer; RowID = (Int32.Parse(GridView1.DataKeys[gvrow.RowIndex].Values[0].ToString())); Can anyone shed any light or have an idea on how I can keep track of the gridview row? Thanks IchBinDicky
[ "One way to keep track of the gridview row would be to store the RowID value in a hidden field on the page, and then retrieve it in the function that is called by the Ok and Cancel buttons in the popup.\nHere is an example of how this could be implemented:\nFirst, add a hidden field to the page where the gridview is located, and set its Value attribute to the RowID value:\n<asp:HiddenField runat=\"server\" id=\"hiddenRowID\" value=\"<%= RowID %>\" />\nThen, in the function that is called by the Ok and Cancel buttons in the popup, retrieve the RowID value from the hidden field, like this:\n int rowID = int.Parse(hiddenRowID.Value);\nThis way, you can access the RowID value in the function that is called by the Ok and Cancel buttons, even though the original context (i.e. the gridview row) is no longer available.\nAlternatively, you could also pass the RowID value as a parameter to the function that is called by the Ok and Cancel buttons, like this:\n functionName(RowID);\n\n // In the function that is called by the Ok and Cancel buttons:\n void functionName(int rowID)\n {\n // Use the rowID parameter here...\n }\n\nThis would allow you to access the RowID value without using a hidden field.\n" ]
[ 0 ]
[]
[]
[ "ajaxcontroltoolkit", "asp.net", "c#" ]
stackoverflow_0074680327_ajaxcontroltoolkit_asp.net_c#.txt
Q: Keep String Formatted When Sending it via Email [PYTHON] I have a string when it's printed in my terminal, it looks the way I want, but when I use the variable to send it via email, it looses all its formatting. Is there anyway I can fix this? This is how it looks on the terminal This is how it looks on email This is how I am declaring and printing for the first image: ticket_medio = (faturamento['Valor Final'] / quantidade['Quantidade']).to_frame() print(ticket_medio) And this is how I am doing the formatted string that is being sent to the user: body_email = f'Segue o ticket médio deste mês:\n\n{ticket_medio}' A: To save a pandas dataframe named ticket_medio to a CSV file, you can use the to_csv method. Here is an example of how to do this: # Import the pandas library import pandas as pd # Save the dataframe to a CSV file ticket_medio.to_csv('ticket_medio.csv') This will create a CSV file named ticket_medio.csv in the current directory. The CSV file will contain the data from the ticket_medio dataframe. Once the CSV file has been created, you can attach it to an email and send it to the desired recipient. The recipient can then open the CSV file in a program like Microsoft Excel or Google Sheets to view the data. Alternatively, you can also specify a different file path to save the CSV file to a different location on your computer, or you can specify additional options to customize the way the data is saved to the CSV file. For more information, you can refer to the documentation for the to_csv method.
Keep String Formatted When Sending it via Email [PYTHON]
I have a string when it's printed in my terminal, it looks the way I want, but when I use the variable to send it via email, it looses all its formatting. Is there anyway I can fix this? This is how it looks on the terminal This is how it looks on email This is how I am declaring and printing for the first image: ticket_medio = (faturamento['Valor Final'] / quantidade['Quantidade']).to_frame() print(ticket_medio) And this is how I am doing the formatted string that is being sent to the user: body_email = f'Segue o ticket médio deste mês:\n\n{ticket_medio}'
[ "To save a pandas dataframe named ticket_medio to a CSV file, you can use the to_csv method. Here is an example of how to do this:\n# Import the pandas library\nimport pandas as pd\n\n# Save the dataframe to a CSV file\nticket_medio.to_csv('ticket_medio.csv')\n\nThis will create a CSV file named ticket_medio.csv in the current directory. The CSV file will contain the data from the ticket_medio dataframe.\nOnce the CSV file has been created, you can attach it to an email and send it to the desired recipient. The recipient can then open the CSV file in a program like Microsoft Excel or Google Sheets to view the data.\nAlternatively, you can also specify a different file path to save the CSV file to a different location on your computer, or you can specify additional options to customize the way the data is saved to the CSV file. For more information, you can refer to the documentation for the to_csv method.\n" ]
[ 0 ]
[ "You can use pandas.DataFrame.to_string.\n\nRender a DataFrame to a console-friendly tabular output.\n\nTry this :\nbody_email = '''Segue o ticket médio destemês:\\n\\n{}'''.format(ticket_medio.to_string())\n\n" ]
[ -1 ]
[ "dataframe", "email", "pandas", "python", "string" ]
stackoverflow_0074680645_dataframe_email_pandas_python_string.txt
Q: Why can't I use $_ in write-host? I am trying to pipe an array of strings to write-host and explicitly use $_ to write those strings: 'foo', 'bar', 'baz' | write-host $_ However, it fails with: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. This error message makes no sense to me because I am perfectly able to write 'foo', 'bar', 'baz' | write-host I would have expected both pipelines to be equivalent. Apparently, they're not. So, what's the difference? A: tl;dr The automatic $_ variable and its alias, $PSItem, only ever have meaningful values inside script blocks ({ ... }), in specific contexts. The bottom section lists all relevant contexts. I would have expected both pipelines to be equivalent. They're not: 'foo', 'bar', 'baz' | write-host It is the pipeline-based equivalent of the following (equivalent in ultimate effect, not technically): foreach ($str in 'foo', 'bar', 'baz') { Write-Host -Object $str } That is, in your command Write-Host receives input from the pipeline that implicitly binds to its -Object parameter for each input object, by virtue of parameter -Object being declared as accepting pipeline input via attribute [Parameter(ValueFromPipeline=$true)] 'foo', 'bar', 'baz' | write-host $_ Before pipeline processing begins, arguments - $_ in your case - are bound to parameters first: Since $_ isn't preceded by a parameter name, it binds positionally to the - implied - -Object parameter. Then, when pipeline processing begins, pipeline parameter binding finds no pipeline-binding Write-Host parameter to bind to anymore, given that the only such parameter, -Object has already been bound, namely by an argument $_. In other words: your command mistakenly tries to bind the -Object parameter twice; unfortunately, the error message doesn't exactly make that clear. The larger point is that using $_ only ever makes sense inside a script block ({ ... }) that is evaluated for each input object. Outside that context, $_ (or its alias, $PSItem) typically has no value and shouldn't be used - see the bottom section for an overview of all contexts in which $_ / $PSItem inside a script block is meaningfully supported. While $_ is most typically used in the script blocks passed to the ForEach-Object and Where-Object cmdlets, there are other useful applications, most typically seen with the Rename-Item cmdlet: a delay-bind script-block argument: # Example: rename *.txt files to *.dat files using a delay-bind script block: Get-ChildItem *.txt | Rename-Item -NewName { $_.BaseName + '.dat' } -WhatIf That is, instead of passing a static new name to Rename-Item, you pass a script block that is evaluated for each input object - with the input object bound to $_, as usual - which enables dynamic behavior. As explained in the linked answer, however, this technique only works with parameters that are both (a) pipeline-binding and (b) not [object] or [scriptblock] typed; therefore, given that Write-Object's -Object parameter is [object] typed, the technique does not work: # Try to enclose all inputs in [...] on output. # !! DOES NOT WORK. 'foo', 'bar', 'baz' | write-host -Object { "[$_]" } Therefore, a pipeline-based solution requires the use of ForEach-Object in this case: # -Object is optional PS> 'foo', 'bar', 'baz' | ForEach-Object { write-host -Object "[$_]" } [foo] [bar] [baz] Contexts in which $_ (and its alias, $PSItem) is meaningfully defined: What these contexts have in common is that the $_ / $PSItem reference must be made inside a script block ({ ... }), namely one passed to / used in: ... the ForEach-Object and Where-Object cmdlets; e.g.: 1..3 | ForEach-Object { 1 + $_ } # -> 2, 3, 4 ... the intrinsic .ForEach() and intrinsic .Where() methods; e.g.: (1..3).ForEach({ 1 + $_ }) # -> 2, 3, 4 ... a parameter, assuming that parameter allows a script block to act as a delay-bind script-block parameter; e.g.: # Rename all *.txt files to *.dat files. Get-ChildItem *.txt | Rename-Item -NewName { $_.BaseName + '.dat' } -WhatIf ... conditionals and associated script blocks inside a switch statement; e.g.: # -> 'is one or three: one', 'is one or three: three' switch ('one', 'two', 'three') { { $_ -in 'one', 'three' } { 'is one or three: ' + $_ } } ... simple function and filters; e.g.: # -> 2, 3 function Add-One { process { 1 + $_ } }; 1..2 | Add-One # -> 2, 3 filter Add-One { 1 + $_ }; 1..2 | Add-One ... direct subscriptions to an object's event (n/a to the script block that is passed to the -Action parameter of a Register-ObjectEvent call); e.g::Tip of the hat to Santiago Squarzon. # In a direct event-subscription script block used in the # context of WinForms; e.g: $txtBox.Add_KeyPress({ param($sender, $eventArgs) # The alternative to the explicitly defined parameters above is: # $this ... implicitly the same as $sender, i.e. the event-originating object # $_ / $PSItem ... implicitly the same as $eventArgs, i.e. the event-arguments object. }) PowerShell (Core) only: ... the substitution operand of the -replace operator; e.g.: # -> 'a10, 'a20' 'a1', 'a2' -replace '\d+', { 10 * [int] $_.Value } ... in the context of using PowerShell SDK methods such as .InvokeWithContext() # -> 43 { 1 + $_ }.InvokeWithContext($null, [psvariable]::new('_', 42), $null) A: You can use it as iRon has indicated in the comments. $_ or $PSItem is the current object in the pipeline that is being processed. Typically, you see this with commands that require a processing or script block. You would have to contain your Write-Host command within a similar processing block. 'foo', 'bar', 'baz' | ForEach-Object {write-host $_} Here is an example using the process block of a function: function write-stuff { process { write-host $_ } } 'foo', 'bar', 'baz' | write-stuff bar foo hi A: $_ will never work outside a scriptblock. How about write-output instead: 'hi' | Write-Output -InputObject { $_ + ' there' } hi there
Why can't I use $_ in write-host?
I am trying to pipe an array of strings to write-host and explicitly use $_ to write those strings: 'foo', 'bar', 'baz' | write-host $_ However, it fails with: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. This error message makes no sense to me because I am perfectly able to write 'foo', 'bar', 'baz' | write-host I would have expected both pipelines to be equivalent. Apparently, they're not. So, what's the difference?
[ "\ntl;dr\n\nThe automatic $_ variable and its alias, $PSItem, only ever have meaningful values inside script blocks ({ ... }), in specific contexts.\n\nThe bottom section lists all relevant contexts.\n\n\n\n\nI would have expected both pipelines to be equivalent.\n\nThey're not:\n\n'foo', 'bar', 'baz' | write-host\n\nIt is the pipeline-based equivalent of the following (equivalent in ultimate effect, not technically):\nforeach ($str in 'foo', 'bar', 'baz') { Write-Host -Object $str }\n\nThat is, in your command Write-Host receives input from the pipeline that implicitly binds to its -Object parameter for each input object, by virtue of parameter -Object being declared as accepting pipeline input via attribute [Parameter(ValueFromPipeline=$true)]\n\n\n'foo', 'bar', 'baz' | write-host $_\n\nBefore pipeline processing begins, arguments - $_ in your case - are bound to parameters first:\nSince $_ isn't preceded by a parameter name, it binds positionally to the - implied - -Object parameter.\nThen, when pipeline processing begins, pipeline parameter binding finds no pipeline-binding Write-Host parameter to bind to anymore, given that the only such parameter, -Object has already been bound, namely by an argument $_.\nIn other words: your command mistakenly tries to bind the -Object parameter twice; unfortunately, the error message doesn't exactly make that clear.\nThe larger point is that using $_ only ever makes sense inside a script block ({ ... }) that is evaluated for each input object.\nOutside that context, $_ (or its alias, $PSItem) typically has no value and shouldn't be used - see the bottom section for an overview of all contexts in which $_ / $PSItem inside a script block is meaningfully supported.\nWhile $_ is most typically used in the script blocks passed to the ForEach-Object and Where-Object cmdlets, there are other useful applications, most typically seen with the Rename-Item cmdlet: a delay-bind script-block argument:\n# Example: rename *.txt files to *.dat files using a delay-bind script block:\nGet-ChildItem *.txt | Rename-Item -NewName { $_.BaseName + '.dat' } -WhatIf\n\nThat is, instead of passing a static new name to Rename-Item, you pass a script block that is evaluated for each input object - with the input object bound to $_, as usual - which enables dynamic behavior.\nAs explained in the linked answer, however, this technique only works with parameters that are both (a) pipeline-binding and (b) not [object] or [scriptblock] typed; therefore, given that Write-Object's -Object parameter is [object] typed, the technique does not work:\n # Try to enclose all inputs in [...] on output.\n # !! DOES NOT WORK.\n 'foo', 'bar', 'baz' | write-host -Object { \"[$_]\" }\n\nTherefore, a pipeline-based solution requires the use of ForEach-Object in this case:\n# -Object is optional\nPS> 'foo', 'bar', 'baz' | ForEach-Object { write-host -Object \"[$_]\" }\n[foo]\n[bar]\n[baz]\n\n\nContexts in which $_ (and its alias, $PSItem) is meaningfully defined:\nWhat these contexts have in common is that the $_ / $PSItem reference must be made inside a script block ({ ... }), namely one passed to / used in:\n\n... the ForEach-Object and Where-Object cmdlets; e.g.:\n1..3 | ForEach-Object { 1 + $_ } # -> 2, 3, 4\n\n\n... the intrinsic .ForEach() and intrinsic .Where() methods; e.g.:\n(1..3).ForEach({ 1 + $_ }) # -> 2, 3, 4\n\n\n... a parameter, assuming that parameter allows a script block to act as a delay-bind script-block parameter; e.g.:\n# Rename all *.txt files to *.dat files.\nGet-ChildItem *.txt | Rename-Item -NewName { $_.BaseName + '.dat' } -WhatIf\n\n\n... conditionals and associated script blocks inside a switch statement; e.g.:\n# -> 'is one or three: one', 'is one or three: three'\nswitch ('one', 'two', 'three') {\n { $_ -in 'one', 'three' } { 'is one or three: ' + $_ }\n}\n\n\n... simple function and filters; e.g.:\n# -> 2, 3\nfunction Add-One { process { 1 + $_ } }; 1..2 | Add-One\n\n# -> 2, 3\nfilter Add-One { 1 + $_ }; 1..2 | Add-One\n\n\n... direct subscriptions to an object's event (n/a to the script block that is passed to the -Action parameter of a Register-ObjectEvent call); e.g::Tip of the hat to Santiago Squarzon.\n# In a direct event-subscription script block used in the\n# context of WinForms; e.g:\n$txtBox.Add_KeyPress({ \n param($sender, $eventArgs)\n # The alternative to the explicitly defined parameters above is:\n # $this ... implicitly the same as $sender, i.e. the event-originating object\n # $_ / $PSItem ... implicitly the same as $eventArgs, i.e. the event-arguments object.\n})\n\n\nPowerShell (Core) only: ... the substitution operand of the -replace operator; e.g.:\n# -> 'a10, 'a20'\n'a1', 'a2' -replace '\\d+', { 10 * [int] $_.Value }\n\n\n... in the context of using PowerShell SDK methods such as .InvokeWithContext()\n# -> 43\n{ 1 + $_ }.InvokeWithContext($null, [psvariable]::new('_', 42), $null)\n\n\n\n", "You can use it as iRon has indicated in the comments. $_ or $PSItem is the current object in the pipeline that is being processed. Typically, you see this with commands that require a processing or script block. You would have to contain your Write-Host command within a similar processing block.\n'foo', 'bar', 'baz' | ForEach-Object {write-host $_}\n\nHere is an example using the process block of a function:\nfunction write-stuff {\n process { write-host $_ }\n}\n\n'foo', 'bar', 'baz' | write-stuff\nbar\nfoo\nhi\n\n", "$_ will never work outside a scriptblock. How about write-output instead:\n'hi' | Write-Output -InputObject { $_ + ' there' } \n\nhi there\n\n" ]
[ 4, 0, 0 ]
[]
[]
[ "automatic_variable", "pipeline", "powershell" ]
stackoverflow_0055665530_automatic_variable_pipeline_powershell.txt
Q: Binary representation recursion Haskell Input: two natural numbers n,k Output: digit at the 2^k digit of the binary representation of n My idea was that: Stelle :: Int -> Int Stelle n k But now I have the problem that I have no idea how to deal with it. It has something to do with recursion and div/mod but I dont what the start of the recursion is. Can somebody help me please! Thank you A: The signature should be: stelle :: Int -> Int -> Int stelle n k = … as for the base case: when k = 0, then you can return n modulo two, for the recursive case, you divide n by two and subtract one from k, so: stelle :: Int -> Int -> Int stelle n 0 = … stelle n k = … where I leave implementing the … parts as an exercise.
Binary representation recursion Haskell
Input: two natural numbers n,k Output: digit at the 2^k digit of the binary representation of n My idea was that: Stelle :: Int -> Int Stelle n k But now I have the problem that I have no idea how to deal with it. It has something to do with recursion and div/mod but I dont what the start of the recursion is. Can somebody help me please! Thank you
[ "The signature should be:\nstelle :: Int -> Int -> Int \nstelle n k = …\nas for the base case: when k = 0, then you can return n modulo two, for the recursive case, you divide n by two and subtract one from k, so:\nstelle :: Int -> Int -> Int \nstelle n 0 = …\nstelle n k = …\nwhere I leave implementing the … parts as an exercise.\n" ]
[ 0 ]
[]
[]
[ "haskell", "recursion" ]
stackoverflow_0074680613_haskell_recursion.txt
Q: How to render ONE of multiple components conditionally that works well with React's change detector? In my CRUD app, I have implemented several reuseable components like a "generic" DialogComponent and several non-reusable components. I have come across many scenarios where I need to (on the same page) either: a) render one of multiple different non-reusable components conditionally like so: return( <> { condition111 && <Component_A>} { condition222 && <Component_B>} </> ) or b) pass different props to the same component conditionally. DialogComponent contains a form which renders different fields based on whether it is an ADD or EDIT dialog (depending on the props passed in): return(<> { openAddDialog && <DialogComponent rowAction={Utils.RowActionsEnum.Add} setOpenDialog={setOpenAddDialog} /> } { openEditDialog && <DialogComponent rowAction={Utils.RowActionsEnum.Edit} setOpenDialog={setOpenEditDialog} /> } </>) ^ This works fine, but idk if it is best practice to do it this way. I was thinking maybe I could render a function that returns a component conditionally like below. QUESTION 1: Is this a good/bad idea in terms of React rendering? export const GridComponent = (props) => { ... const [gridName, setgridName] = useState(null); useEffect(() => { setGridName(props.gridName); }, []); const renderGrid = () => { switch (gridName) { case GridNameEnum.Student: return <StudentGridComponent />; case GridNameEnum.Employee: return <EmployeeGridComponent />; default: return <h1>Grid rendering error.</h1>; } }; return(<> { renderGrid() } </>) } QUESTION 2: What is the best way to handle this conditional rendering of a) one of multiple different components and b) same component rendered conditionally with different props? (Note: these are "child components" to be rendered on the same page) A: You're asking two questions in one here and for opinions which is generally frowned upon but for the sake of trying to provide some guidance let's approach this in a functional way. QUESTION 1: Is this a good/bad idea in terms of React rendering?: It's fine because you only do one OR the other, never both but I'd still use a ternary if I were writing this myself to make it very clear that only one of these situations can ever occur: enum DialogOptions { Add, Edit, Delete } interface MyComponentProps { DialogOption: DialogOptions } const MyComponent = ({ DialogOption }: MyComponentProps) => { return DialogOption === DialogOptions.Add ? 'Add' : DialogOption === DialogOptions.Edit ? 'Edit' : DialogOption === DialogOptions.Delete ? 'Delete' : null } QUESTION 2: What is the best way to handle this conditional rendering of a) one of multiple different components and b) same component rendered conditionally with different props? There are many ways you could do this and people will have different opinions. In the limited situation you've described your grid component obfuscates what is happening and means I have to dig in the code which is not helpful. It would be cleaner to: Use a generic grid component which can be applied in multiple places (if this is possible, otherwise ignore this). Create your StudentGridComponent and EmployeeGridComponent components which implement the generic grid component, or their own unique grid component if nothing can be shared. Call the appropriate grid directly where it is required (whether this is a page or another component) using the ternary suggestion above (but put this inside your return and conditionally render the appropriate component or return some sort of empty message) In terms of the way you've built your grid component I don't see the point of this. At the time where you're rendering your grid you should already be conditionally rendering either of the grids because you know you have that data, or you don't. There's no need for the complex state logic you've introduced within the grid component itself.
How to render ONE of multiple components conditionally that works well with React's change detector?
In my CRUD app, I have implemented several reuseable components like a "generic" DialogComponent and several non-reusable components. I have come across many scenarios where I need to (on the same page) either: a) render one of multiple different non-reusable components conditionally like so: return( <> { condition111 && <Component_A>} { condition222 && <Component_B>} </> ) or b) pass different props to the same component conditionally. DialogComponent contains a form which renders different fields based on whether it is an ADD or EDIT dialog (depending on the props passed in): return(<> { openAddDialog && <DialogComponent rowAction={Utils.RowActionsEnum.Add} setOpenDialog={setOpenAddDialog} /> } { openEditDialog && <DialogComponent rowAction={Utils.RowActionsEnum.Edit} setOpenDialog={setOpenEditDialog} /> } </>) ^ This works fine, but idk if it is best practice to do it this way. I was thinking maybe I could render a function that returns a component conditionally like below. QUESTION 1: Is this a good/bad idea in terms of React rendering? export const GridComponent = (props) => { ... const [gridName, setgridName] = useState(null); useEffect(() => { setGridName(props.gridName); }, []); const renderGrid = () => { switch (gridName) { case GridNameEnum.Student: return <StudentGridComponent />; case GridNameEnum.Employee: return <EmployeeGridComponent />; default: return <h1>Grid rendering error.</h1>; } }; return(<> { renderGrid() } </>) } QUESTION 2: What is the best way to handle this conditional rendering of a) one of multiple different components and b) same component rendered conditionally with different props? (Note: these are "child components" to be rendered on the same page)
[ "You're asking two questions in one here and for opinions which is generally frowned upon but for the sake of trying to provide some guidance let's approach this in a functional way.\nQUESTION 1: Is this a good/bad idea in terms of React rendering?:\nIt's fine because you only do one OR the other, never both but I'd still use a ternary if I were writing this myself to make it very clear that only one of these situations can ever occur:\nenum DialogOptions {\n Add,\n Edit,\n Delete\n}\n\ninterface MyComponentProps {\n DialogOption: DialogOptions\n}\n\nconst MyComponent = ({ DialogOption }: MyComponentProps) => {\n return DialogOption === DialogOptions.Add ? 'Add' : DialogOption === DialogOptions.Edit ? 'Edit' : DialogOption === DialogOptions.Delete ? 'Delete' : null\n}\n\nQUESTION 2: What is the best way to handle this conditional rendering of a) one of multiple different components and b) same component rendered conditionally with different props?\nThere are many ways you could do this and people will have different opinions. In the limited situation you've described your grid component obfuscates what is happening and means I have to dig in the code which is not helpful. It would be cleaner to:\n\nUse a generic grid component which can be applied in multiple places (if this is possible, otherwise ignore this).\nCreate your StudentGridComponent and EmployeeGridComponent components which implement the generic grid component, or their own unique grid component if nothing can be shared.\nCall the appropriate grid directly where it is required (whether this is a page or another component) using the ternary suggestion above (but put this inside your return and conditionally render the appropriate component or return some sort of empty message)\n\nIn terms of the way you've built your grid component I don't see the point of this. At the time where you're rendering your grid you should already be conditionally rendering either of the grids because you know you have that data, or you don't. There's no need for the complex state logic you've introduced within the grid component itself.\n" ]
[ 1 ]
[]
[]
[ "javascript", "react_functional_component", "reactjs", "typescript" ]
stackoverflow_0074678164_javascript_react_functional_component_reactjs_typescript.txt
Q: How do I combine html, css, vanilla JS and python? I'm taking a python course and I want to make a projects page, displaying all course projects. So far, I've been working on creating a hub page, each project getting a project "card" which, upon being clicked, redirects one to a particular project page. The basic gist of it is this: https://codepen.io/MaFomedanu/pen/mdKGVNN So far I've been using replit to write the python code and then import it on the page using an iframe tag. As the course progressed, I'm required to use Pycharm. I would still like to put projects on my page but I don't really know how. I'm aware that you can't run python on a page the same way you run JS but I've read about Flask. I don't know how it works exactly, but from what I've seen in tutorials, they all create a new page that runs a python script. My question/what I want to achieve: Is it possible for me to create python web apps (pages?) that I can import in my already existing project(which only uses html, css and vanilla JS)? In extra layman terms: how can I click a project card so that I get redirected to a page that allows me to present a working python "app" as if it were run by the browser (the same way JS is)?
How do I combine html, css, vanilla JS and python?
I'm taking a python course and I want to make a projects page, displaying all course projects. So far, I've been working on creating a hub page, each project getting a project "card" which, upon being clicked, redirects one to a particular project page. The basic gist of it is this: https://codepen.io/MaFomedanu/pen/mdKGVNN So far I've been using replit to write the python code and then import it on the page using an iframe tag. As the course progressed, I'm required to use Pycharm. I would still like to put projects on my page but I don't really know how. I'm aware that you can't run python on a page the same way you run JS but I've read about Flask. I don't know how it works exactly, but from what I've seen in tutorials, they all create a new page that runs a python script. My question/what I want to achieve: Is it possible for me to create python web apps (pages?) that I can import in my already existing project(which only uses html, css and vanilla JS)? In extra layman terms: how can I click a project card so that I get redirected to a page that allows me to present a working python "app" as if it were run by the browser (the same way JS is)?
[]
[]
[ "Flask is a library for that allows you to write all the backend code for a web server in Python. Flask handles listening for requests, setting up routes, and things like session management, but it does not run in the browser. You can use Jinja with Flask to insert data into the HTML templates that it returns, but once the webpage is sent to the client, the server no longer has any control over it.\nYou could try using something like PyScript to run Python code on the client side too, but Python does not support this natively, and Flask does not include any functionality like this out of the box.\nIf you already have the HTML, CSS, and JS written for your webpages, all you would need to do in Flask is set up a route for clients to request, then create a function that returns your webpage.\nFlask has some great documentation that describes how to set this up (you'll want to view the rendering templates section to see how to return html files)\nHope this helps!\n" ]
[ -1 ]
[ "flask", "frameworks", "frontend", "javascript", "python" ]
stackoverflow_0074622193_flask_frameworks_frontend_javascript_python.txt
Q: barplot using ggplot2 is not working with error bars I am trying to plot a simple barplot on R using ggplot2 but I am having trouble. The y axis numbers are all messed up and the error bars are also not showing up correctly. Below is my code and this is a link to my data file. Thanks! #load data and view dataset crop.data1 <- read.csv("barleystarch1.csv", header = TRUE,stringsAsFactors = T) summary(crop.data1) crop.data1$locyear = as.factor(paste(crop.data1$location,"_",crop.data1$year,sep='')) View(crop.data1) str(crop.data1) #barplot with error bars library(ggplot2) ggplot(crop.data1) + geom_bar( aes(x=locyear, y=adry), stat="identity", fill="grey", alpha=0.5) + geom_pointrange( aes(x=locyear, y=adry, ymin=adry-sd, ymax=adry+sd), colour="orange", alpha=0.95, size=0.5)+ theme_classic() A: The problem is that you have several rows for each locyear (one for each genotype). Currently, the values for adry are stacking on top of each other. You either need a separate plot for each genotype, or use genotype for the fill aesthetic and dodge the bars at each locyear, or summarize the different genotypes yourself for plotting. Here's the third option, which is closest to the plot you seemed to want: crop.data1 <- read.csv("barleystarch1.csv", stringsAsFactors = TRUE) crop.data1$locyear = as.factor(paste(crop.data1$location, "_", crop.data1$year, sep = '')) library(ggplot2) library(dplyr) crop.data1 %>% group_by(locyear) %>% summarize(se = sd(adry, na.rm = TRUE)/sqrt(n()), adry = mean(adry, na.rm = TRUE)) %>% ggplot(aes(locyear, adry)) + geom_col(fill = "gray", alpha = 0.5, position = "dodge") + geom_pointrange(aes(ymin = adry - se, ymax = adry + se), alpha = 0.95, size = 0.5, color = "orange", position = position_dodge(width = 0.9)) + theme_classic() Note though that "dynamite stick" plots like this are generally considered a poor way of showing summarized data. A boxplot, dotplot or violin plot might be better.
barplot using ggplot2 is not working with error bars
I am trying to plot a simple barplot on R using ggplot2 but I am having trouble. The y axis numbers are all messed up and the error bars are also not showing up correctly. Below is my code and this is a link to my data file. Thanks! #load data and view dataset crop.data1 <- read.csv("barleystarch1.csv", header = TRUE,stringsAsFactors = T) summary(crop.data1) crop.data1$locyear = as.factor(paste(crop.data1$location,"_",crop.data1$year,sep='')) View(crop.data1) str(crop.data1) #barplot with error bars library(ggplot2) ggplot(crop.data1) + geom_bar( aes(x=locyear, y=adry), stat="identity", fill="grey", alpha=0.5) + geom_pointrange( aes(x=locyear, y=adry, ymin=adry-sd, ymax=adry+sd), colour="orange", alpha=0.95, size=0.5)+ theme_classic()
[ "The problem is that you have several rows for each locyear (one for each genotype). Currently, the values for adry are stacking on top of each other. You either need a separate plot for each genotype, or use genotype for the fill aesthetic and dodge the bars at each locyear, or summarize the different genotypes yourself for plotting.\nHere's the third option, which is closest to the plot you seemed to want:\ncrop.data1 <- read.csv(\"barleystarch1.csv\", stringsAsFactors = TRUE)\ncrop.data1$locyear = as.factor(paste(crop.data1$location, \"_\", \n crop.data1$year, sep = ''))\n\nlibrary(ggplot2)\nlibrary(dplyr)\n\ncrop.data1 %>%\n group_by(locyear) %>%\n summarize(se = sd(adry, na.rm = TRUE)/sqrt(n()),\n adry = mean(adry, na.rm = TRUE)) %>%\n ggplot(aes(locyear, adry)) +\n geom_col(fill = \"gray\", alpha = 0.5, position = \"dodge\") +\n geom_pointrange(aes(ymin = adry - se, ymax = adry + se), \n alpha = 0.95, size = 0.5, color = \"orange\",\n position = position_dodge(width = 0.9)) +\n theme_classic() \n\n\nNote though that \"dynamite stick\" plots like this are generally considered a poor way of showing summarized data. A boxplot, dotplot or violin plot might be better.\n" ]
[ 0 ]
[]
[]
[ "ggplot2", "r" ]
stackoverflow_0074680527_ggplot2_r.txt
Q: nextjs /home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/cli/next-dev.js:315 I would like to create my first project in NextJS. I follow this steps: npx create-next-app@latest npm run dev But I get the following error: grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ npm run dev > my-app@0.1.0 dev > next dev /home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/cli/next-dev.js:315 showAll: args["--show-all"] ?? false, ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.dev (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/lib/commands.js:10:30) at Object.<anonymous> (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/bin/next:141:28) at Module._compile (internal/modules/cjs/loader.js:999:30) grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ rm -rf node_modules grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ npm install npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'eslint-import-resolver-typescript@3.5.2', npm WARN EBADENGINE required: { node: '^14.18.0 || >=16.0.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'next@13.0.6', npm WARN EBADENGINE required: { node: '>=14.6.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'synckit@0.8.4', npm WARN EBADENGINE required: { node: '^14.18.0 || >=16.0.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } added 251 packages, and audited 252 packages in 6s 86 packages are looking for funding run `npm fund` for details found 0 vulnerabilities grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ npm run dev > my-app@0.1.0 dev > next dev /home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/cli/next-dev.js:315 showAll: args["--show-all"] ?? false, ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.dev (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/lib/commands.js:10:30) at Object.<anonymous> (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/bin/next:141:28) at Module._compile (internal/modules/cjs/loader.js:999:30)* I tried delete node_modules folder and after execute "npm install". But it still giving me the same error Thanks in advance A: You are running an older version of Node.js (v12.22.9) which does not support the ?? operator used in the next package. The error message indicates that the next package requires at least Node.js 14.6.0 to run. To fix this issue, you will need to update your version of Node.js to at least 14.6.0 by following the instructions on the Node.js website. Once you have updated Node.js, you can try running npm run dev again to start the development server. Additionally, after updating Nodejs, you can try removing the node_modules directory and running npm install again to ensure that all of the required packages are installed with compatible versions.
nextjs /home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/cli/next-dev.js:315
I would like to create my first project in NextJS. I follow this steps: npx create-next-app@latest npm run dev But I get the following error: grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ npm run dev > my-app@0.1.0 dev > next dev /home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/cli/next-dev.js:315 showAll: args["--show-all"] ?? false, ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.dev (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/lib/commands.js:10:30) at Object.<anonymous> (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/bin/next:141:28) at Module._compile (internal/modules/cjs/loader.js:999:30) grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ rm -rf node_modules grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ npm install npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'eslint-import-resolver-typescript@3.5.2', npm WARN EBADENGINE required: { node: '^14.18.0 || >=16.0.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'next@13.0.6', npm WARN EBADENGINE required: { node: '>=14.6.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: 'synckit@0.8.4', npm WARN EBADENGINE required: { node: '^14.18.0 || >=16.0.0' }, npm WARN EBADENGINE current: { node: 'v12.22.9', npm: '8.5.1' } npm WARN EBADENGINE } added 251 packages, and audited 252 packages in 6s 86 packages are looking for funding run `npm fund` for details found 0 vulnerabilities grafeno30@linuxHome:~/src/NextJS/file-based-routing/my-app$ npm run dev > my-app@0.1.0 dev > next dev /home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/cli/next-dev.js:315 showAll: args["--show-all"] ?? false, ^ SyntaxError: Unexpected token '?' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.dev (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/lib/commands.js:10:30) at Object.<anonymous> (/home/grafeno30/src/NextJS/file-based-routing/my-app/node_modules/next/dist/bin/next:141:28) at Module._compile (internal/modules/cjs/loader.js:999:30)* I tried delete node_modules folder and after execute "npm install". But it still giving me the same error Thanks in advance
[ "You are running an older version of Node.js (v12.22.9) which does not support the ?? operator used in the next package. The error message indicates that the next package requires at least Node.js 14.6.0 to run.\nTo fix this issue, you will need to update your version of Node.js to at least 14.6.0 by following the instructions on the Node.js website. Once you have updated Node.js, you can try running npm run dev again to start the development server.\nAdditionally, after updating Nodejs, you can try removing the node_modules directory and running npm install again to ensure that all of the required packages are installed with compatible versions.\n" ]
[ 0 ]
[]
[]
[ "next.js" ]
stackoverflow_0074680641_next.js.txt
Q: how i extends my custom order item using WC_Order_Item_Product i want to extends my custom entity from WC_Order_Item_Product. i add my custom extra data to this class . class RoomOrderItem extends OrderItemLegacy { protected $extra_data = array( 'product_id' => 0, 'variation_id' => 0, 'quantity' => 1, 'tax_class'=> '', 'subtotal' => 0, 'subtotal_tax' => 0, 'total' => 0, 'total_tax' => 0, 'taxes' => [ 'subtotal' => [], 'total' => [], ], 'period' => '', 'extra' => '', 'manager' => [], 'entity' => __CLASS__, ); public function set_period(DateTime $day){ $this->set_prop('period',$day->format('Y-m-d')); return $this; } public function set_extra(int $extra){ $this->set_prop('extra',$extra); return $this; } public function set_manager(array $manager){ $this->set_prop('manager',$manager); return $this; } } but when is adding my custom order item (RoomOrderItem extends WC_Order_Item_Product) new extra data does not save in any tables. here is my sample code for adding new RoomOrdeItem to order object: public function add(RoomCartItem $room_cart_item){ $this->set_props([ 'quantity' => $room_cart_item->get_prop('quantity'), 'variation' => $room_cart_item->get_prop('variation'), 'subtotal' => $room_cart_item->get_prop('line_subtotal'), 'total' => $room_cart_item->get_prop('line_total'), 'name' => $room_cart_item->get_hotel()->get_name(), 'product_id' => $room_cart_item->get_prop('product_id'), 'variation_id' => $room_cart_item->get_prop('variation_id'), '_period' => $room_cart_item->get_period(), '_manager' => $room_cart_item->get_manager(), '_extra' => $room_cart_item->get_extra(), '_entity' => __CLASS__, ]); return $this->get_order()->add_item($this); } In addition, I know that a meta can be added to this item with the $this->add_meta_data(). But why the new data is not automatically saved in the item. A: I think your issues is you haven't saved the data. if you're working with an orderitem object class you should be able to use the save() function. public function add(RoomCartItem $room_cart_item){ $this->set_props([ 'quantity' => $room_cart_item->get_prop('quantity'), 'variation' => $room_cart_item->get_prop('variation'), 'subtotal' => $room_cart_item->get_prop('line_subtotal'), 'total' => $room_cart_item->get_prop('line_total'), 'name' => $room_cart_item->get_hotel()->get_name(), 'product_id' => $room_cart_item->get_prop('product_id'), 'variation_id' => $room_cart_item->get_prop('variation_id'), '_period' => $room_cart_item->get_period(), '_manager' => $room_cart_item->get_manager(), '_extra' => $room_cart_item->get_extra(), '_entity' => __CLASS__, ]); $this->save(); //save the updated props return $this->get_order()->add_item($this); }
how i extends my custom order item using WC_Order_Item_Product
i want to extends my custom entity from WC_Order_Item_Product. i add my custom extra data to this class . class RoomOrderItem extends OrderItemLegacy { protected $extra_data = array( 'product_id' => 0, 'variation_id' => 0, 'quantity' => 1, 'tax_class'=> '', 'subtotal' => 0, 'subtotal_tax' => 0, 'total' => 0, 'total_tax' => 0, 'taxes' => [ 'subtotal' => [], 'total' => [], ], 'period' => '', 'extra' => '', 'manager' => [], 'entity' => __CLASS__, ); public function set_period(DateTime $day){ $this->set_prop('period',$day->format('Y-m-d')); return $this; } public function set_extra(int $extra){ $this->set_prop('extra',$extra); return $this; } public function set_manager(array $manager){ $this->set_prop('manager',$manager); return $this; } } but when is adding my custom order item (RoomOrderItem extends WC_Order_Item_Product) new extra data does not save in any tables. here is my sample code for adding new RoomOrdeItem to order object: public function add(RoomCartItem $room_cart_item){ $this->set_props([ 'quantity' => $room_cart_item->get_prop('quantity'), 'variation' => $room_cart_item->get_prop('variation'), 'subtotal' => $room_cart_item->get_prop('line_subtotal'), 'total' => $room_cart_item->get_prop('line_total'), 'name' => $room_cart_item->get_hotel()->get_name(), 'product_id' => $room_cart_item->get_prop('product_id'), 'variation_id' => $room_cart_item->get_prop('variation_id'), '_period' => $room_cart_item->get_period(), '_manager' => $room_cart_item->get_manager(), '_extra' => $room_cart_item->get_extra(), '_entity' => __CLASS__, ]); return $this->get_order()->add_item($this); } In addition, I know that a meta can be added to this item with the $this->add_meta_data(). But why the new data is not automatically saved in the item.
[ "I think your issues is you haven't saved the data.\nif you're working with an orderitem object class you should be able to use the save() function.\npublic function add(RoomCartItem $room_cart_item){\n $this->set_props([\n 'quantity' => $room_cart_item->get_prop('quantity'),\n 'variation' => $room_cart_item->get_prop('variation'),\n 'subtotal' => $room_cart_item->get_prop('line_subtotal'),\n 'total' => $room_cart_item->get_prop('line_total'),\n 'name' => $room_cart_item->get_hotel()->get_name(),\n 'product_id' => $room_cart_item->get_prop('product_id'),\n 'variation_id' => $room_cart_item->get_prop('variation_id'),\n '_period' => $room_cart_item->get_period(),\n '_manager' => $room_cart_item->get_manager(),\n '_extra' => $room_cart_item->get_extra(),\n '_entity' => __CLASS__,\n ]);\n $this->save(); //save the updated props\n return $this->get_order()->add_item($this);\n}\n\n" ]
[ 0 ]
[]
[]
[ "php", "woocommerce", "wordpress" ]
stackoverflow_0073070151_php_woocommerce_wordpress.txt
Q: Error while migrating from AngularJS to Angular: This constructor is not compatible with Angular Dependency Injection I've been trying for days to understand why I have this error on my browser console, the full stack: Unhandled Promise rejection: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors. ; Zone: <root> ; Task: Promise.then ; Value: Error: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors. at ɵɵinvalidFactoryDep (injector_compatibility.ts:94:9) at Object.AppModule_Factory [as useFactory] (ɵfac.js? [sm]:1:1) at Object.factory (r3_injector.ts:450:32) at R3Injector.hydrate (r3_injector.ts:352:29) at R3Injector.get (r3_injector.ts:235:23) at injectInjectorOnly (injector_compatibility.ts:64:29) at ɵɵinject (injector_compatibility.ts:81:58) at useValue (provider_collection.ts:249:62) at R3Injector.resolveInjectorInitializers (r3_injector.ts:284:9) at new NgModuleRef (ng_module_ref.ts:86:22) Error: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors. at ɵɵinvalidFactoryDep (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:4774:11) at Object.AppModule_Factory [as useFactory] (ng:///AppModule/ɵfac.js:4:37) at Object.factory (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6968:38) at R3Injector.hydrate (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6881:35) at R3Injector.get (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6769:33) at injectInjectorOnly (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:4758:33) at ɵɵinject (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:4762:61) at useValue (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6561:65) at R3Injector.resolveInjectorInitializers (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6818:17) at new NgModuleRef (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:21725:26) My app.module.ts looks like this: import "@angular/compiler"; import "zone.js"; import {DoBootstrap, NgModule} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UpgradeModule } from '@angular/upgrade/static'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; // import moment from "moment"; @NgModule({ imports: [ BrowserModule, UpgradeModule ], }) export class AppModule implements DoBootstrap { constructor(private upgrade: UpgradeModule) { } ngDoBootstrap() { this.upgrade.bootstrap(document.body, ['CoreApplication'], { strictDi: true }); } } platformBrowserDynamic().bootstrapModule(AppModule); I'm using importmap to handle ES modules, that (from what I can see) it is working but on bootstrap the application fails with that error. Can someone help me? [EDIT 1] I'm trying to debug the library, the error is raised at provider.useFactory(), the provider on console is presented like this: { deps: [] provide: ƒ AppModule(upgrade) useFactory: ƒ AppModule_Factory(t) [[Prototype]]: Object } The line at https://github.com/angular/angular/blob/211c35358a322f6857c919a2cc80218fbd235649/packages/core/src/di/r3_injector.ts#L450 uses injectArgs to return an array that in my case is empty, due to this the function does not go on. Do I have to declare some factory? If so where? [EDIT 2] The function provider.useFactory seems to be defined as follows: 'function AppModule_Factory(t) {\n return new (t || jit_AppModule_0)(jit___invalidFactoryDep_1(0));\n}' A: I saw the same issue and I was able to resolve it by adding an Injection Token inside the constructor constructor(@Inject(UpgradeModule) private upgrade: UpgradeModule) {}
Error while migrating from AngularJS to Angular: This constructor is not compatible with Angular Dependency Injection
I've been trying for days to understand why I have this error on my browser console, the full stack: Unhandled Promise rejection: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors. ; Zone: <root> ; Task: Promise.then ; Value: Error: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors. at ɵɵinvalidFactoryDep (injector_compatibility.ts:94:9) at Object.AppModule_Factory [as useFactory] (ɵfac.js? [sm]:1:1) at Object.factory (r3_injector.ts:450:32) at R3Injector.hydrate (r3_injector.ts:352:29) at R3Injector.get (r3_injector.ts:235:23) at injectInjectorOnly (injector_compatibility.ts:64:29) at ɵɵinject (injector_compatibility.ts:81:58) at useValue (provider_collection.ts:249:62) at R3Injector.resolveInjectorInitializers (r3_injector.ts:284:9) at new NgModuleRef (ng_module_ref.ts:86:22) Error: NG0202: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors. at ɵɵinvalidFactoryDep (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:4774:11) at Object.AppModule_Factory [as useFactory] (ng:///AppModule/ɵfac.js:4:37) at Object.factory (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6968:38) at R3Injector.hydrate (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6881:35) at R3Injector.get (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6769:33) at injectInjectorOnly (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:4758:33) at ɵɵinject (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:4762:61) at useValue (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6561:65) at R3Injector.resolveInjectorInitializers (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:6818:17) at new NgModuleRef (http://localhost:3300/node_modules/@angular/core/fesm2015/core.mjs:21725:26) My app.module.ts looks like this: import "@angular/compiler"; import "zone.js"; import {DoBootstrap, NgModule} from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UpgradeModule } from '@angular/upgrade/static'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; // import moment from "moment"; @NgModule({ imports: [ BrowserModule, UpgradeModule ], }) export class AppModule implements DoBootstrap { constructor(private upgrade: UpgradeModule) { } ngDoBootstrap() { this.upgrade.bootstrap(document.body, ['CoreApplication'], { strictDi: true }); } } platformBrowserDynamic().bootstrapModule(AppModule); I'm using importmap to handle ES modules, that (from what I can see) it is working but on bootstrap the application fails with that error. Can someone help me? [EDIT 1] I'm trying to debug the library, the error is raised at provider.useFactory(), the provider on console is presented like this: { deps: [] provide: ƒ AppModule(upgrade) useFactory: ƒ AppModule_Factory(t) [[Prototype]]: Object } The line at https://github.com/angular/angular/blob/211c35358a322f6857c919a2cc80218fbd235649/packages/core/src/di/r3_injector.ts#L450 uses injectArgs to return an array that in my case is empty, due to this the function does not go on. Do I have to declare some factory? If so where? [EDIT 2] The function provider.useFactory seems to be defined as follows: 'function AppModule_Factory(t) {\n return new (t || jit_AppModule_0)(jit___invalidFactoryDep_1(0));\n}'
[ "I saw the same issue and I was able to resolve it by adding an Injection Token inside the constructor\nconstructor(@Inject(UpgradeModule) private upgrade: UpgradeModule) {}\n" ]
[ 0 ]
[]
[]
[ "angular", "angularjs", "import_maps", "systemjs", "typescript" ]
stackoverflow_0073154262_angular_angularjs_import_maps_systemjs_typescript.txt
Q: is there a method to turn general sound on or off in an SFML application? I want to make a button in main.cpp, by pressing which the general sound will turn on or off, but I have sounds scattered over each .h and .cpp file. I created the button itself, but so far it does not entail anything After reading the documentation about Sound in SFML, I could not find the desired function, etc. If there is such a function, I would be very happy. for example: GameState.h class GameState : public State { private: sf::SoundBuffer soundBufferMiss; sf::SoundBuffer soundBufferCrash; sf::SoundBuffer soundBufferStartGame; sf::SoundBuffer soundBufferWin; sf::SoundBuffer soundBufferLose; sf::Sound soundMiss; sf::Sound soundCrash; sf::Sound soundStartGame; sf::Sound soundWin; sf::Sound soundLose; sf::Text textAboutPlayer; sf::Text textAboutEnemy; sf::Text textInfo; Legend legend = Legend(100, 500); Map enemyMap = Map(770, 100, 1); Map* playerMap; bool winFlag; bool playerMove; std::map<std::string, Button*> buttons; std::vector<MapCoord> damagedDecks; public: GameState(std::vector<State*>* statesPointer, Map* playerMap = nullptr); ~GameState(); void botAttack(int i, int j); bool checkField(int coorI, int coorJ); void ArtificInt(); void update(sf::RenderWindow* targetWindow = nullptr); void render(sf::RenderWindow* targetWindow = nullptr); }; for example PlacingState.h class PlacingState : public State { private: sf::SoundBuffer soundBufferPlacing; sf::Sound soundPlacing; sf::SoundBuffer soundBufferFlipShip; sf::Sound soundFlipShip; sf::Text headerText; sf::Text helpText; sf::Text yourShipsText; sf::RectangleShape helpTextBackground; Map playerMap = Map(110, 100); std::vector<sf::RectangleShape> outMapShipsTable; std::map<std::string, Button*> buttons; std::vector<OutMapShip> outMapShip; public: PlacingState(std::vector<State*>* statesPointer); ~PlacingState(); void initOutMapShips(); void update(sf::RenderWindow* targetWindow = nullptr); void render(sf::RenderWindow* targetWindow = nullptr); }; A: If you mean changing the global volume for all sounds and musics there is this function you can try: SFML 2.5.1 sf::Listener::setGlobalVolume Example (turn off sound): sf::Listener::setGlobalVolume(0.0f);
is there a method to turn general sound on or off in an SFML application?
I want to make a button in main.cpp, by pressing which the general sound will turn on or off, but I have sounds scattered over each .h and .cpp file. I created the button itself, but so far it does not entail anything After reading the documentation about Sound in SFML, I could not find the desired function, etc. If there is such a function, I would be very happy. for example: GameState.h class GameState : public State { private: sf::SoundBuffer soundBufferMiss; sf::SoundBuffer soundBufferCrash; sf::SoundBuffer soundBufferStartGame; sf::SoundBuffer soundBufferWin; sf::SoundBuffer soundBufferLose; sf::Sound soundMiss; sf::Sound soundCrash; sf::Sound soundStartGame; sf::Sound soundWin; sf::Sound soundLose; sf::Text textAboutPlayer; sf::Text textAboutEnemy; sf::Text textInfo; Legend legend = Legend(100, 500); Map enemyMap = Map(770, 100, 1); Map* playerMap; bool winFlag; bool playerMove; std::map<std::string, Button*> buttons; std::vector<MapCoord> damagedDecks; public: GameState(std::vector<State*>* statesPointer, Map* playerMap = nullptr); ~GameState(); void botAttack(int i, int j); bool checkField(int coorI, int coorJ); void ArtificInt(); void update(sf::RenderWindow* targetWindow = nullptr); void render(sf::RenderWindow* targetWindow = nullptr); }; for example PlacingState.h class PlacingState : public State { private: sf::SoundBuffer soundBufferPlacing; sf::Sound soundPlacing; sf::SoundBuffer soundBufferFlipShip; sf::Sound soundFlipShip; sf::Text headerText; sf::Text helpText; sf::Text yourShipsText; sf::RectangleShape helpTextBackground; Map playerMap = Map(110, 100); std::vector<sf::RectangleShape> outMapShipsTable; std::map<std::string, Button*> buttons; std::vector<OutMapShip> outMapShip; public: PlacingState(std::vector<State*>* statesPointer); ~PlacingState(); void initOutMapShips(); void update(sf::RenderWindow* targetWindow = nullptr); void render(sf::RenderWindow* targetWindow = nullptr); };
[ "If you mean changing the global volume for all sounds and musics there is this function you can try: SFML 2.5.1 sf::Listener::setGlobalVolume\nExample (turn off sound):\nsf::Listener::setGlobalVolume(0.0f);\n\n" ]
[ 0 ]
[]
[]
[ "c++", "sfml" ]
stackoverflow_0074680571_c++_sfml.txt
Q: how to initialize y_true and y_pred for confusion_matrix and classification_report How to initialize y_true and y_pred for confusion_matrix and classification_report? I have used flow_from_dataframe. My code is as below: train_set = train_datagen.flow_from_dataframe( train, path, x_col="image_name", y_col="level", class_mode="raw", color_mode="rgb", batch_size=32, target_size=(64, 64)) val_set = val_datagen.flow_from_dataframe( val, path, x_col="image_name", y_col="level", class_mode="raw", color_mode="rgb", batch_size=32, target_size=(64, 64)) from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix Y_pred = model.predict(val_set) y_pred = np.argmax(Y_pred, axis=1) print('Confusion Matrix') print(confusion_matrix(val_set.classes, y_pred)) print('Classification Report') class_labels = list(val_set.class_indices.keys()) print(classification_report(val_set.classes, y_pred, target_names=class_labels)) I get the error as AttributeError: 'DataFrameIterator' object has no attribute 'classes'. I am trying it since a ling time. I get result for flow_from_directory but not for flow_from_dataframe. Please guide me. A: try this code below.NOTE in val_set = val_datagen.flow_from_dataframe( ...) set parameter shuffle=False errors=0 y_pred=[] y_true=val_set.labels # make sure shuffle=False in generator classes=list(val_set.class_indices.keys()) class_count=len(classes) preds=model.predict(val_set, verbose=1) for i, p in enumerate(preds): pred_index=np.argmax(p) true_index=test_gen.labels[i] # labels are integer values if pred_index != true_index: # a misclassification has occurred errors=errors + 1 y_pred.append(pred_index) tests=len(preds) acc=( 1-errors/tests) * 100 msg=f'there were {errors} errors in {tests} tests for an accuracy of {acc:6.2f}' print(msg) ypred=np.array(y_pred) ytrue=np.array(y_true) cm = confusion_matrix(ytrue, ypred ) plt.figure(figsize=(12, 8)) sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False) plt.xticks(np.arange(class_count)+.5, classes, rotation=90) plt.yticks(np.arange(class_count)+.5, classes, rotation=0) plt.xlabel("Predicted") plt.ylabel("Actual") plt.title("Confusion Matrix") plt.show() clr = classification_report(y_true, y_pred, target_names=classes, digits= 4) # create classification report print("Classification Report:\n----------------------\n", clr)
how to initialize y_true and y_pred for confusion_matrix and classification_report
How to initialize y_true and y_pred for confusion_matrix and classification_report? I have used flow_from_dataframe. My code is as below: train_set = train_datagen.flow_from_dataframe( train, path, x_col="image_name", y_col="level", class_mode="raw", color_mode="rgb", batch_size=32, target_size=(64, 64)) val_set = val_datagen.flow_from_dataframe( val, path, x_col="image_name", y_col="level", class_mode="raw", color_mode="rgb", batch_size=32, target_size=(64, 64)) from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix Y_pred = model.predict(val_set) y_pred = np.argmax(Y_pred, axis=1) print('Confusion Matrix') print(confusion_matrix(val_set.classes, y_pred)) print('Classification Report') class_labels = list(val_set.class_indices.keys()) print(classification_report(val_set.classes, y_pred, target_names=class_labels)) I get the error as AttributeError: 'DataFrameIterator' object has no attribute 'classes'. I am trying it since a ling time. I get result for flow_from_directory but not for flow_from_dataframe. Please guide me.
[ "try this code below.NOTE in val_set = val_datagen.flow_from_dataframe( ...) set parameter shuffle=False\nerrors=0\ny_pred=[]\ny_true=val_set.labels # make sure shuffle=False in generator\nclasses=list(val_set.class_indices.keys())\nclass_count=len(classes)\npreds=model.predict(val_set, verbose=1)\nfor i, p in enumerate(preds): \n pred_index=np.argmax(p) \n true_index=test_gen.labels[i] # labels are integer values \n if pred_index != true_index: # a misclassification has occurred \n errors=errors + 1\n y_pred.append(pred_index)\ntests=len(preds)\nacc=( 1-errors/tests) * 100\nmsg=f'there were {errors} errors in {tests} tests for an accuracy of {acc:6.2f}'\nprint(msg)\nypred=np.array(y_pred)\nytrue=np.array(y_true)\ncm = confusion_matrix(ytrue, ypred )\nplt.figure(figsize=(12, 8))\nsns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False) \nplt.xticks(np.arange(class_count)+.5, classes, rotation=90)\nplt.yticks(np.arange(class_count)+.5, classes, rotation=0)\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"Actual\")\nplt.title(\"Confusion Matrix\")\nplt.show()\nclr = classification_report(y_true, y_pred, target_names=classes, digits= 4) # create classification report\nprint(\"Classification Report:\\n----------------------\\n\", clr)\n\n" ]
[ 0 ]
[]
[]
[ "confusion_matrix", "keras", "multiclass_classification", "tensorflow" ]
stackoverflow_0074675829_confusion_matrix_keras_multiclass_classification_tensorflow.txt
Q: win32api.SendMessage not working when trying to release a button i am trying to send some virtual keycodes to an application while it is out of focus. I get it to work without a problem except for releasing normal keys. I have tried: win32api.SendMessage(hwnd, win32con.WM_KEYUP, VK_CODE["a"]) win32api.PostMessage(hwnd, win32con.WM_KEYUP, VK_CODE["a"]) releasing a key works perfectly with the left mouse button: win32api.SendMessage(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0) and using keydb_event: win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0) But for some reason when trying to release a key using SendMessage it pressed down the button instead. A: SendMessage lParam(0) PostMessage lParam(0) Keystroke Messages INPUT inputs{}; inputs.type = INPUT_KEYBOARD; inputs.ki.wVk = 0x41; inputs.ki.dwFlags = KEYEVENTF_KEYUP; UINT uSent = SendInput(1, &inputs, sizeof(INPUT)); Dead-Character Messages(such as The circumflex key on a German keyboard) WM_KEYDOWN WM_DEADCHAR WM_KEYUP WM_KEYDOWN WM_CHAR WM_KEYUP It depends on how the application implements WM_KEYUP and then simulation is not reliable. Attached a classic article You can't simulate keyboard input with PostMessage. A: for anyone reading this later on the problem was i wasn't specifying the Lparam in the function. this post explains it very well. should also mention SPY++ which made understanding how keypresses in windows work a lot easier.
win32api.SendMessage not working when trying to release a button
i am trying to send some virtual keycodes to an application while it is out of focus. I get it to work without a problem except for releasing normal keys. I have tried: win32api.SendMessage(hwnd, win32con.WM_KEYUP, VK_CODE["a"]) win32api.PostMessage(hwnd, win32con.WM_KEYUP, VK_CODE["a"]) releasing a key works perfectly with the left mouse button: win32api.SendMessage(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, 0) and using keydb_event: win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0) But for some reason when trying to release a key using SendMessage it pressed down the button instead.
[ "SendMessage lParam(0)\n\nPostMessage lParam(0)\n\nKeystroke Messages\n\nINPUT inputs{};\ninputs.type = INPUT_KEYBOARD;\ninputs.ki.wVk = 0x41;\ninputs.ki.dwFlags = KEYEVENTF_KEYUP;\nUINT uSent = SendInput(1, &inputs, sizeof(INPUT));\n\n\nDead-Character Messages(such as The circumflex key on a German keyboard)\n\nWM_KEYDOWN\nWM_DEADCHAR\nWM_KEYUP\nWM_KEYDOWN\nWM_CHAR\nWM_KEYUP\n\nIt depends on how the application implements WM_KEYUP and then simulation is not reliable.\nAttached a classic article You can't simulate keyboard input with PostMessage.\n", "for anyone reading this later on the problem was i wasn't specifying the Lparam in the function. this post explains it very well.\nshould also mention SPY++ which made understanding how keypresses in windows work a lot easier.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "pywin32", "winapi" ]
stackoverflow_0074532299_python_pywin32_winapi.txt
Q: How can I delay splash launch screen programmatically in Swift Xcode iOS I have put an image in imageView in LaunchStoreyboard. How can I delay the time of image programmatically? Here is the Launch Screen Guideline from Apple. Here is code for Launch Screen View controller: import UIKit class LaunshViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.delay(0.4) } func delay(_ delay:Double, closure:@escaping ()->()) { let when = DispatchTime.now() + delay DispatchQueue.main.asyncAfter(deadline: when, execute: closure) } } A: As of today there is no predefine method from Apple to hold launch screen. Here are some Approaches which are not optimum but works Approach #1 Create a Separate ViewController which has Launch logo & create a timer or perform some operation (Like Database/Loads some essential network call) depends on your app type this way you can ready with data before hand & hold the launch screen as well :) Approach #2 Not Optimum Use Sleep code which holds up the app for a while. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Thread.sleep(forTimeInterval: 3.0) // Override point for customization after application launch. return true } A: Would not recommending setting the entire application in a waiting state. If the application needs to do more work before finishing the watchdog could kill the application for taking too long time to start up. Instead you could do something like this to delay the launch screen. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UIStoryboard(name: "LaunchScreen", bundle: nil).instantiateInitialViewController() window?.makeKeyAndVisible() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() } return true } A: Swift 4.x It is Not a good practice to put your application to sleep! Booting your App should be as fast as possible, so the Launch screen delay is something you do not want to use. But, instead of sleeping you can run a loop during which the receiver processes data from all attached input sources: This will prolong the launch-screen's visibility time. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. RunLoop.current.run(until: NSDate(timeIntervalSinceNow:1) as Date) return true } A: Swift 5.x, iOS 13.x.x Modifying the following function in the AppDelegate class does not work in Swift 5.x/iOS 13.x.x. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } Instead, you will have to modify the scene function in SceneDelegate class as following. It will delay the LaunchSceen for 3 seconds. func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { window?.rootViewController = UIStoryboard(name: "LaunchScreen", bundle: nil).instantiateInitialViewController() window?.makeKeyAndVisible() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() } guard let _ = (scene as? UIWindowScene) else { return } } The window variable should already be there in SceneDelegate class like the following. var window: UIWindow? A: Definitely your app should not be put to sleep as it may be killed by the OS for being unresponsive for so long. If you're using a static image for your launch screen, what works for me is to use the image in the LaunchScreen.storyboard, and then when your main controller launches, modally present a VC with the same image as the background in the ViewDidAppear of your main controller (with animated set to false). You can then use your logic to know when to dismiss the launch screen (dismiss method in the VC with animated set to false). The transition from the actual LaunchScreen to my VC presenting the same screen looks to me imperceptible. PS: the ViewDidAppear method might be called more than once, in which case you need to use logic to not present the VC with the launch screen a second time. A: Create a ViewController and use NSTimer to detect the delay time. and when the timer ends push the first UIViewcontroller. In ViewDidLoad method.. [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(fireMethod) userInfo:nil repeats:NO]; -(void)fireMethod { // push view controller here.. } A: Put one line of code in AppDelegate Class; func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. Thread.sleep(forTimeInterval: 3.0) return true }
How can I delay splash launch screen programmatically in Swift Xcode iOS
I have put an image in imageView in LaunchStoreyboard. How can I delay the time of image programmatically? Here is the Launch Screen Guideline from Apple. Here is code for Launch Screen View controller: import UIKit class LaunshViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.delay(0.4) } func delay(_ delay:Double, closure:@escaping ()->()) { let when = DispatchTime.now() + delay DispatchQueue.main.asyncAfter(deadline: when, execute: closure) } }
[ "As of today there is no predefine method from Apple to hold launch screen. Here are some Approaches which are not optimum but works\nApproach #1\nCreate a Separate ViewController which has Launch logo & create a timer or perform some operation (Like Database/Loads some essential network call) depends on your app type this way you can ready with data before hand & hold the launch screen as well :)\nApproach #2 Not Optimum\nUse Sleep code which holds up the app for a while.\nfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n Thread.sleep(forTimeInterval: 3.0)\n // Override point for customization after application launch.\n return true\n }\n\n", "Would not recommending setting the entire application in a waiting state. \nIf the application needs to do more work before finishing the watchdog could kill the application for taking too long time to start up.\nInstead you could do something like this to delay the launch screen.\nfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n // Override point for customization after application launch.\n window = UIWindow(frame: UIScreen.main.bounds)\n window?.rootViewController = UIStoryboard(name: \"LaunchScreen\", bundle: nil).instantiateInitialViewController()\n window?.makeKeyAndVisible()\n\n DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {\n self.window?.rootViewController = UIStoryboard(name: \"Main\", bundle: nil).instantiateInitialViewController()\n }\n return true\n }\n\n", "Swift 4.x\nIt is Not a good practice to put your application to sleep!\nBooting your App should be as fast as possible, so the Launch screen delay is something you do not want to use.\nBut, instead of sleeping you can run a loop during which the receiver processes data from all attached input sources:\nThis will prolong the launch-screen's visibility time.\nfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {\n // Override point for customization after application launch.\n\n RunLoop.current.run(until: NSDate(timeIntervalSinceNow:1) as Date)\n\n return true\n}\n\n", "Swift 5.x, iOS 13.x.x\nModifying the following function in the AppDelegate class does not work in Swift 5.x/iOS 13.x.x.\nfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n // Override point for customization after application launch.\n return true\n}\n\nInstead, you will have to modify the scene function in SceneDelegate class as following. It will delay the LaunchSceen for 3 seconds.\nfunc scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {\n\n window?.rootViewController = UIStoryboard(name: \"LaunchScreen\", bundle: nil).instantiateInitialViewController()\n window?.makeKeyAndVisible()\n\n DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {\n self.window?.rootViewController = UIStoryboard(name: \"Main\", bundle: nil).instantiateInitialViewController()\n }\n\n guard let _ = (scene as? UIWindowScene) else { return }\n}\n\nThe window variable should already be there in SceneDelegate class like the following.\nvar window: UIWindow?\n\n", "Definitely your app should not be put to sleep as it may be killed by the OS for being unresponsive for so long. \nIf you're using a static image for your launch screen, what works for me is to use the image in the LaunchScreen.storyboard, and then when your main controller launches, modally present a VC with the same image as the background in the ViewDidAppear of your main controller (with animated set to false).\nYou can then use your logic to know when to dismiss the launch screen (dismiss method in the VC with animated set to false).\nThe transition from the actual LaunchScreen to my VC presenting the same screen looks to me imperceptible.\nPS: the ViewDidAppear method might be called more than once, in which case you need to use logic to not present the VC with the launch screen a second time.\n", "Create a ViewController and use NSTimer to detect the delay time. and when the timer ends push the first UIViewcontroller.\nIn ViewDidLoad method..\n[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(fireMethod) userInfo:nil repeats:NO];\n\n\n-(void)fireMethod\n{\n// push view controller here..\n}\n\n", "Put one line of code in AppDelegate Class;\n func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n // Override point for customization after application launch.\n Thread.sleep(forTimeInterval: 3.0)\n return true\n }\n\n" ]
[ 78, 23, 22, 20, 3, 2, 0 ]
[ "SwiftUI\nFor SwiftUI, you can put a very similar code to the accepted answer into ContentView.onAppearing:\nstruct ContentView: View {\n\n var body: some View {\n Text(\"Hello\")\n .onAppear {\n Thread.sleep(forTimeInterval: 3.0)\n }\n }\n}\n\n", "Putting a thread to sleep is not a good idea.\nI would suggest you go to SceneDelegate's \"willConnectTo\" function and paste this piece of code and you are good to go.\nwindow?.rootViewController = UIStoryboard(name: \"LaunchScreen\", bundle: nil).instantiateInitialViewController()\n\nwindow?.makeKeyAndVisible()\n \nDispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {\n self.window?.rootViewController = UIStoryboard(name: \"Main\", bundle: nil).instantiateInitialViewController()\n}\n \nguard let _ = (scene as? UIWindowScene) else { return }\n\n" ]
[ -1, -1 ]
[ "ios", "splash_screen", "swift", "timedelay", "xcode" ]
stackoverflow_0043276199_ios_splash_screen_swift_timedelay_xcode.txt
Q: npm create svelte@latest not working correctly on Ubuntu When I try to use npm create svelte@latest to create a SvelteKit app it won't work when using VS Code with SSH. The SSH server I'm connected to runs Ubuntu 20.04.2 on 64 bit Intel hardware. When I try to use npm create svelte@latest . to initialize a SvelteKit project it outputs an error: import fs from 'fs'; ^^ SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:723:23) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) Any way to fix this? I would appreciate any help. A: You need to update Node. The latest in Ubuntu 20 is v10, which is very outdated. If you're not in a position to update your system to Jammy or Kinetic, you can use nvm another version manager to get yourself up to date. Personally I like n: npm i -g n n stable
npm create svelte@latest not working correctly on Ubuntu
When I try to use npm create svelte@latest to create a SvelteKit app it won't work when using VS Code with SSH. The SSH server I'm connected to runs Ubuntu 20.04.2 on 64 bit Intel hardware. When I try to use npm create svelte@latest . to initialize a SvelteKit project it outputs an error: import fs from 'fs'; ^^ SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:723:23) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12) at startup (internal/bootstrap/node.js:283:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3) Any way to fix this? I would appreciate any help.
[ "You need to update Node. The latest in Ubuntu 20 is v10, which is very outdated. If you're not in a position to update your system to Jammy or Kinetic, you can use nvm another version manager to get yourself up to date. Personally I like n:\nnpm i -g n\nn stable\n\n" ]
[ 1 ]
[ "error says your system does not have the necessary dependencies to run the create command.\nclean install first\nnpm install -g @sveltejs/kit\n\nalso check version,\nnode --version\nnpm --version\n\nIf not current then ;\nnpm install -g npm\nnode --version\n\n" ]
[ -1 ]
[ "node.js", "npm", "svelte" ]
stackoverflow_0074680683_node.js_npm_svelte.txt
Q: Get user name from user_id in pivot table with eager load laravel I have 2 models and one pivot table: users id experiments id experiments_assigns id exp_id user_id The pivot table experiments_assigns has extra fields but I have not created a specific model for it. So I want to eager load all experiments with their assignments (if any) and the associated user details. I can get it work except for getting user details.. In controller I have this code: $experiments = Experiments::with('assigns')->get(); But no way I can figure out how to load the associated user details by user_id returned in pivot property. This is Experminemts class: class Experminemts extends Model { public function assigns() { return $this->belongsToMany( Experminemts::class, 'experminemts_assigns', 'exp_id' )->withPivot('name', 'description', 'date_start', 'date_end', 'user_id'); } } experiments_assigns table migration: Schema::create('experiments_assigns', function (Blueprint $table) { $table->timestamps(); $table->bigIncrements('id'); $table->string('name'); $table->text('description')->nullable(true); $table->dateTime('date_start'); $table->dateTime('date_end'); $table->unsignedBigInteger('exp_id');//->unsigned() $table->unsignedBigInteger('user_id'); $table->foreign('exp_id')->references('id')->on('experiments') ->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users') ->onDelete('cascade'); }); So what I get for assigns is: { "exp_id": 6, "name": "Experiment assignation 1", "description": null, "date_start": "2022-11-29 14:17:00", "date_end": "2022-12-30 14:17:00", "user_id": 9 } Where I would expect: { "exp_id": 6, "name": "Experiment assignation 1", "description": null, "date_start": "2022-11-29 14:17:00", "date_end": "2022-12-30 14:17:00", "user_id": 9, "user_name": "Some Name", "user_email": "some@ema.il" } Thanks A: You can create eloquent model for your pivot table ExperimentAssign and in it define relationship for user: public function user() { return $this->belongsTo(User::class); } maybe you will need to define the table too: protected $table = 'experiments_assigns'; in your Experiment model add relationship: public function experiment_assigns() { return $this->hasMany(ExperimentAssign::class); } and then call: $experiments = Experiments::with('experiment_assigns.user')->get();
Get user name from user_id in pivot table with eager load laravel
I have 2 models and one pivot table: users id experiments id experiments_assigns id exp_id user_id The pivot table experiments_assigns has extra fields but I have not created a specific model for it. So I want to eager load all experiments with their assignments (if any) and the associated user details. I can get it work except for getting user details.. In controller I have this code: $experiments = Experiments::with('assigns')->get(); But no way I can figure out how to load the associated user details by user_id returned in pivot property. This is Experminemts class: class Experminemts extends Model { public function assigns() { return $this->belongsToMany( Experminemts::class, 'experminemts_assigns', 'exp_id' )->withPivot('name', 'description', 'date_start', 'date_end', 'user_id'); } } experiments_assigns table migration: Schema::create('experiments_assigns', function (Blueprint $table) { $table->timestamps(); $table->bigIncrements('id'); $table->string('name'); $table->text('description')->nullable(true); $table->dateTime('date_start'); $table->dateTime('date_end'); $table->unsignedBigInteger('exp_id');//->unsigned() $table->unsignedBigInteger('user_id'); $table->foreign('exp_id')->references('id')->on('experiments') ->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users') ->onDelete('cascade'); }); So what I get for assigns is: { "exp_id": 6, "name": "Experiment assignation 1", "description": null, "date_start": "2022-11-29 14:17:00", "date_end": "2022-12-30 14:17:00", "user_id": 9 } Where I would expect: { "exp_id": 6, "name": "Experiment assignation 1", "description": null, "date_start": "2022-11-29 14:17:00", "date_end": "2022-12-30 14:17:00", "user_id": 9, "user_name": "Some Name", "user_email": "some@ema.il" } Thanks
[ "You can create eloquent model for your pivot table ExperimentAssign and in it define relationship for user:\npublic function user()\n{\n return $this->belongsTo(User::class);\n}\n\nmaybe you will need to define the table too:\nprotected $table = 'experiments_assigns';\n\nin your Experiment model add relationship:\npublic function experiment_assigns()\n{\n return $this->hasMany(ExperimentAssign::class);\n}\n\nand then call:\n$experiments = Experiments::with('experiment_assigns.user')->get();\n\n" ]
[ 0 ]
[]
[]
[ "eloquent", "laravel", "left_join", "mysql", "php" ]
stackoverflow_0074670783_eloquent_laravel_left_join_mysql_php.txt
Q: How to quantify how good the model is after using train_test_split I'm using the train_test_split from sklearn.model_selection. My code looks like the following: x_train, x_test , y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=1234) Edit: After this is done, how do I fit these to the linear regression model, and then see how good this model is? i.e. Which of the four components (x_train, x_test, y_train, or y_test) would I use to calculate MSE or RMSE? And how exactly how would I do that? A: To evaluate the model's performance, you can use the x_test and y_test data sets. These are the datasets that the model has not seen before and will be used to evaluate the model's generalization ability. To calculate the MSE for the model, you can use the mean_squared_error() function from the sklearn.metrics module. These functions take the true values (y_test) and the predicted values (the output of your model on the x_test data) as input and return the MSE or RMSE as a floating-point value.
How to quantify how good the model is after using train_test_split
I'm using the train_test_split from sklearn.model_selection. My code looks like the following: x_train, x_test , y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=1234) Edit: After this is done, how do I fit these to the linear regression model, and then see how good this model is? i.e. Which of the four components (x_train, x_test, y_train, or y_test) would I use to calculate MSE or RMSE? And how exactly how would I do that?
[ "To evaluate the model's performance, you can use the x_test and y_test data sets. These are the datasets that the model has not seen before and will be used to evaluate the model's generalization ability.\nTo calculate the MSE for the model, you can use the mean_squared_error() function from the sklearn.metrics module. These functions take the true values (y_test) and the predicted values (the output of your model on the x_test data) as input and return the MSE or RMSE as a floating-point value.\n" ]
[ 0 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074680716_python_scikit_learn.txt
Q: Why in different themes different buttons are created? I have an usual button and a theme which is applied to android:theme in AndroidManifest file: <Button android:id="@+id/supperButton" android:layout_width="match_parent" android:layout_height="120dp" /> <style name="AppTheme" parent="Theme.AppCompat"> </style> When i inflate this button and stop the app with debugger to see what class has been created i see the following: As you can see, instead of an usual button class, AppComapatButton has been created. When i change theme to as follows: <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> </style> MaterialButton is created, instead of an usual button class or AppComapatButton: Question: as i can gather, themes can define what exactly type of a widget is used. So what exactly does define it? Maybe there is some attribute in a theme that does it ? A: It happens if your Activity extends AppCompatActivity. The AppCompatActivity calls the setFactory2 method using a custom implementation of LayoutInflater. This implementation is done by the AppCompatViewInflater which checks the names of the views in the layout and automatically "substitutes" all usages of core Android widgets inflated from layout files by the AppCompat extensions of those widgets. You can check in the source code: @Nullable public final View createView(/**...*/) { //... switch (name) { case "Button": view = createButton(context, attrs); verifyNotNull(view, name); break; //... } @NonNull protected AppCompatButton createButton(Context context, AttributeSet attrs) { return new AppCompatButton(context, attrs); } In the MaterialComponents theme is defined another implemetantion, the MaterialComponentsViewInflater. For example you can check in the source code: @Override protected AppCompatButton createButton(@NonNull Context context, @NonNull AttributeSet attrs) { return new MaterialButton(context, attrs); } You can use an own inflater adding in the app theme the viewInflaterClass attribute: <style name="Theme.App" parent="Theme.MaterialComponents.*"> <item name="viewInflaterClass">com.google.android.material.theme.MaterialComponentsViewInflater</item> </style>
Why in different themes different buttons are created?
I have an usual button and a theme which is applied to android:theme in AndroidManifest file: <Button android:id="@+id/supperButton" android:layout_width="match_parent" android:layout_height="120dp" /> <style name="AppTheme" parent="Theme.AppCompat"> </style> When i inflate this button and stop the app with debugger to see what class has been created i see the following: As you can see, instead of an usual button class, AppComapatButton has been created. When i change theme to as follows: <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> </style> MaterialButton is created, instead of an usual button class or AppComapatButton: Question: as i can gather, themes can define what exactly type of a widget is used. So what exactly does define it? Maybe there is some attribute in a theme that does it ?
[ "It happens if your Activity extends AppCompatActivity.\nThe AppCompatActivity calls the setFactory2 method using a custom implementation of LayoutInflater.\nThis implementation is done by the AppCompatViewInflater\nwhich checks the names of the views in the layout and automatically \"substitutes\" all usages of core Android widgets inflated from layout files by the AppCompat extensions of those widgets.\nYou can check in the source code:\n@Nullable\npublic final View createView(/**...*/) {\n //...\n switch (name) {\n case \"Button\":\n view = createButton(context, attrs);\n verifyNotNull(view, name);\n break;\n //...\n}\n\n@NonNull\nprotected AppCompatButton createButton(Context context, AttributeSet attrs) {\n return new AppCompatButton(context, attrs);\n}\n\nIn the MaterialComponents theme is defined another implemetantion, the MaterialComponentsViewInflater.\nFor example you can check in the source code:\n@Override\n protected AppCompatButton createButton(@NonNull Context context, @NonNull AttributeSet attrs) {\n return new MaterialButton(context, attrs);\n }\n\nYou can use an own inflater adding in the app theme the viewInflaterClass attribute:\n <style name=\"Theme.App\" parent=\"Theme.MaterialComponents.*\">\n <item name=\"viewInflaterClass\">com.google.android.material.theme.MaterialComponentsViewInflater</item>\n </style>\n\n" ]
[ 0 ]
[]
[]
[ "android", "android_appcompat", "android_button", "material_components_android" ]
stackoverflow_0074476228_android_android_appcompat_android_button_material_components_android.txt
Q: Remove first day of data from multiple tracked individuals I have a database of many individuals that have been tracked for a long time and I'm trying to remove the first 24h of data for each one of them. This is done to remove data on potentially unnatural behaviour as a result of manipulation during the tagging process in future analyses. It has been tricky to solve because many have different starting dates. Thanks. My data is basically looks like this: datetime Ind Lat Long 2019-04-02 08:54:03 Animal_1 Y X 2019-04-02 09:01:13 Animal_2 Y X 2019-04-02 15:45:22 Animal_1 Y X 2019-04-03 17:31:50 Animal_1 Y X 2019-04-03 21:24:38 Animal_1 Y X 2019-04-04 00:01:24 Animal_1 Y X 2019-04-04 00:01:24 Animal_1 Y X 2019-04-05 03:32:56 Animal_1 Y X 2019-04-05 18:42:07 Animal_3 Y X 2019-04-06 17:16:24 Animal_1 Y X . . . 2021-10-14 12:34:56 Animal_1 Y X 2021-10-15 16:05:50 Animal_20 Y X 2021-10-15 22:29:37 Animal_15 Y X I have tried adapting code I've found in other relatively similar questions but haven't succeeded.. A: How about something like this: library(dplyr) library(lubridate) dat %>% arrange(Ind, datetime) %>% group_by(Ind) %>% filter(datetime > min(datetime) + hours(24))
Remove first day of data from multiple tracked individuals
I have a database of many individuals that have been tracked for a long time and I'm trying to remove the first 24h of data for each one of them. This is done to remove data on potentially unnatural behaviour as a result of manipulation during the tagging process in future analyses. It has been tricky to solve because many have different starting dates. Thanks. My data is basically looks like this: datetime Ind Lat Long 2019-04-02 08:54:03 Animal_1 Y X 2019-04-02 09:01:13 Animal_2 Y X 2019-04-02 15:45:22 Animal_1 Y X 2019-04-03 17:31:50 Animal_1 Y X 2019-04-03 21:24:38 Animal_1 Y X 2019-04-04 00:01:24 Animal_1 Y X 2019-04-04 00:01:24 Animal_1 Y X 2019-04-05 03:32:56 Animal_1 Y X 2019-04-05 18:42:07 Animal_3 Y X 2019-04-06 17:16:24 Animal_1 Y X . . . 2021-10-14 12:34:56 Animal_1 Y X 2021-10-15 16:05:50 Animal_20 Y X 2021-10-15 22:29:37 Animal_15 Y X I have tried adapting code I've found in other relatively similar questions but haven't succeeded..
[ "How about something like this:\nlibrary(dplyr) \nlibrary(lubridate)\ndat %>% \n arrange(Ind, datetime) %>% \n group_by(Ind) %>% \n filter(datetime > min(datetime) + hours(24))\n\n" ]
[ 0 ]
[]
[]
[ "data_cleaning", "filter", "r" ]
stackoverflow_0074680650_data_cleaning_filter_r.txt
Q: Terrain long distance object draw blue tint / fog Unity I have a basic 1000x1000 Terrain inside a very basic scene (almost empty) but the rendering for long distance is providing like a blue tint or like some fog : The Terrain settings : I tried increase all LODs or distances I found, even on the Camera object. How can I get rid of this ? A: Check if you have deferred fog enabled in the Lighting settings, as it typically fades scenery far from the camera. There's also a setting for fog in other settings which may be the culprit.
Terrain long distance object draw blue tint / fog Unity
I have a basic 1000x1000 Terrain inside a very basic scene (almost empty) but the rendering for long distance is providing like a blue tint or like some fog : The Terrain settings : I tried increase all LODs or distances I found, even on the Camera object. How can I get rid of this ?
[ "Check if you have deferred fog enabled in the Lighting settings, as it typically fades scenery far from the camera. There's also a setting for fog in other settings which may be the culprit.\n" ]
[ 0 ]
[]
[]
[ "fog", "terrain", "unity3d", "unity3d_terrain" ]
stackoverflow_0074680023_fog_terrain_unity3d_unity3d_terrain.txt
Q: Matplotlib: Draw second y-axis with different length I'm trying to make a matplotlib plot with a second y-axis. This works so far, but I was wondering, wether it was possible to shorten the second y-axis? Furthermore, I struggle on some other formatting issues. a) I want to draw an arrow on the second y-axis, just as drawn on the first y-axis. b) I want to align the second y-axis at -1, so that the intersection of x- and 2nd y-axis is at(...; -1) c) The x-axis crosses the x- and y-ticks at the origin, which I want to avoid. d) How can I get a common legend for both y-axis? Here is my code snippet so far. fig, ax = plt.subplots() bx = ax.twinx() # 2nd y-axis ax.spines['bottom'].set_position(('data',0)) ax.spines['left'].set_position(('data',0)) ax.xaxis.set_ticks_position('bottom') bx.spines['left'].set_position(('data',-1)) bx.spines['bottom'].set_position(('data',-1)) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) bx.spines["top"].set_visible(False) bx.spines["bottom"].set_visible(False) bx.spines["left"].set_visible(False) ## Graphs x_val = np.arange(0,10) y_val = 0.1*x_val ax.plot(x_val, y_val, 'k--') bx.plot(x_val, -y_val+1, color = 'purple') ## Arrows ms=2 #ax.plot(1, 0, ">k", ms=ms, transform=ax.get_yaxis_transform(), clip_on=False) ax.plot(0, 1, "^k", ms=ms, transform=ax.get_xaxis_transform(), clip_on=False) bx.plot(1, 1, "^k", ms=ms, transform=bx.get_xaxis_transform(), clip_on=False) plt.ylim((-1, 1.2)) bx.set_yticks([-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5]) ## Legend ax.legend([r'$A_{hull}$'], frameon=False, loc='upper left', bbox_to_anchor=(0.2, .75)) plt.show() I've uploaded a screenshot of my plot so far, annotating the questioned points. EDIT: I've changed the plotted values in the code snippet so that the example is easier to reproduce. However, the question is more or less only related to formatting issues so that the acutual values are not too important. Image is not changed, so don't be surprised when plotting the edited values, the graphs will look differently. A: To avoid the strange overlap at x=0 and y=0, you could leave out the calls to ax.spines[...].set_position(('data',0)). You can change the transforms that place the arrows. Explicitly setting the x and y limits to start at 0 will also have the spines at those positions. ax2.set_bounds(...) shortens the right y-axis. To put items in the legend, each plotted item needs a label. get_legend_handles_labels can fetch the handles and labels of both axes, which can be combined in a new legend. Renaming bx to something like ax2 makes the code easier to compare with existing example code. In matplotlib it often also helps to first put the plotting code and only later changes to limits, ticks and embellishments. import matplotlib.pyplot as plt import pandas as pd import numpy as np fig, ax = plt.subplots() ax2 = ax.twinx() # 2nd y-axis ## Graphs x_val = np.arange(0, 10) y_val = 0.1 * x_val ax.plot(x_val, y_val, 'k--', label=r'$A_{hull}$') ax2.plot(x_val, -y_val + 1, color='purple', label='right axis') ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax2.spines["top"].set_visible(False) ax2.spines["bottom"].set_visible(False) ax2.spines["left"].set_visible(False) ax2_upper_bound = 0.55 ax2.spines["right"].set_bounds(-1, ax2_upper_bound) # shorten the right y-axis ## add arrows to spines ms = 2 # ax.plot(1, 0, ">k", ms=ms, transform=ax.get_yaxis_transform(), clip_on=False) ax.plot(0, 1, "^k", ms=ms, transform=ax.transAxes, clip_on=False) ax2.plot(1, ax2_upper_bound, "^k", ms=ms, transform=ax2.get_yaxis_transform(), clip_on=False) # set limits to the axes ax.set_xlim(xmin=0) ax.set_ylim(ymin=0) ax2.set_ylim((-1, 1.2)) ax2.set_yticks(np.arange(-1, 0.5001, 0.25)) ## Legend handles1, labels1 = ax.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() ax.legend(handles1 + handles2, labels1 + labels2, frameon=False, loc='upper left', bbox_to_anchor=(0.2, .75)) plt.show()
Matplotlib: Draw second y-axis with different length
I'm trying to make a matplotlib plot with a second y-axis. This works so far, but I was wondering, wether it was possible to shorten the second y-axis? Furthermore, I struggle on some other formatting issues. a) I want to draw an arrow on the second y-axis, just as drawn on the first y-axis. b) I want to align the second y-axis at -1, so that the intersection of x- and 2nd y-axis is at(...; -1) c) The x-axis crosses the x- and y-ticks at the origin, which I want to avoid. d) How can I get a common legend for both y-axis? Here is my code snippet so far. fig, ax = plt.subplots() bx = ax.twinx() # 2nd y-axis ax.spines['bottom'].set_position(('data',0)) ax.spines['left'].set_position(('data',0)) ax.xaxis.set_ticks_position('bottom') bx.spines['left'].set_position(('data',-1)) bx.spines['bottom'].set_position(('data',-1)) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) bx.spines["top"].set_visible(False) bx.spines["bottom"].set_visible(False) bx.spines["left"].set_visible(False) ## Graphs x_val = np.arange(0,10) y_val = 0.1*x_val ax.plot(x_val, y_val, 'k--') bx.plot(x_val, -y_val+1, color = 'purple') ## Arrows ms=2 #ax.plot(1, 0, ">k", ms=ms, transform=ax.get_yaxis_transform(), clip_on=False) ax.plot(0, 1, "^k", ms=ms, transform=ax.get_xaxis_transform(), clip_on=False) bx.plot(1, 1, "^k", ms=ms, transform=bx.get_xaxis_transform(), clip_on=False) plt.ylim((-1, 1.2)) bx.set_yticks([-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5]) ## Legend ax.legend([r'$A_{hull}$'], frameon=False, loc='upper left', bbox_to_anchor=(0.2, .75)) plt.show() I've uploaded a screenshot of my plot so far, annotating the questioned points. EDIT: I've changed the plotted values in the code snippet so that the example is easier to reproduce. However, the question is more or less only related to formatting issues so that the acutual values are not too important. Image is not changed, so don't be surprised when plotting the edited values, the graphs will look differently.
[ "To avoid the strange overlap at x=0 and y=0, you could leave out the calls to ax.spines[...].set_position(('data',0)). You can change the transforms that place the arrows. Explicitly setting the x and y limits to start at 0 will also have the spines at those positions.\nax2.set_bounds(...) shortens the right y-axis.\nTo put items in the legend, each plotted item needs a label. get_legend_handles_labels can fetch the handles and labels of both axes, which can be combined in a new legend.\nRenaming bx to something like ax2 makes the code easier to compare with existing example code. In matplotlib it often also helps to first put the plotting code and only later changes to limits, ticks and embellishments.\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfig, ax = plt.subplots()\nax2 = ax.twinx() # 2nd y-axis\n\n## Graphs\nx_val = np.arange(0, 10)\ny_val = 0.1 * x_val\nax.plot(x_val, y_val, 'k--', label=r'$A_{hull}$')\nax2.plot(x_val, -y_val + 1, color='purple', label='right axis')\n\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\nax2.spines[\"top\"].set_visible(False)\nax2.spines[\"bottom\"].set_visible(False)\nax2.spines[\"left\"].set_visible(False)\nax2_upper_bound = 0.55\nax2.spines[\"right\"].set_bounds(-1, ax2_upper_bound) # shorten the right y-axis\n\n## add arrows to spines\nms = 2\n# ax.plot(1, 0, \">k\", ms=ms, transform=ax.get_yaxis_transform(), clip_on=False)\nax.plot(0, 1, \"^k\", ms=ms, transform=ax.transAxes, clip_on=False)\nax2.plot(1, ax2_upper_bound, \"^k\", ms=ms, transform=ax2.get_yaxis_transform(), clip_on=False)\n\n# set limits to the axes\nax.set_xlim(xmin=0)\nax.set_ylim(ymin=0)\nax2.set_ylim((-1, 1.2))\nax2.set_yticks(np.arange(-1, 0.5001, 0.25))\n\n## Legend\nhandles1, labels1 = ax.get_legend_handles_labels()\nhandles2, labels2 = ax2.get_legend_handles_labels()\nax.legend(handles1 + handles2, labels1 + labels2, frameon=False,\n loc='upper left', bbox_to_anchor=(0.2, .75))\n\nplt.show()\n\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074677995_matplotlib_python.txt
Q: How to test best that my code delivers Graphviz conform dot file? After wasting time just to realise that my problem was a badly produced DOT file from my code: What is the best way to check that my created string is valid a DOT input graph in a Jest test environment for Javascript? A: use the graphlib package and its read method. This method takes a string as input and returns a graph object. You can then use the isDag method on the graph object to check if the input string represents a directed acyclic graph. const { isValid } = require('dot-check'); const input = digraph { a -> b -> c }; const result = isValid(input); expect(result).toBe(true);
How to test best that my code delivers Graphviz conform dot file?
After wasting time just to realise that my problem was a badly produced DOT file from my code: What is the best way to check that my created string is valid a DOT input graph in a Jest test environment for Javascript?
[ "use the graphlib package and its read method. This method takes a string as input and returns a graph object. You can then use the isDag method on the graph object to check if the input string represents a directed acyclic graph.\nconst { isValid } = require('dot-check');\n\nconst input = digraph { a -> b -> c };\n\nconst result = isValid(input);\n\nexpect(result).toBe(true);\n\n" ]
[ 3 ]
[]
[]
[ "graphviz", "javascript", "jestjs" ]
stackoverflow_0074680724_graphviz_javascript_jestjs.txt
Q: Why can't a weak_ptr be constructed from a unique_ptr? If I understand correctly, a weak_ptr doesn't increment the reference count of the managed object, therefore it doesn't represent ownership. It simply lets you access an object, the lifetime of which is managed by someone else. So I don't really see why a weak_ptr can't be constructed from a unique_ptr, but only a shared_ptr. Can someone briefly explain this? A: If you think about it, a weak_ptr must refer to something other than the object itself. That's because the object can cease to exist (when there are no more strong pointers to it) and the weak_ptr still has to refer to something that contains the information that the object no longer exists. With a shared_ptr, that something is the thing that contains the reference count. But with a unique_ptr, there is no reference count, so there is no thing that contains the reference count, thus nothing to continue to exist when the object is gone. So there's nothing for a weak_ptr to refer to. There would also be no sane way to use such a weak_ptr. To use it, you'd have to have some way to guarantee that the object wasn't destroyed while you were using it. That's easy with a shared_ptr -- that's what a shared_ptr does. But how do you do that with a unique_ptr? You obviously can't have two of them, and something else must already own the object or it would have been destroyed since your pointer is weak. A: std::weak_ptr can't be used unless you convert it to std::shared_ptr by the means of lock(). if the standard allowed what you suggest, that means that you need to convert std::weak_ptr to unique in order to use it, violating the uniqueness (or re-inventing std::shared_ptr) In order to illustrate, look at the two pieces of code: std::shared_ptr<int> shared = std::make_shared<int>(10); std::weak_ptr<int> weak(shared); { *(weak.lock()) = 20; //OK, the temporary shared_ptr will be destroyed but the pointee-integer still has shared to keep it alive } Now with your suggestion: std::unique_ptr<int> unique = std::make_unique<int>(10); std::weak_ptr<int> weak(unique); { *(weak.lock()) = 20; //not OK. the temporary unique_ptr will be destroyed but unique still points at it! } That has been said, you may suggest that there is only one unique_ptr, and you still can dereference weak_ptr (without creating another unique_ptr) then there is no problem. But then what is the difference between unique_ptr and shared_ptr with one reference? or moreover, what is the difference between a regular unique_ptr and C-pointers an get by using get? weak_ptr is not for "general nonowning resources", it has a very specific job - The main goal of weak_ptr is to prevent circular pointing of shared_ptr which will make a memory leak. Anything else needs to be done with plain unique_ptr and shared_ptr. A: A shared_ptr basically has two parts: the pointed-to object the reference count object Once the reference count drops to zero the object (#1) is deleted. The weak_ptr needs to be able to know if the object (#1) still exists. In order to do this, it has to be able to see the reference count object (#2), if it's not zero it can create a shared_ptr for the object (by incrementing the reference count). If the count is zero it will return an empty shared_ptr. Consider the question of when can the reference count object (#2) be deleted? We must wait until no shared_ptr OR weak_ptr object refer to it. For this purpose the reference count object holds two reference counts, a strong ref and a weak ref. The reference count object will only be deleted when both these counts are zero. This means that part of the memory can only be freed after all the weak references are gone (this implies a hidden disadvantage with make_shared). tl;dr; weak_ptr depends on a weak reference count which is part of shared_ptr, there cannot be a weak_ptr without a shared_ptr. A: Conceptually, there is nothing preventing an implementation where a weak_ptr only provides access and a unique_ptr controls the lifetime. However, there are problems with that: unique_ptr doesn't use reference counting to begin with. Adding the management structure for managing the weak references would be possible, but require an additional dynamic allocation. Since unique_ptr is supposed to avoid any(!) runtime overhead over a raw pointer, that overhead is not acceptable. In order to use the object referenced by a weak_ptr, you need to extract a "real" reference from it, which will first validate that the pointer is not expired first and then give you this real reference (a shared_ptr in this case). This means that you suddenly have a second reference to an object that is supposed to be uniquely owned, which is a recipe for errors. This can't be fixed by returning a mixed half-strong pointer that only temporarily delays possible destruction of the pointee, because you could just as well store that one, too, defeating the idea behind unique_ptr. Just wondering, what problem are you trying to solve using a weak_ptr here? A: Looks like everyone is writing here about std::weak_ptr but not about weak poiner concept which I believe is what the author is asking for I think that no one mentioned why standard library is not providing weak_ptr for unique_ptr. Weak pointer CONCEPT doesn't disclaims unique_ptr usage. Weak pointer is only an information if the object has been already deleted so it's not a magic but very simple generalized observer pattern. It's because of threadsafety and consistency with shared_ptr. You just simply can't guarantee that your weak_ptr (created from unique_ptr existing on other thread) will be not destroyed during calling method on pointed object. It's because weak_ptr needs to be consistent with std::shared_ptr which guarantee threadsafety. You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case. You can check chromium sources for base::WeakPtr and base::WeakPtrFactory - you can use it freely with unique_ptr. Chromium weak pointer code is most probably based on last member destruction - you need to add factory as a last member and after that I believe that WeakPtr is informed abut object deleteion (I'm not 100% sure) - so it doesn't looks so hard to implement. Overall using unique_ptr with weak pointer concept is OK IMHO. A: No-one has mentioned the performance aspect of the problem yet, so let me throw my $0.02 in. weak_ptr must somehow know when the corresponding shared_ptrs have all gone out of scope and the pointed object has been deallocated and destroyed. This means that shared_ptrs need to communicate the destruction towards each weak_ptr to the same object somehow. This has a certain cost – for example, a global hash table needs to be updated, where weak_ptr gets the address from (or nullptr if the object is destroyed). This also involves locking in a multi-threaded environment, so it can potentially be too slow for some tasks. However, the goal of unique_ptr is to provide a zero-cost RAII-style abstraction class. Hence, it should not incur any other cost than that of deleteing (or delete[]ing) the dynamically allocated object. The delay imposed by doing a locked or otherwise guarded hash table access, for example, may be comparable to the cost of deallocation, however, which is not desirable in the case of unique_ptr. A: It may be useful to distinguish reasons for preferring a unique_ptr over a shared_ptr. Performance One obvious reason is computational-time and memory use. As currently defined, shared_ptr objects typically need something like a reference-count value, which takes space and also must be actively maintained. unique_ptr objects don't. Semantics With a unique_ptr, you as the programmer have a pretty good idea when the pointed-to object is going to be destroyed: when the unique_ptr is destroyed or when one of its modifying methods is called. And so on large or unfamiliar code bases, using unique_ptr statically conveys (and enforces) some information about the program's runtime behavior that might not be obvious. The comments above have generally focused on the performance-based reasons that it would be undesirable for weak_ptr objects to be tied to unique_ptr objects. But one might wonder if the semantics-based argument is sufficient reason for some future version of the STL to support the use-case implied by the original question. A: After many years of c++ programing works, i finally realized that the correct way in c++ world is not to use shared_ptr/weak_ptr for ever. We have spent so many time to fix the bugs caused by the unclear ownership of share_ptr. The solution is to use unque_ptr and some weak pointer for unique_ptr instead, just as what's expected in this topic. cpp standard library has no weak pointer for unique_ptr, so i create a very simple, but useful libary here -- https://github.com/xhawk18/noshared_ptr It has two new smart pointers, noshared_ptr<T>, a new kind of unique_ptr noweak_ptr<T>, the weak pointer for noshare_ptr<T> A: I demonstrated the problem to myself with a MWE implementing weak_ptr on single objects. (I implement it on X here, but X can be anything that can tell us when it dies, such as a unique_ptr with a custom deleter). The ultimate problem however is that at some point we need reference counting on the weak pointers themselves, because while X is not shared, the weak pointers are shared. This takes us full circle back to using shared_ptr again. Perhaps the only advantage of doing this is that the intent of single ownership is clearer and cannot be violated, however, as Stroustrup suggests and is quoted this answer, this can be hinted at with the using statement. #include <iostream> #include <memory> template<typename T> struct ControlBlock { T* Target; explicit ControlBlock(T* target) : Target(target) {} }; template<typename T> struct WeakReference { std::shared_ptr<ControlBlock<T>> ControlBlock; T* Get() { return ControlBlock ? ControlBlock->Target : nullptr; } }; template<typename T> struct WeakReferenceRoot { WeakReference<T> _weakRef; WeakReferenceRoot(T* target) : _weakRef{std::make_shared<ControlBlock<T>>(target)} { } const WeakReference<T>& GetReference() { return _weakRef; } ~WeakReferenceRoot() { _weakRef.ControlBlock->Target = nullptr; } }; struct Customer { WeakReferenceRoot<Customer> Weak{this}; }; int main() { WeakReference<Customer> someRef; std::cout << "BEFORE SCOPE - WEAK REFERENCE IS " << someRef.Get() << "\n"; { Customer obj{}; someRef = obj.Weak.GetReference(); std::cout << "IN SCOPE - WEAK REFERENCE IS " << someRef.Get() << "\n"; } std::cout << "OUT OF SCOPE - WEAK REFERENCE IS " << someRef.Get() << "\n"; return 0; } A: Sadly as with many cases - cause the C++ committee just didn't care and dismissed such usecases. How it is: weak_ptr was specified in terms of shared-pointer, precluding any attempts at making it a more broadly useful smart-pointer. In C++ conceptually a weak-ptr is a non-owning pointer that MUST be converted to a shared_ptr to access the underlying object. And as a unique_ptr does not support any sort of reference-counting (as it is the unique owner by definition) converting a weak_ptr to a pointer with any sort of ownership is not allowed. It is sadly a bit too late to get good well-named smart-pointers that offer a bit more generality. But you can create something like that: To make it safe you would need your own deleter (unique_ptr has the deleter in the type), and a new non-owning unique_ptr_observer that changes the deleter. When creating an observer it would register a cleanup-handler as the deleter. That way you can have a unique_ptr_observer that can check if the Threadsafety would still be a problem as you would need either a locking-mechanism, create copies for readout, or some other way to prevent the pointer from getting deleted while you are actively looking at it. (it is so annoying that the deleter is part of the type.......)
Why can't a weak_ptr be constructed from a unique_ptr?
If I understand correctly, a weak_ptr doesn't increment the reference count of the managed object, therefore it doesn't represent ownership. It simply lets you access an object, the lifetime of which is managed by someone else. So I don't really see why a weak_ptr can't be constructed from a unique_ptr, but only a shared_ptr. Can someone briefly explain this?
[ "If you think about it, a weak_ptr must refer to something other than the object itself. That's because the object can cease to exist (when there are no more strong pointers to it) and the weak_ptr still has to refer to something that contains the information that the object no longer exists.\nWith a shared_ptr, that something is the thing that contains the reference count. But with a unique_ptr, there is no reference count, so there is no thing that contains the reference count, thus nothing to continue to exist when the object is gone. So there's nothing for a weak_ptr to refer to.\nThere would also be no sane way to use such a weak_ptr. To use it, you'd have to have some way to guarantee that the object wasn't destroyed while you were using it. That's easy with a shared_ptr -- that's what a shared_ptr does. But how do you do that with a unique_ptr? You obviously can't have two of them, and something else must already own the object or it would have been destroyed since your pointer is weak.\n", "std::weak_ptr can't be used unless you convert it to std::shared_ptr by the means of lock(). if the standard allowed what you suggest, that means that you need to convert std::weak_ptr to unique in order to use it, violating the uniqueness (or re-inventing std::shared_ptr)\nIn order to illustrate, look at the two pieces of code:\nstd::shared_ptr<int> shared = std::make_shared<int>(10);\nstd::weak_ptr<int> weak(shared);\n\n{\n*(weak.lock()) = 20; //OK, the temporary shared_ptr will be destroyed but the pointee-integer still has shared to keep it alive\n}\n\nNow with your suggestion:\nstd::unique_ptr<int> unique = std::make_unique<int>(10);\nstd::weak_ptr<int> weak(unique);\n\n{\n*(weak.lock()) = 20; //not OK. the temporary unique_ptr will be destroyed but unique still points at it! \n}\n\nThat has been said, you may suggest that there is only one unique_ptr, and you still can dereference weak_ptr (without creating another unique_ptr) then there is no problem. But then what is the difference between unique_ptr and shared_ptr with one reference? or moreover, what is the difference between a regular unique_ptr and C-pointers an get by using get? \nweak_ptr is not for \"general nonowning resources\", it has a very specific job - The main goal of weak_ptr is to prevent circular pointing of shared_ptr which will make a memory leak. Anything else needs to be done with plain unique_ptr and shared_ptr.\n", "A shared_ptr basically has two parts:\n\nthe pointed-to object\nthe reference count object\n\nOnce the reference count drops to zero the object (#1) is deleted.\nThe weak_ptr needs to be able to know if the object (#1) still exists. In order to do this, it has to be able to see the reference count object (#2), if it's not zero it can create a shared_ptr for the object (by incrementing the reference count). If the count is zero it will return an empty shared_ptr.\nConsider the question of when can the reference count object (#2) be deleted? We must wait until no shared_ptr OR weak_ptr object refer to it. For this purpose the reference count object holds two reference counts, a strong ref and a weak ref. The reference count object will only be deleted when both these counts are zero. This means that part of the memory can only be freed after all the weak references are gone (this implies a hidden disadvantage with make_shared).\ntl;dr; weak_ptr depends on a weak reference count which is part of shared_ptr, there cannot be a weak_ptr without a shared_ptr.\n", "Conceptually, there is nothing preventing an implementation where a weak_ptr only provides access and a unique_ptr controls the lifetime. However, there are problems with that:\n\nunique_ptr doesn't use reference counting to begin with. Adding the management structure for managing the weak references would be possible, but require an additional dynamic allocation. Since unique_ptr is supposed to avoid any(!) runtime overhead over a raw pointer, that overhead is not acceptable.\nIn order to use the object referenced by a weak_ptr, you need to extract a \"real\" reference from it, which will first validate that the pointer is not expired first and then give you this real reference (a shared_ptr in this case). This means that you suddenly have a second reference to an object that is supposed to be uniquely owned, which is a recipe for errors. This can't be fixed by returning a mixed half-strong pointer that only temporarily delays possible destruction of the pointee, because you could just as well store that one, too, defeating the idea behind unique_ptr.\n\nJust wondering, what problem are you trying to solve using a weak_ptr here?\n", "Looks like everyone is writing here about std::weak_ptr but not about weak poiner concept which I believe is what the author is asking for\nI think that no one mentioned why standard library is not providing weak_ptr for unique_ptr. Weak pointer CONCEPT doesn't disclaims unique_ptr usage. Weak pointer is only an information if the object has been already deleted so it's not a magic but very simple generalized observer pattern.\nIt's because of threadsafety and consistency with shared_ptr.\nYou just simply can't guarantee that your weak_ptr (created from unique_ptr existing on other thread) will be not destroyed during calling method on pointed object. \nIt's because weak_ptr needs to be consistent with std::shared_ptr which guarantee threadsafety. You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case. You can check chromium sources for base::WeakPtr and base::WeakPtrFactory - you can use it freely with unique_ptr. \nChromium weak pointer code is most probably based on last member destruction - you need to add factory as a last member and after that I believe that WeakPtr is informed abut object deleteion (I'm not 100% sure) - so it doesn't looks so hard to implement. \nOverall using unique_ptr with weak pointer concept is OK IMHO. \n", "No-one has mentioned the performance aspect of the problem yet, so let me throw my $0.02 in.\nweak_ptr must somehow know when the corresponding shared_ptrs have all gone out of scope and the pointed object has been deallocated and destroyed. This means that shared_ptrs need to communicate the destruction towards each weak_ptr to the same object somehow. This has a certain cost – for example, a global hash table needs to be updated, where weak_ptr gets the address from (or nullptr if the object is destroyed).\nThis also involves locking in a multi-threaded environment, so it can potentially be too slow for some tasks.\nHowever, the goal of unique_ptr is to provide a zero-cost RAII-style abstraction class. Hence, it should not incur any other cost than that of deleteing (or delete[]ing) the dynamically allocated object. The delay imposed by doing a locked or otherwise guarded hash table access, for example, may be comparable to the cost of deallocation, however, which is not desirable in the case of unique_ptr.\n", "It may be useful to distinguish reasons for preferring a unique_ptr over a shared_ptr.\nPerformance One obvious reason is computational-time and memory use. As currently defined, shared_ptr objects typically need something like a reference-count value, which takes space and also must be actively maintained. unique_ptr objects don't.\nSemantics With a unique_ptr, you as the programmer have a pretty good idea when the pointed-to object is going to be destroyed: when the unique_ptr is destroyed or when one of its modifying methods is called. And so on large or unfamiliar code bases, using unique_ptr statically conveys (and enforces) some information about the program's runtime behavior that might not be obvious.\nThe comments above have generally focused on the performance-based reasons that it would be undesirable for weak_ptr objects to be tied to unique_ptr objects. But one might wonder if the semantics-based argument is sufficient reason for some future version of the STL to support the use-case implied by the original question.\n", "After many years of c++ programing works, i finally realized that the correct way in c++ world is not to use shared_ptr/weak_ptr for ever. We have spent so many time to fix the bugs caused by the unclear ownership of share_ptr.\nThe solution is to use unque_ptr and some weak pointer for unique_ptr instead, just as what's expected in this topic.\ncpp standard library has no weak pointer for unique_ptr, so i create a very simple, but useful libary here --\nhttps://github.com/xhawk18/noshared_ptr\nIt has two new smart pointers,\nnoshared_ptr<T>, a new kind of unique_ptr\nnoweak_ptr<T>, the weak pointer for noshare_ptr<T>\n\n", "I demonstrated the problem to myself with a MWE implementing weak_ptr on single objects. (I implement it on X here, but X can be anything that can tell us when it dies, such as a unique_ptr with a custom deleter).\nThe ultimate problem however is that at some point we need reference counting on the weak pointers themselves, because while X is not shared, the weak pointers are shared. This takes us full circle back to using shared_ptr again.\nPerhaps the only advantage of doing this is that the intent of single ownership is clearer and cannot be violated, however, as Stroustrup suggests and is quoted this answer, this can be hinted at with the using statement.\n#include <iostream>\n#include <memory>\n\ntemplate<typename T>\nstruct ControlBlock\n{\n T* Target;\n explicit ControlBlock(T* target) : Target(target) {}\n};\n\ntemplate<typename T>\nstruct WeakReference\n{\n std::shared_ptr<ControlBlock<T>> ControlBlock;\n T* Get() { return ControlBlock ? ControlBlock->Target : nullptr; }\n};\n\ntemplate<typename T>\nstruct WeakReferenceRoot\n{\n WeakReference<T> _weakRef;\n WeakReferenceRoot(T* target) : _weakRef{std::make_shared<ControlBlock<T>>(target)} { }\n const WeakReference<T>& GetReference() { return _weakRef; }\n ~WeakReferenceRoot() { _weakRef.ControlBlock->Target = nullptr; }\n};\n\nstruct Customer\n{\n WeakReferenceRoot<Customer> Weak{this};\n};\n\nint main() {\n WeakReference<Customer> someRef;\n std::cout << \"BEFORE SCOPE - WEAK REFERENCE IS \" << someRef.Get() << \"\\n\";\n {\n Customer obj{};\n someRef = obj.Weak.GetReference();\n std::cout << \"IN SCOPE - WEAK REFERENCE IS \" << someRef.Get() << \"\\n\";\n }\n std::cout << \"OUT OF SCOPE - WEAK REFERENCE IS \" << someRef.Get() << \"\\n\";\n return 0;\n}\n\n", "Sadly as with many cases - cause the C++ committee just didn't care and dismissed such usecases.\nHow it is:\nweak_ptr was specified in terms of shared-pointer, precluding any attempts at making it a more broadly useful smart-pointer. In C++ conceptually a weak-ptr is a non-owning pointer that MUST be converted to a shared_ptr to access the underlying object. And as a unique_ptr does not support any sort of reference-counting (as it is the unique owner by definition) converting a weak_ptr to a pointer with any sort of ownership is not allowed.\nIt is sadly a bit too late to get good well-named smart-pointers that offer a bit more generality.\nBut you can create something like that:\nTo make it safe you would need your own deleter (unique_ptr has the deleter in the type), and a new non-owning unique_ptr_observer that changes the deleter. When creating an observer it would register a cleanup-handler as the deleter. That way you can have a unique_ptr_observer that can check if the Threadsafety would still be a problem as you would need either a locking-mechanism, create copies for readout, or some other way to prevent the pointer from getting deleted while you are actively looking at it.\n(it is so annoying that the deleter is part of the type.......)\n" ]
[ 37, 29, 15, 10, 6, 4, 0, 0, 0, 0 ]
[]
[]
[ "c++", "shared_ptr", "smart_pointers", "unique_ptr", "weak_ptr" ]
stackoverflow_0029059343_c++_shared_ptr_smart_pointers_unique_ptr_weak_ptr.txt
Q: Confused With "TypeError: '<=' not supported between instances of 'int' and 'str'" I tried making a random password generator and it gave me this error. Here is my source code It says the problem is at | password="".join(random.sample(characters,USER_INP)) #Variables import random import tkinter from tkinter import simpledialog characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890" USER_INP = simpledialog.askstring(title="Secure Password Gen", prompt="How many characters do you want your password to be? *password will be in Terminal*") password="".join(random.sample(characters,USER_INP)) #Gui ROOT = tkinter.Tk() ROOT.withdraw() #Password Generator print("The Password is: ", password) tried to add password="".joinint(random.sample(characters,USER_INP)) A: To use tkinter.simpledialog.askstring, random.choices, and a string of acceptable password characters to generate a random password of a length requested by the user in Python, you can use the following code: import tkinter as tk from tkinter import simpledialog import random # Create a string containing all the acceptable password characters password_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*" # Use the askstring function from the simpledialog module to ask the user for the password length root = tk.Tk() root.withdraw() password_length = simpledialog.askstring("Input", "Enter password length:") # Use the random.choices function to generate a random password of the requested length password = "".join(random.choices(password_chars, k=password_length)) # Print the generated password to the console print(password) This code will use tkinter.simpledialog.askstring to ask the user for the desired password length - it must cast this str input to an int type. It will then use the random.choices function to generate a random password of the requested length, using the string of acceptable password characters as the source of possible characters. Finally, it will print the generated password to the console. The part which your code is missing is the casting from string to integer when the user enters their desired length.
Confused With "TypeError: '<=' not supported between instances of 'int' and 'str'"
I tried making a random password generator and it gave me this error. Here is my source code It says the problem is at | password="".join(random.sample(characters,USER_INP)) #Variables import random import tkinter from tkinter import simpledialog characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$1234567890" USER_INP = simpledialog.askstring(title="Secure Password Gen", prompt="How many characters do you want your password to be? *password will be in Terminal*") password="".join(random.sample(characters,USER_INP)) #Gui ROOT = tkinter.Tk() ROOT.withdraw() #Password Generator print("The Password is: ", password) tried to add password="".joinint(random.sample(characters,USER_INP))
[ "To use tkinter.simpledialog.askstring, random.choices, and a string of acceptable password characters to generate a random password of a length requested by the user in Python, you can use the following code:\nimport tkinter as tk\nfrom tkinter import simpledialog\nimport random\n\n# Create a string containing all the acceptable password characters\npassword_chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*\"\n\n# Use the askstring function from the simpledialog module to ask the user for the password length\nroot = tk.Tk()\nroot.withdraw()\npassword_length = simpledialog.askstring(\"Input\", \"Enter password length:\")\n\n# Use the random.choices function to generate a random password of the requested length\npassword = \"\".join(random.choices(password_chars, k=password_length))\n\n# Print the generated password to the console\nprint(password)\n\nThis code will use tkinter.simpledialog.askstring to ask the user for the desired password length - it must cast this str input to an int type. It will then use the random.choices function to generate a random password of the requested length, using the string of acceptable password characters as the source of possible characters. Finally, it will print the generated password to the console.\nThe part which your code is missing is the casting from string to integer when the user enters their desired length.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074680657_python.txt
Q: Using OpenGl code to the FreeCAD COIN3D scene? I would like to be able to use OpenGL inside the QuarterWidget, FreeCAD use to glue Coin3D to OpenCascade scene. I can retrieve the following objects via python: def GetQuarterWidget(self): #From FreeCAD forum views = [] self.mainWindow=Gui.getMainWindow() for w in self.mainWindow.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): if w.inherits("SIM::Coin3D::Quarter::QuarterWidget"): views.append(w) return views def getMdiWindow(self) #From FreeCAD forum mw = Gui.getMainWindow() mdi = mw.findChild(PySide2.QtWidgets.QMdiArea) but I don't know how to be able to draw to the scene using OpenGL code... Say hello world code (drawing only a triangle)? My goal is to be able to make a link to the scene so I can draw all my new object using OpenGL directly, not COIN3D, or using SDL2 library ..etc. I appreciate any hint to achieve that. I use python but I accept getting cpp code also. Thank you very much EDIT: I managed to draw hello world triangle inside the scene .. how good is the code? I am not sure yet. below is the code . from OpenGL.GL import * from OpenGL.GLU import * import PySide2 import FreeCADGui as Gui import pivy.coin as coin import PySide.QtCore as QtCore import PySide.QtGui as QtGui from PySide2.QtOpenGL import * #as QtOPENGL from OpenGL.WGL import * def drawOpenGl(arg1,arg2): glTranslatef(-2.5, 0.5, -6.0) glColor3f( 1.0, 1.5, 0.0 ) glPolygonMode(GL_FRONT, GL_FILL) glBegin(GL_TRIANGLES) glVertex3f(2.0,-1.2,0.0) glVertex3f(2.6,0.0,0.0) glVertex3f(2.9,-1.2,0.0) glEnd() def drawsomething(): w_view = Gui.ActiveDocument.ActiveView Root_SceneGraph = w_view.getSceneGraph() calback_=coin.SoCallback() calback_.setCallback(drawOpenGl) Root_SceneGraph.addChild(calback_) drawsomething() please notice that you need to install pyopengl inside freecad (not your pc/linux/mac version of pip or python) by running FreeCAD's python. FREECAD_DIR/bin/Scripts/pip install pyopengl A: Your code looks very similar to the sample in the Invertor Mentor book. I think you should store current state with glPushMatrix and glPopMatrix. Otherwise transformations may behave incorrectly. def drawOpenGl(arg1,arg2): glPushMatrix() glTranslatef(-2.5, 0.5, -6.0) glColor3f( 1.0, 1.5, 0.0 ) glPolygonMode(GL_FRONT, GL_FILL) glBegin(GL_TRIANGLES) glVertex3f(2.0,-1.2,0.0) glVertex3f(2.6,0.0,0.0) glVertex3f(2.9,-1.2,0.0) glEnd() glPopMatrix() Not sure if this can be useful for you in any way, but there is a C++ sample that mixes a pure OpenGL geometry (a rectangle) and a Coin3D geometry (a cone) and uses Quarter: #include <QApplication> #include <Inventor/nodes/SoBaseColor.h> #include <Inventor/nodes/SoCone.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoCallback.h> #include <Quarter/Quarter.h> #include <Quarter/QuarterWidget.h> #include <GL/gl.h> using namespace SIM::Coin3D::Quarter; // Callback routine to render using OpenGL void myCallbackRoutine(void *, SoAction *) { glPushMatrix(); glTranslatef(0.0, -3.0, 0.0); glColor3f(1.0, 0.0, 0.0); glDisable(GL_LIGHTING); // so we don't have to set normals glBegin(GL_POLYGON); glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.5, 0.0, 0.0); glVertex3f(0.5, 0.5, 0.0); glVertex3f(0.0, 0.5, 0.0); glEnd(); glEnable(GL_LIGHTING); glPopMatrix(); } int main(int argc, char ** argv) { QApplication app(argc, argv); // Initializes Quarter library (and implicitly also the Coin and Qt // libraries). Quarter::init(); // Make a dead simple scene graph by using the Coin library, only // containing a single yellow cone under the scenegraph root. SoSeparator * root = new SoSeparator; root->ref(); SoBaseColor * col = new SoBaseColor; col->rgb = SbColor(1, 1, 0); root->addChild(col); root->addChild(new SoCone); SoCallback *myCallback = new SoCallback; myCallback->setCallback(myCallbackRoutine); root->addChild(myCallback); // Create a QuarterWidget for displaying a Coin scene graph QuarterWidget * viewer = new QuarterWidget; viewer->setSceneGraph(root); // make the viewer react to input events similar to the good old // ExaminerViewer viewer->setNavigationModeFile(QUrl("coin:///scxml/navigation/examiner.xml")); // Pop up the QuarterWidget viewer->show(); // Loop until exit. app.exec(); // Clean up resources. root->unref(); delete viewer; Quarter::clean(); return 0; }
Using OpenGl code to the FreeCAD COIN3D scene?
I would like to be able to use OpenGL inside the QuarterWidget, FreeCAD use to glue Coin3D to OpenCascade scene. I can retrieve the following objects via python: def GetQuarterWidget(self): #From FreeCAD forum views = [] self.mainWindow=Gui.getMainWindow() for w in self.mainWindow.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): if w.inherits("SIM::Coin3D::Quarter::QuarterWidget"): views.append(w) return views def getMdiWindow(self) #From FreeCAD forum mw = Gui.getMainWindow() mdi = mw.findChild(PySide2.QtWidgets.QMdiArea) but I don't know how to be able to draw to the scene using OpenGL code... Say hello world code (drawing only a triangle)? My goal is to be able to make a link to the scene so I can draw all my new object using OpenGL directly, not COIN3D, or using SDL2 library ..etc. I appreciate any hint to achieve that. I use python but I accept getting cpp code also. Thank you very much EDIT: I managed to draw hello world triangle inside the scene .. how good is the code? I am not sure yet. below is the code . from OpenGL.GL import * from OpenGL.GLU import * import PySide2 import FreeCADGui as Gui import pivy.coin as coin import PySide.QtCore as QtCore import PySide.QtGui as QtGui from PySide2.QtOpenGL import * #as QtOPENGL from OpenGL.WGL import * def drawOpenGl(arg1,arg2): glTranslatef(-2.5, 0.5, -6.0) glColor3f( 1.0, 1.5, 0.0 ) glPolygonMode(GL_FRONT, GL_FILL) glBegin(GL_TRIANGLES) glVertex3f(2.0,-1.2,0.0) glVertex3f(2.6,0.0,0.0) glVertex3f(2.9,-1.2,0.0) glEnd() def drawsomething(): w_view = Gui.ActiveDocument.ActiveView Root_SceneGraph = w_view.getSceneGraph() calback_=coin.SoCallback() calback_.setCallback(drawOpenGl) Root_SceneGraph.addChild(calback_) drawsomething() please notice that you need to install pyopengl inside freecad (not your pc/linux/mac version of pip or python) by running FreeCAD's python. FREECAD_DIR/bin/Scripts/pip install pyopengl
[ "Your code looks very similar to the sample in the Invertor Mentor book. I think you should store current state with glPushMatrix and glPopMatrix. Otherwise transformations may behave incorrectly.\ndef drawOpenGl(arg1,arg2):\n glPushMatrix()\n glTranslatef(-2.5, 0.5, -6.0)\n glColor3f( 1.0, 1.5, 0.0 )\n glPolygonMode(GL_FRONT, GL_FILL)\n glBegin(GL_TRIANGLES)\n glVertex3f(2.0,-1.2,0.0)\n glVertex3f(2.6,0.0,0.0)\n glVertex3f(2.9,-1.2,0.0)\n glEnd()\n glPopMatrix()\n\nNot sure if this can be useful for you in any way, but there is a C++ sample that mixes a pure OpenGL geometry (a rectangle) and a Coin3D geometry (a cone) and uses Quarter:\n#include <QApplication>\n#include <Inventor/nodes/SoBaseColor.h>\n#include <Inventor/nodes/SoCone.h>\n#include <Inventor/nodes/SoSeparator.h>\n#include <Inventor/nodes/SoCallback.h>\n#include <Quarter/Quarter.h>\n#include <Quarter/QuarterWidget.h>\n#include <GL/gl.h>\n\nusing namespace SIM::Coin3D::Quarter;\n\n// Callback routine to render using OpenGL\nvoid\nmyCallbackRoutine(void *, SoAction *)\n{\n glPushMatrix();\n glTranslatef(0.0, -3.0, 0.0);\n glColor3f(1.0, 0.0, 0.0);\n glDisable(GL_LIGHTING); // so we don't have to set normals\n glBegin(GL_POLYGON);\n glVertex3f(0.0, 0.0, 0.0);\n glVertex3f(0.5, 0.0, 0.0);\n glVertex3f(0.5, 0.5, 0.0);\n glVertex3f(0.0, 0.5, 0.0);\n glEnd();\n glEnable(GL_LIGHTING);\n glPopMatrix();\n}\n\nint\nmain(int argc, char ** argv)\n{\n QApplication app(argc, argv);\n // Initializes Quarter library (and implicitly also the Coin and Qt\n // libraries).\n Quarter::init();\n // Make a dead simple scene graph by using the Coin library, only\n // containing a single yellow cone under the scenegraph root.\n SoSeparator * root = new SoSeparator;\n root->ref();\n SoBaseColor * col = new SoBaseColor;\n col->rgb = SbColor(1, 1, 0);\n root->addChild(col);\n root->addChild(new SoCone);\n \n SoCallback *myCallback = new SoCallback;\n myCallback->setCallback(myCallbackRoutine);\n root->addChild(myCallback);\n \n // Create a QuarterWidget for displaying a Coin scene graph\n QuarterWidget * viewer = new QuarterWidget;\n viewer->setSceneGraph(root);\n // make the viewer react to input events similar to the good old\n // ExaminerViewer\n viewer->setNavigationModeFile(QUrl(\"coin:///scxml/navigation/examiner.xml\"));\n // Pop up the QuarterWidget\n viewer->show();\n // Loop until exit.\n app.exec();\n // Clean up resources.\n root->unref();\n delete viewer;\n Quarter::clean();\n return 0;\n}\n\n" ]
[ 0 ]
[]
[]
[ "freecad", "opengl", "scene" ]
stackoverflow_0074500493_freecad_opengl_scene.txt
Q: how to make dropdown menu in tailwindcss please can any one tell me how to make dropdown menu in tailwind css i have tried everything but it does not work at all ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dropdown Menu</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <div > <ul class="bg-blue-500 flex justify-end items-center pr-[150px] space-x-10 text-white relative"> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded">Home</a></li> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded flex hover:block">Services</a> <div > <ul class=" flex hidden absolute bg-red-600 w-20 pt-20"> <li><a href="#">Web Development</a></li> <li><a href="#">Mobile Development</a></li> <li><a href="#">Game Development</a></li> </ul> </div> </li> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded">About</a></li> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded">FAQ</a></li> </ul> </div> </body> </html> ` A: You are missing javascript events to trigger the dorpdown I am guessing you are trying to work with flowbite check out their quick start doc, You can still do the native dropdown with css only like mentioned here
how to make dropdown menu in tailwindcss
please can any one tell me how to make dropdown menu in tailwind css i have tried everything but it does not work at all ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dropdown Menu</title> <script src="https://cdn.tailwindcss.com"></script> </head> <body> <div > <ul class="bg-blue-500 flex justify-end items-center pr-[150px] space-x-10 text-white relative"> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded">Home</a></li> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded flex hover:block">Services</a> <div > <ul class=" flex hidden absolute bg-red-600 w-20 pt-20"> <li><a href="#">Web Development</a></li> <li><a href="#">Mobile Development</a></li> <li><a href="#">Game Development</a></li> </ul> </div> </li> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded">About</a></li> <li><a href="#" class="hover:bg-blue-400 hover:font-bold hover:rounded">FAQ</a></li> </ul> </div> </body> </html> `
[ "You are missing javascript events to trigger the dorpdown I am guessing you are trying to work with flowbite check out their quick start doc, You can still do the native dropdown with css only like mentioned here\n" ]
[ 0 ]
[]
[]
[ "css", "drop_down_menu", "html", "tailwind_css" ]
stackoverflow_0074680592_css_drop_down_menu_html_tailwind_css.txt
Q: Django Async View - Model __str__ I'm trying to convert my existing Django 4.1 app to async due to performance reasons. It's more of a struggle than I initially anticipated. Below is some test code: async def diagrams(request): tests = await sync_to_async(list)(Test.objects.filter(name='Test 1')) print(tests) return render(request, 'analyticsApp/test.html') class Test2(models.Model): name = models.CharField(max_length=50, default='', blank=True) def __str__(self): return self.name class Test(models.Model): name = models.CharField(max_length=50, default='', blank=True) testForeignKey = models.ForeignKey(Test2, editable=True, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): # Need to get foreign key here in async way but this function cannot be async ?? return self.name + '_' + self.testForeignKey.name So I kind of figured out how to "filter" objects using async_to_async. However, a problem that I'm struggling to solve is using __str__ in a Model. All of my models use __str__ to give accurate string depcitions of the model. It seems like this cannot be done ? I tried to convert def __str__ to async def __str__ but django is not awaiting this when it is being called so it causes problems. Any idea how to handle this ? A: Probably the async don't increase your performance. In your code you work don't correct with async. Str should work with existing data, without ask to database. Therefore you should receive needed data before instance init. In your case you can made: obj = Test.objects.select_related("testForeignKey").get(**something) Also you can use defer/only. The query works async, after that you get your Str(object) normally. A: I have't used much the async support but as a work around you can use a select_related async def diagrams(request): tests = await sync_to_async(list)( Test.objects.filter(name='Test 1') .select_related('testForeignKey') ) print(tests) return render(request, 'analyticsApp/test.html') A: I think your problem here is the print(tests) That's when the query gets evaluated and at that point __str__ gets called to print the list of tests. Simply put, if you don't print them __str__ will never get called in an async context! Also the .filter just prepares the sql statement and there's no need to wrap it in the sync_to_async unless you really need a list there which will cause it to evaluate. In this example you don't seem to need it as you can pass a queryset directly to your template for rendering and it will be evaluated there. You can simply do this: tests = Test.objects.filter(name='Test 1') return render(request, 'analyticsApp/test.html', { 'tests':tests }) If you absolutely need to print them then you simply wrap the print in a sync_to_async await sync_to_async(print)(tests) Or if you need to print them as a list then test_list = await sync_to_async(list)(tests) await sync_to_async(print)(test_list) Print needs to be sync to access the . notation of accessing related fields. Same stands for using the dot notation to access related fields in your template. If you are then wrap the render in a sync_to_async and await it. return await sync_to_async(render)(request, 'analyticsApp/test.html', { 'tests':tests }) All you manage with select_related is to cause the evaluation of the related fields to happen at the same time as the creation of the list in sync context and that's why it works with the dot notation in your template or with print.
Django Async View - Model __str__
I'm trying to convert my existing Django 4.1 app to async due to performance reasons. It's more of a struggle than I initially anticipated. Below is some test code: async def diagrams(request): tests = await sync_to_async(list)(Test.objects.filter(name='Test 1')) print(tests) return render(request, 'analyticsApp/test.html') class Test2(models.Model): name = models.CharField(max_length=50, default='', blank=True) def __str__(self): return self.name class Test(models.Model): name = models.CharField(max_length=50, default='', blank=True) testForeignKey = models.ForeignKey(Test2, editable=True, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): # Need to get foreign key here in async way but this function cannot be async ?? return self.name + '_' + self.testForeignKey.name So I kind of figured out how to "filter" objects using async_to_async. However, a problem that I'm struggling to solve is using __str__ in a Model. All of my models use __str__ to give accurate string depcitions of the model. It seems like this cannot be done ? I tried to convert def __str__ to async def __str__ but django is not awaiting this when it is being called so it causes problems. Any idea how to handle this ?
[ "Probably the async don't increase your performance.\nIn your code you work don't correct with async. Str should work with existing data, without ask to database.\nTherefore you should receive needed data before instance init.\nIn your case you can made:\nobj = Test.objects.select_related(\"testForeignKey\").get(**something)\n\nAlso you can use defer/only.\nThe query works async, after that you get your Str(object) normally.\n", "I have't used much the async support but as a work around you can use a select_related\nasync def diagrams(request):\n\n tests = await sync_to_async(list)(\n Test.objects.filter(name='Test 1')\n .select_related('testForeignKey')\n )\n print(tests)\n\n return render(request, 'analyticsApp/test.html')\n\n", "I think your problem here is the print(tests)\nThat's when the query gets evaluated and at that point __str__ gets called to print the list of tests. Simply put, if you don't print them __str__ will never get called in an async context!\nAlso the .filter just prepares the sql statement and there's no need to wrap it in the sync_to_async unless you really need a list there which will cause it to evaluate. In this example you don't seem to need it as you can pass a queryset directly to your template for rendering and it will be evaluated there. You can simply do this:\ntests = Test.objects.filter(name='Test 1')\nreturn render(request, 'analyticsApp/test.html', { 'tests':tests })\n\nIf you absolutely need to print them then you simply wrap the print in a sync_to_async\nawait sync_to_async(print)(tests)\n\nOr if you need to print them as a list then\ntest_list = await sync_to_async(list)(tests)\nawait sync_to_async(print)(test_list)\n\nPrint needs to be sync to access the . notation of accessing related fields.\nSame stands for using the dot notation to access related fields in your template. If you are then wrap the render in a sync_to_async and await it.\nreturn await sync_to_async(render)(request, 'analyticsApp/test.html', { 'tests':tests })\n\nAll you manage with select_related is to cause the evaluation of the related fields to happen at the same time as the creation of the list in sync context and that's why it works with the dot notation in your template or with print.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "django", "django_models", "django_views", "python_asyncio" ]
stackoverflow_0073265399_django_django_models_django_views_python_asyncio.txt
Q: Count(*) on VARCHAR Index with blank NVARCHAR or NULL check results in double the rows returned I have a table with a VARCHAR column and an index on it. Whenever a SELECT COUNT(*) is done on this table that has a check for COLUMN = N'' OR COLUMN IS NULL it returns double the number of rows. SELECT * with the same where clause will return the correct number of records. After reading this article: https://sqlquantumleap.com/2017/07/10/impact-on-indexes-when-mixing-varchar-and-nvarchar-types/ and doing some testing I believe the collation of the column and the implicit conversion isn't the fault (at least not directly). The collation of the column is Latin1_General_CI_AS. The database is on SQL Server 2012, and I've tested on 2016 as well. I've created a test script (below) that will demonstrate this problem. In doing so, I believe that it may be related to data paging, as it needed a bit of data in the table for it to occur. CREATE TABLE [dbo].TEMP ( ID [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, [DATA] [varchar](200) COLLATE Latin1_General_CI_AS NULL, [TESTCOLUMN] [varchar](50) COLLATE Latin1_General_CI_AS NULL, CONSTRAINT [PK_TEMP] PRIMARY KEY CLUSTERED ([ID] ASC) ) GO CREATE NONCLUSTERED INDEX [I_TEMP_TESTCOLUMN] ON dbo.TEMP (TESTCOLUMN ASC) GO DECLARE @ROWS AS INT = 40; WITH NUMBERS (NUM) AS ( SELECT 1 AS NUM UNION ALL SELECT NUM + 1 FROM NUMBERS WHERE NUM < @ROWS ) INSERT INTO TEMP (ID, DATA) SELECT NUM, '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901324561234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890' FROM NUMBERS SELECT @ROWS AS EXPECTED, COUNT(*) AS ACTUALROWS FROM TEMP GO SELECT COUNT(*) AS INVALIDINDEXSEARCHCOUNT FROM TEMP WHERE (TESTCOLUMN = N'' OR TESTCOLUMN IS NULL) GO DROP TABLE TEMP I'm able to modify the database to some extent (I won't be able to change data, or change the column from allowing NULL), unfortunately I am not able to modify the code doing the search, can anyone identify a way to get the correct COUNT(*) results returned?
Count(*) on VARCHAR Index with blank NVARCHAR or NULL check results in double the rows returned
I have a table with a VARCHAR column and an index on it. Whenever a SELECT COUNT(*) is done on this table that has a check for COLUMN = N'' OR COLUMN IS NULL it returns double the number of rows. SELECT * with the same where clause will return the correct number of records. After reading this article: https://sqlquantumleap.com/2017/07/10/impact-on-indexes-when-mixing-varchar-and-nvarchar-types/ and doing some testing I believe the collation of the column and the implicit conversion isn't the fault (at least not directly). The collation of the column is Latin1_General_CI_AS. The database is on SQL Server 2012, and I've tested on 2016 as well. I've created a test script (below) that will demonstrate this problem. In doing so, I believe that it may be related to data paging, as it needed a bit of data in the table for it to occur. CREATE TABLE [dbo].TEMP ( ID [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL, [DATA] [varchar](200) COLLATE Latin1_General_CI_AS NULL, [TESTCOLUMN] [varchar](50) COLLATE Latin1_General_CI_AS NULL, CONSTRAINT [PK_TEMP] PRIMARY KEY CLUSTERED ([ID] ASC) ) GO CREATE NONCLUSTERED INDEX [I_TEMP_TESTCOLUMN] ON dbo.TEMP (TESTCOLUMN ASC) GO DECLARE @ROWS AS INT = 40; WITH NUMBERS (NUM) AS ( SELECT 1 AS NUM UNION ALL SELECT NUM + 1 FROM NUMBERS WHERE NUM < @ROWS ) INSERT INTO TEMP (ID, DATA) SELECT NUM, '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901324561234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890' FROM NUMBERS SELECT @ROWS AS EXPECTED, COUNT(*) AS ACTUALROWS FROM TEMP GO SELECT COUNT(*) AS INVALIDINDEXSEARCHCOUNT FROM TEMP WHERE (TESTCOLUMN = N'' OR TESTCOLUMN IS NULL) GO DROP TABLE TEMP I'm able to modify the database to some extent (I won't be able to change data, or change the column from allowing NULL), unfortunately I am not able to modify the code doing the search, can anyone identify a way to get the correct COUNT(*) results returned?
[]
[]
[ "In my test, which was on SQL 2019, when one removes the N and just compares against '' or null, the double counting goes away.\nSELECT COUNT(*) AS ACTUALROWS\nFROM TEMP \nWHERE (TESTCOLUMN = '' OR TESTCOLUMN IS NULL)\n\nThe N identifier indicating Unicode is inappropriate anyway as the search column is not of type NVARCHAR. If test column were of type NVARCHAR, the count would be correct.\n", "Eric Kassan's answer is correct:\nThe column in the table is VARCHAR, but you are searching as if the column is NVARCHAR.\nThese are two different datatypes, so the column should be changed to NVARCHAR, or the query should be changed by removing the N.\nWhy the result is doubled up when joining different datatypes is interesting, but that was not the question. :)\n" ]
[ -1, -1 ]
[ "count", "indexing", "sql", "sql_server" ]
stackoverflow_0060922793_count_indexing_sql_sql_server.txt
Q: allMarkdownRemark doesn't have a "field" and "order" in sort I can't sort by fields and order in graphql because those options doesn't exist in my graphql tree. If I add manually fields and order I getting error - Field order is not defined by type MarkdownRemarkSortInput and Field fields is not defined by type MarkdownRemarkSortInput. Any solutions for that? I was trying to add manually but that's not helping. A: From the documentation, the sort variable is an array of objects of the form { objectName: { fieldName: DIRECTION } } where DIRECTION is ASC or DESC. Your query should look more like: { allMarkdownRemark( sort: [{ frontmatter: { date: ASC } }, { frontmatter: { title: ASC } }] ) { …result fields } You can use the left side of your query explorer to build the query - you can see how under allMarkdownRemark the sort option is there and then under that there is frontMatter, headings etc…
allMarkdownRemark doesn't have a "field" and "order" in sort
I can't sort by fields and order in graphql because those options doesn't exist in my graphql tree. If I add manually fields and order I getting error - Field order is not defined by type MarkdownRemarkSortInput and Field fields is not defined by type MarkdownRemarkSortInput. Any solutions for that? I was trying to add manually but that's not helping.
[ "From the documentation, the sort variable is an array of objects of the form\n{ objectName: { fieldName: DIRECTION } } where DIRECTION is ASC or DESC.\nYour query should look more like:\n{\n allMarkdownRemark(\n sort: [{ frontmatter: { date: ASC } }, { frontmatter: { title: ASC } }]\n ) {\n …result fields\n}\n\nYou can use the left side of your query explorer to build the query - you can see how under allMarkdownRemark the sort option is there and then under that there is frontMatter, headings etc…\n" ]
[ 0 ]
[]
[]
[ "gatsby", "graphql", "reactjs" ]
stackoverflow_0074677265_gatsby_graphql_reactjs.txt
Q: How can I redirectveriable veriable from object to my haracter I have 2 scripts one on player : using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerPositionCorrection : MonoBehaviour { Transform _playerTransform; public float _xAxys; public float _newXAxys; public GameObject _changerPlayerPosition; private void Start() { _playerTransform = GetComponent<Transform>(); } private void OnTriggerEnter(Collider other) { if (other.tag == "ChangePlayerPosition") { float _newXAxys = this.GetComponent<ChangePositionOn>()._newPostion; } } private void LateUpdate() { if (transform.position.z != 0) { transform.position = new Vector3(_xAxys, _playerTransform.position.y, _playerTransform.position.z); } } and second on object : public class ChangePositionOn : MonoBehaviour { public float _newPostion = 5; void Start() { } // Update is called once per frame void Update() { } } I using Unity 2022.1.19f1 and C#. Thank you for your healp, Michal I would like to have several object in my game and when player will collide with them change location on x axis. Unfortunately every time i have this error message: NullReferenceException: Object reference not set to an instance of an object PlayerPositionCorrection.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/PlayerPositionCorrection.cs:23) A: Check if the ChangePositionOn script is attached to the player gameObject. remove the float decalaration in the function because it makes it a local variable replace your function with this instead private void OnTriggerEnter(Collider other) { if (other.CompareTag("ChangePlayerPosition")) { Debug.Log("Check if Collided With : "+ other.gameObject.name); _newXAxys = this.GetComponent<ChangePositionOn>()._newPostion; Debug.Log("New XAxys value : "+ _newXAxys ); } } A: Make a new script PositionCorrector and Attach it to the Collider GameObject : using System.Collections; using System.Collections.Generic; using UnityEngine; public class PositionCorrector : MonoBehaviour { //this should be attached to Collider GameObject //this is the X value you want to change to, each collider can have a different number. public float _newXAxys=4; private void OnTriggerEnter(Collider other) { if (other.CompareTag("PlayerTag")) { //changing the x axys of the player position other.transform.position = new Vector3(_newXAxys, other.transform.position.y, other.transform.position.z); } } }
How can I redirectveriable veriable from object to my haracter
I have 2 scripts one on player : using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerPositionCorrection : MonoBehaviour { Transform _playerTransform; public float _xAxys; public float _newXAxys; public GameObject _changerPlayerPosition; private void Start() { _playerTransform = GetComponent<Transform>(); } private void OnTriggerEnter(Collider other) { if (other.tag == "ChangePlayerPosition") { float _newXAxys = this.GetComponent<ChangePositionOn>()._newPostion; } } private void LateUpdate() { if (transform.position.z != 0) { transform.position = new Vector3(_xAxys, _playerTransform.position.y, _playerTransform.position.z); } } and second on object : public class ChangePositionOn : MonoBehaviour { public float _newPostion = 5; void Start() { } // Update is called once per frame void Update() { } } I using Unity 2022.1.19f1 and C#. Thank you for your healp, Michal I would like to have several object in my game and when player will collide with them change location on x axis. Unfortunately every time i have this error message: NullReferenceException: Object reference not set to an instance of an object PlayerPositionCorrection.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/PlayerPositionCorrection.cs:23)
[ "\nCheck if the ChangePositionOn script is attached to the player\ngameObject.\nremove the float decalaration in the function because it makes it a\nlocal variable\nreplace your function with this instead\n\nprivate void OnTriggerEnter(Collider other)\n {\n if (other.CompareTag(\"ChangePlayerPosition\"))\n {\n Debug.Log(\"Check if Collided With : \"+ other.gameObject.name);\n _newXAxys = this.GetComponent<ChangePositionOn>()._newPostion;\n Debug.Log(\"New XAxys value : \"+ _newXAxys );\n }\n }\n\n", "Make a new script PositionCorrector and Attach it to the Collider GameObject :\nusing System.Collections;\n using System.Collections.Generic;\n using UnityEngine;\n \n public class PositionCorrector : MonoBehaviour\n {\n //this should be attached to Collider GameObject\n \n //this is the X value you want to change to, each collider can have a different number.\n public float _newXAxys=4;\n\n private void OnTriggerEnter(Collider other)\n {\n if (other.CompareTag(\"PlayerTag\"))\n {\n //changing the x axys of the player position\n other.transform.position = new Vector3(_newXAxys, other.transform.position.y, other.transform.position.z);\n \n }\n }\n }\n\n" ]
[ 0, 0 ]
[]
[]
[ "c#", "nullreferenceexception", "unity3d" ]
stackoverflow_0074675698_c#_nullreferenceexception_unity3d.txt
Q: How to report and fix errors while iterating? I would like to iterate through elements in raw_data below, and store the value of f(x) when f(x) gives an error, show the error msg and store this message fix the error that arised due to type, ie "four" instead of 4 Would it be possible to do all three at the same time? import math import sys raw_data = [5,"four", -3,2,1] def f(x): return math.log(x) What I have so far is: import math import sys raw_data = [5,"four", -3,2,1] def f(x): return math.log(x) for x in raw_data: try: print(f(x)) except: print("error:",sys.exc_info()[0]) This gives me a list results: 1.6094379124341003 error: <class 'TypeError'> error: <class 'ValueError'> 0.6931471805599453 0.0 How would I a) store the values of f(x) where there are no errors b) where there are errors, report and store the error message c) correct the type error? Thank you very much in advance A: Assuming you want to store the function results and error messages in two different lists, I'd suggest creating two lists and appending to one or the other in your try/except. Use a dictionary to do the translation between specific strings and their numeric equivalents. results = [] errors = [] num_names = { 'four': 4, } for x in raw_data: x = num_names.get(x, x) try: results.append(f(x)) except Exception as e: errors.append(repr(e)) print("Results:", *results, sep='\n') print("Errors:", *errors, sep='\n') Results: 1.6094379124341003 1.3862943611198906 0.6931471805599453 0.0 Errors: ValueError('math domain error')
How to report and fix errors while iterating?
I would like to iterate through elements in raw_data below, and store the value of f(x) when f(x) gives an error, show the error msg and store this message fix the error that arised due to type, ie "four" instead of 4 Would it be possible to do all three at the same time? import math import sys raw_data = [5,"four", -3,2,1] def f(x): return math.log(x) What I have so far is: import math import sys raw_data = [5,"four", -3,2,1] def f(x): return math.log(x) for x in raw_data: try: print(f(x)) except: print("error:",sys.exc_info()[0]) This gives me a list results: 1.6094379124341003 error: <class 'TypeError'> error: <class 'ValueError'> 0.6931471805599453 0.0 How would I a) store the values of f(x) where there are no errors b) where there are errors, report and store the error message c) correct the type error? Thank you very much in advance
[ "Assuming you want to store the function results and error messages in two different lists, I'd suggest creating two lists and appending to one or the other in your try/except. Use a dictionary to do the translation between specific strings and their numeric equivalents.\nresults = []\nerrors = []\nnum_names = {\n 'four': 4,\n}\n\nfor x in raw_data:\n x = num_names.get(x, x)\n try:\n results.append(f(x))\n except Exception as e:\n errors.append(repr(e))\n\nprint(\"Results:\", *results, sep='\\n')\nprint(\"Errors:\", *errors, sep='\\n')\n\nResults:\n1.6094379124341003\n1.3862943611198906\n0.6931471805599453\n0.0\nErrors:\nValueError('math domain error')\n\n" ]
[ 1 ]
[]
[]
[ "iteration", "loops", "python", "store", "typeerror" ]
stackoverflow_0074680732_iteration_loops_python_store_typeerror.txt
Q: How to make a stacked (tidy) dataframe where the index (indices) are filled in each row? I needed to take a wide, MutiIndex dataframe and stack it into Tidy for another program to chart it. I got that solved in a different question. However, the final exported file has merged cells for the stacked indices. I need each index repeated in the row so that the other program doesn't read the merged portion as "null". We have a group of Products, Year, Colors, and Sizes for the indices and the Sales numbers as the data. After the final stack, the dataframe looks like this: # Minimum Working Example of incoming data in wide format import pandas as pd import numpy as np colhead = ["Small Black", "Small White", "Small Brown", "Medium Black", "Medium White", "Medium Brown", "Large Black", "Large White", "Large Brown"] rowhead = pd.MultiIndex.from_product([['sofa','table','chair'],[2011, 2012, 2013, 2014, 2015]]) df_mix = pd.DataFrame(np.random.randint(1,10, size=15,9)), index=rowhead, columns=colhead) # Reindex by list and use .names to label dataframe hierarchy hierarch1 = ["Small", "Small", "Small", "Medium", "Medium", "Medium", "Large", "Large", "Large"] hierarch2 = ["Black", "White", "Brown", "Black", "White", "Brown", "Black", "White", "Brown"] df_mixfix = df_mix df_mixfix.columns = [hierarch1, hierarch2] df_mixfix.columns.names = ['Size', 'Color'] df_mixfix.index.names = ['Product', 'Year'] # Stack for tidy data stk = df_mixfix.stack() df_stk = stk.stack() print(df_stk) Product Year Color Size sofa 2011 Black Large 1 Medium 5 Small 1 Brown Large 9 Medium 4 .. chair 2015 Brown Medium 6 Small 5 White Large 8 Medium 1 Small 6 Length: 135, dtype: int32 Note that some additional tables are created, where the MultiIndex is regrouped by year first, then by product. Regardless of the grouping, What I need it to look like is this, where each of the grouped-by rows is filled with the index, so that when I run the export to excel (this is the problem here: because it looks like above, not below), the tidy data will not be merged: Product Year Color Size sofa 2011 Black Large 1 sofa 2011 Black Medium 5 sofa 2011 Black Small 1 sofa 2011 Brown Large 9 sofa 2011 Brown Medium 4 .. chair 2015 Brown Medium 6 chair 2015 Brown Small 5 chair 2015 White Large 8 chair 2015 White Medium 1 chair 2015 White Small 6 What I have tried is able to get the displays in Jupyter notebook to not look sparse, but the export to Excel still ends up merged. I had to update pandas to 1.5.2 then used the following: pd.set_option("display.multi_sparse", False) # for output display pd.set_option("styler.sparse.index", False) # fills in rows with pd.ExcelWriter('Tidy.xlsx') as writer: df_stk.to_excel(writer, sheet_name='Sales') #still has merged cells How do I get each explicit level element in a hierarchical key for each row in the Excel? A: I figured it out! While the examples weren't helpful, buried in the documentation was the info that I just needed to add the parameter merge_cells=False so the whole thing inside the writer is: with pd.ExcelWriter('Tidy.xlsx') as writer: df_stk.to_excel(writer, sheet_name='Sales', merge_cells=False) # Fully Tidy data! Note: this will un-sparse all hierarchical merges.
How to make a stacked (tidy) dataframe where the index (indices) are filled in each row?
I needed to take a wide, MutiIndex dataframe and stack it into Tidy for another program to chart it. I got that solved in a different question. However, the final exported file has merged cells for the stacked indices. I need each index repeated in the row so that the other program doesn't read the merged portion as "null". We have a group of Products, Year, Colors, and Sizes for the indices and the Sales numbers as the data. After the final stack, the dataframe looks like this: # Minimum Working Example of incoming data in wide format import pandas as pd import numpy as np colhead = ["Small Black", "Small White", "Small Brown", "Medium Black", "Medium White", "Medium Brown", "Large Black", "Large White", "Large Brown"] rowhead = pd.MultiIndex.from_product([['sofa','table','chair'],[2011, 2012, 2013, 2014, 2015]]) df_mix = pd.DataFrame(np.random.randint(1,10, size=15,9)), index=rowhead, columns=colhead) # Reindex by list and use .names to label dataframe hierarchy hierarch1 = ["Small", "Small", "Small", "Medium", "Medium", "Medium", "Large", "Large", "Large"] hierarch2 = ["Black", "White", "Brown", "Black", "White", "Brown", "Black", "White", "Brown"] df_mixfix = df_mix df_mixfix.columns = [hierarch1, hierarch2] df_mixfix.columns.names = ['Size', 'Color'] df_mixfix.index.names = ['Product', 'Year'] # Stack for tidy data stk = df_mixfix.stack() df_stk = stk.stack() print(df_stk) Product Year Color Size sofa 2011 Black Large 1 Medium 5 Small 1 Brown Large 9 Medium 4 .. chair 2015 Brown Medium 6 Small 5 White Large 8 Medium 1 Small 6 Length: 135, dtype: int32 Note that some additional tables are created, where the MultiIndex is regrouped by year first, then by product. Regardless of the grouping, What I need it to look like is this, where each of the grouped-by rows is filled with the index, so that when I run the export to excel (this is the problem here: because it looks like above, not below), the tidy data will not be merged: Product Year Color Size sofa 2011 Black Large 1 sofa 2011 Black Medium 5 sofa 2011 Black Small 1 sofa 2011 Brown Large 9 sofa 2011 Brown Medium 4 .. chair 2015 Brown Medium 6 chair 2015 Brown Small 5 chair 2015 White Large 8 chair 2015 White Medium 1 chair 2015 White Small 6 What I have tried is able to get the displays in Jupyter notebook to not look sparse, but the export to Excel still ends up merged. I had to update pandas to 1.5.2 then used the following: pd.set_option("display.multi_sparse", False) # for output display pd.set_option("styler.sparse.index", False) # fills in rows with pd.ExcelWriter('Tidy.xlsx') as writer: df_stk.to_excel(writer, sheet_name='Sales') #still has merged cells How do I get each explicit level element in a hierarchical key for each row in the Excel?
[ "I figured it out! While the examples weren't helpful, buried in the documentation was the info that I just needed to add the parameter merge_cells=False\nso the whole thing inside the writer is:\nwith pd.ExcelWriter('Tidy.xlsx') as writer:\n df_stk.to_excel(writer, sheet_name='Sales', merge_cells=False) # Fully Tidy data!\n\nNote: this will un-sparse all hierarchical merges.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "export_to_excel", "multi_index", "series", "styler" ]
stackoverflow_0074663460_dataframe_export_to_excel_multi_index_series_styler.txt
Q: Rust doesn't get it when a reference is no longer borrowed In Rust when I borrow a value, the compiler takes notice, but when I replace it the compiler does not notice and issues an E0597 error. Given a mutable variable that contains a reference x. When I replace its content, with the reference to a local variable, and before the local goes out of scope I replace it back to the original. Here is a code that shows this: struct X {payload : i32} fn main() { let pl = X{payload : 44}; { let mut x = &pl; { let inner = X{payload : 30}; let tmp = std::mem::replace(&mut x, &inner); println! ("data ={:?}", x.payload); let _f = std::mem::replace(&mut x, &tmp); } println! ("data ={:?}", x.payload); } } The compiler notices when I assign a reference of inner to x, but overlooks the fact that while inner is still alive I replace this reference with the original one to pl again. The expected output should be: data =30 data =44 What am I doing wrong? A: I believe this is a limitation of non-lexical lifetimes. I'm no expert by any means so I hope someone will correct me if I'm wrong. First, let's rewrite your program to be a skosh simpler, by just using regular assignments instead of mem::replace (should be identical for Copy types): struct X {payload : i32} fn main() { let pl = X{payload : 44}; { let mut x = &pl; { let inner = X{payload : 30}; let tmp = x; x = &inner; println! ("data ={:?}", x.payload); x = tmp; } println! ("data ={:?}", x.payload); } } I think the relevant part of the NLL RFC is this: Subtyping Whenever references are copied from one location to another, the Rust subtyping rules require that the lifetime of the source reference outlives the lifetime of the target location. The souce reference in this case is &inner and the target location is x, so &inner must outlive x. But printing x.payload after the block in which inner is alive forces the lifetime of x to extend past the lifetime of &inner, meaning &inner can't outlive x, meaning you aren't meeting the requirements of the subtyping rules, whether or not you put something back that fulfils them later. The rules are a little unflexible like that. (There might also be a legitimate soundness issue with allowing something like that, I just can't come up with one off the top of my head.)
Rust doesn't get it when a reference is no longer borrowed
In Rust when I borrow a value, the compiler takes notice, but when I replace it the compiler does not notice and issues an E0597 error. Given a mutable variable that contains a reference x. When I replace its content, with the reference to a local variable, and before the local goes out of scope I replace it back to the original. Here is a code that shows this: struct X {payload : i32} fn main() { let pl = X{payload : 44}; { let mut x = &pl; { let inner = X{payload : 30}; let tmp = std::mem::replace(&mut x, &inner); println! ("data ={:?}", x.payload); let _f = std::mem::replace(&mut x, &tmp); } println! ("data ={:?}", x.payload); } } The compiler notices when I assign a reference of inner to x, but overlooks the fact that while inner is still alive I replace this reference with the original one to pl again. The expected output should be: data =30 data =44 What am I doing wrong?
[ "I believe this is a limitation of non-lexical lifetimes. I'm no expert by any means so I hope someone will correct me if I'm wrong.\nFirst, let's rewrite your program to be a skosh simpler, by just using regular assignments instead of mem::replace (should be identical for Copy types):\nstruct X {payload : i32}\n\nfn main() {\n let pl = X{payload : 44};\n {\n let mut x = &pl;\n {\n let inner = X{payload : 30};\n let tmp = x;\n x = &inner;\n println! (\"data ={:?}\", x.payload);\n x = tmp;\n }\n println! (\"data ={:?}\", x.payload);\n }\n}\n\nI think the relevant part of the NLL RFC is this:\n\nSubtyping\nWhenever references are copied from one location to another, the Rust subtyping rules require that the lifetime of the source reference outlives the lifetime of the target location.\n\nThe souce reference in this case is &inner and the target location is x, so &inner must outlive x. But printing x.payload after the block in which inner is alive forces the lifetime of x to extend past the lifetime of &inner, meaning &inner can't outlive x, meaning you aren't meeting the requirements of the subtyping rules, whether or not you put something back that fulfils them later. The rules are a little unflexible like that. (There might also be a legitimate soundness issue with allowing something like that, I just can't come up with one off the top of my head.)\n" ]
[ 0 ]
[]
[]
[ "borrow_checker", "reference", "rust", "stack" ]
stackoverflow_0074679510_borrow_checker_reference_rust_stack.txt
Q: Expected a value of type 'int', but got one of type 'String' flutter I'm trying to build a simple list in flutter, I based my code of a flutter cookbook https://docs.flutter.dev/cookbook/networking/background-parsing but I tried applying DDD so its separated in different classes. import 'package:corsiapp/Domain/Course/course.dart'; import 'package:corsiapp/Infraestructure/remote_data_source.dart'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. //3232 // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.red, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key, required this.title}); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), ), body: FutureBuilder<List<Course>>( future: RemoteDataSourceImpl(client: http.Client()).getCoursefromAPI(), builder: (context, snapshot) { if (snapshot.hasError) { return const Center( child: Text('An error has occurred!'), ); } else if (snapshot.hasData) { return CourseList(course: snapshot.data!); } else { return const Center( child: CircularProgressIndicator(), ); } }, ), ); } } class CourseList extends StatelessWidget { const CourseList({super.key, required this.course}); final List<Course> course; @override Widget build(BuildContext context) { return GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), itemCount: course.length, itemBuilder: (context, index) { return Text(course[index].title); }, ); } } import 'package:equatable/equatable.dart'; import 'package:corsiapp/Domain/Course/lesson.dart'; class Course extends Equatable { const Course( {required this.id, required this.title, required this.urlImage, required this.description}); final int id; final String title; final String urlImage; final String description; factory Course.fromJson(Map<String, dynamic> json) { return Course( id: json['id'] as int, title: json['title'] as String, urlImage: json['urlimage'] as String, description: json['description'] as String); } @override List<Object?> get props => [id, title, urlImage, description]; } import 'dart:convert'; import 'package:corsiapp/Domain/Course/course.dart'; import 'package:http/http.dart' as http; abstract class RemoteDataSource { Future<List<Course>> getCoursefromAPI(); } class RemoteDataSourceImpl implements RemoteDataSource { final http.Client client; RemoteDataSourceImpl({required this.client}); @override Future<List<Course>> getCoursefromAPI() async { final response = await client .get(Uri.parse('https://638c1e60eafd555746a0b852.mockapi.io/Course')); if (response.statusCode == 200) { return parseCourse(response.body); } else { print('Serch Local Repository'); throw Exception(); } } // A function that converts a response body into a List<Photo>. List<Course> parseCourse(String responseBody) { final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<Course>((json) => Course.fromJson(json)).toList(); } } Using a basic print I captured the error of the snapshot that error being Expected a value of type 'int', but got one of type 'String', in the tutorial they show a list of pictures I wanted to show a list of titles. A: the JSON returned from https://638c1e60eafd555746a0b852.mockapi.io/Course indicates that the id is of type String not int try this: factory Course.fromJson(Map<String, dynamic> json) { return Course( id: int.parse(json['id']), title: json['title'] as String, urlImage: json['urlimage'] as String, description: json['description'] as String, ); }
Expected a value of type 'int', but got one of type 'String' flutter
I'm trying to build a simple list in flutter, I based my code of a flutter cookbook https://docs.flutter.dev/cookbook/networking/background-parsing but I tried applying DDD so its separated in different classes. import 'package:corsiapp/Domain/Course/course.dart'; import 'package:corsiapp/Infraestructure/remote_data_source.dart'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. //3232 // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.red, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key, required this.title}); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), ), body: FutureBuilder<List<Course>>( future: RemoteDataSourceImpl(client: http.Client()).getCoursefromAPI(), builder: (context, snapshot) { if (snapshot.hasError) { return const Center( child: Text('An error has occurred!'), ); } else if (snapshot.hasData) { return CourseList(course: snapshot.data!); } else { return const Center( child: CircularProgressIndicator(), ); } }, ), ); } } class CourseList extends StatelessWidget { const CourseList({super.key, required this.course}); final List<Course> course; @override Widget build(BuildContext context) { return GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), itemCount: course.length, itemBuilder: (context, index) { return Text(course[index].title); }, ); } } import 'package:equatable/equatable.dart'; import 'package:corsiapp/Domain/Course/lesson.dart'; class Course extends Equatable { const Course( {required this.id, required this.title, required this.urlImage, required this.description}); final int id; final String title; final String urlImage; final String description; factory Course.fromJson(Map<String, dynamic> json) { return Course( id: json['id'] as int, title: json['title'] as String, urlImage: json['urlimage'] as String, description: json['description'] as String); } @override List<Object?> get props => [id, title, urlImage, description]; } import 'dart:convert'; import 'package:corsiapp/Domain/Course/course.dart'; import 'package:http/http.dart' as http; abstract class RemoteDataSource { Future<List<Course>> getCoursefromAPI(); } class RemoteDataSourceImpl implements RemoteDataSource { final http.Client client; RemoteDataSourceImpl({required this.client}); @override Future<List<Course>> getCoursefromAPI() async { final response = await client .get(Uri.parse('https://638c1e60eafd555746a0b852.mockapi.io/Course')); if (response.statusCode == 200) { return parseCourse(response.body); } else { print('Serch Local Repository'); throw Exception(); } } // A function that converts a response body into a List<Photo>. List<Course> parseCourse(String responseBody) { final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<Course>((json) => Course.fromJson(json)).toList(); } } Using a basic print I captured the error of the snapshot that error being Expected a value of type 'int', but got one of type 'String', in the tutorial they show a list of pictures I wanted to show a list of titles.
[ "the JSON returned from https://638c1e60eafd555746a0b852.mockapi.io/Course indicates that the id is of type String not int\ntry this:\nfactory Course.fromJson(Map<String, dynamic> json) {\n return Course(\n id: int.parse(json['id']),\n title: json['title'] as String,\n urlImage: json['urlimage'] as String,\n description: json['description'] as String,\n );\n}\n\n" ]
[ 0 ]
[]
[]
[ "dart", "domain_driven_design", "flutter" ]
stackoverflow_0074680633_dart_domain_driven_design_flutter.txt
Q: Django ORM. Check that sum of additional field of m2m relation model equals 100 I want to implement a check on this relation, to ensure that all ticket's weight in sum gives me 100. class PortfolioTicker(models.Model): """ Helper model for M2M relationship between Tickers and Portfolios """ portfolio = models.ForeignKey(Portfolio, models.PROTECT, related_name="tickers") ticker = models.ForeignKey(Ticker, models.PROTECT) weight = models.FloatField(null=False) def __str__(self) -> str: return f"{self.portfolio} {self.ticker} {self.weight}" A: if you want a report for each ticker: x = PortfolioTicker.objects.values('ticker').order_by('ticker').annotate(summa=Sum('weight')).annotate(hundert=Case(When(summa=100, then=True), default=False)) if you want to check for a given ticker PortfolioTicker.objects.filter(ticker=given_ticker).aggregate(summa=Sum('weight'))['summa']
Django ORM. Check that sum of additional field of m2m relation model equals 100
I want to implement a check on this relation, to ensure that all ticket's weight in sum gives me 100. class PortfolioTicker(models.Model): """ Helper model for M2M relationship between Tickers and Portfolios """ portfolio = models.ForeignKey(Portfolio, models.PROTECT, related_name="tickers") ticker = models.ForeignKey(Ticker, models.PROTECT) weight = models.FloatField(null=False) def __str__(self) -> str: return f"{self.portfolio} {self.ticker} {self.weight}"
[ "if you want a report for each ticker:\nx = PortfolioTicker.objects.values('ticker').order_by('ticker').annotate(summa=Sum('weight')).annotate(hundert=Case(When(summa=100, then=True), default=False))\n\nif you want to check for a given ticker\nPortfolioTicker.objects.filter(ticker=given_ticker).aggregate(summa=Sum('weight'))['summa']\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_orm" ]
stackoverflow_0074583403_django_django_models_django_orm.txt
Q: Firebase revoking download URL doesn't work I am using firebase, react and react-native to develop an MVP app where users can upload image files and other users can retrieve them for viewing, and I am using firebase storage and the getDownloadURL() function. I know that there are other ways of retrieving firebase storage files, but I want to use the downloadURL so that unauthenticated users may also view the images. I know that downloadURL is public and access to files cannot be restricted even by firebase security rules. Nonetheless, there is the revoke function where I can supposedly revoke the access token, i.e. the downloadURL. At the firebase console, I tried it out. It turns out that every time I revoke it, firebase generates a new one as replacement. More problematic is that I can still use the old (revoked) URL to access the image files. I checked out at the browser developer tool. The URL used by the browser was indeed the revoked URL. I used a new browser to ensure that the problem is not related to the cache. Even if I use a react-ative app, the same problem appears. The image cannot be accessed only if I completely delete it from the firebase storage. What is the problem here? Have I missed something? I have looked up the firebase documentation and searched for similar issues on stackoverflow but cannot get an answer. Other people don't seem to have this problem. A: The reason why you can still access the revoked urls is because in your firebase storage rules you have accepted reads for all users, whether authenticated or unauthenticated. To prevent access to revoked urls, use the following in your firebase storage rules. NB// This will require all users to be authenticated inorder to get the download url rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if request.auth != null; } } }
Firebase revoking download URL doesn't work
I am using firebase, react and react-native to develop an MVP app where users can upload image files and other users can retrieve them for viewing, and I am using firebase storage and the getDownloadURL() function. I know that there are other ways of retrieving firebase storage files, but I want to use the downloadURL so that unauthenticated users may also view the images. I know that downloadURL is public and access to files cannot be restricted even by firebase security rules. Nonetheless, there is the revoke function where I can supposedly revoke the access token, i.e. the downloadURL. At the firebase console, I tried it out. It turns out that every time I revoke it, firebase generates a new one as replacement. More problematic is that I can still use the old (revoked) URL to access the image files. I checked out at the browser developer tool. The URL used by the browser was indeed the revoked URL. I used a new browser to ensure that the problem is not related to the cache. Even if I use a react-ative app, the same problem appears. The image cannot be accessed only if I completely delete it from the firebase storage. What is the problem here? Have I missed something? I have looked up the firebase documentation and searched for similar issues on stackoverflow but cannot get an answer. Other people don't seem to have this problem.
[ "The reason why you can still access the revoked urls is because in your firebase storage rules you have accepted reads for all users, whether authenticated or unauthenticated.\nTo prevent access to revoked urls, use the following in your firebase storage rules.\nNB// This will require all users to be authenticated inorder to get the download url\nrules_version = '2';\nservice firebase.storage {\n match /b/{bucket}/o {\n match /{allPaths=**} {\n allow read, write: if request.auth != null;\n }\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "firebase", "firebase_storage", "url" ]
stackoverflow_0074672439_firebase_firebase_storage_url.txt
Q: What is wrong with this implementation of Barrier using atomics in Rust? I've wrote the following implementation of a Barrier using atomics only: use std::sync::atomic::{AtomicUsize, Ordering}; pub struct Barrier { pub done: AtomicUsize, pub tids: usize, } impl Barrier { pub fn new(tids: usize) -> Barrier { Barrier { done: AtomicUsize::new(0), tids, } } pub fn wait(&self) { let done = self.done.fetch_add(1, Ordering::SeqCst); if done + 1 == self.tids { self.done.store(0, Ordering::SeqCst); } else { while self.done.load(Ordering::SeqCst) != 0 {} } } } It doesn't work as expected. For example, // inside threads loop barrier.wait(); println!("a"); barrier.wait(); println!("b"); Intuitively, it should work, since, once .wait() is called, it will hang on the while loop, breaking free from it after all the threads have called .wait(), and resetting the counter for the next .wait(). Instead, eventually it will hang. Below is an usage example: fn main() { println!("Hello, world!"); let barrier = &Barrier::new(10); std::thread::scope(|s| { for tid in 0 .. 10 { s.spawn(move || { loop { barrier.wait(); println!("{} a", tid); barrier.wait(); println!("{} b", tid); } }); } }); } A: The problem is that there is a race condition between two consecutive barriers: A thread might get unscheduled while waiting for the barrier. A second thread (who is the last thread the barrier waits for) enters the barrier, releases it, runs its next iteration and enters the barrier again The first thread wakes up and sees a value of 1, missing the barrier release completely. If you are sure that you are always using the same threads, you could fix that by utilizing two counters, and flipping back and forth between them. That way all threads wait either for the first or the second one. But there is no way for one thread to bypass the others, as it would have to go through the second counter to block the first one again, and the second one will only unblock if no thread is still left in the first one. This one seems to work: use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; pub struct Barrier { pub done: [AtomicUsize; 2], pub use_first_done: AtomicBool, pub tids: usize, } impl Barrier { pub fn new(tids: usize) -> Barrier { Barrier { done: [AtomicUsize::new(0), AtomicUsize::new(0)], use_first_done: AtomicBool::new(true), tids, } } pub fn wait(&self) { let done = if self.use_first_done.load(Ordering::SeqCst) { &self.done[0] } else { &self.done[1] }; let num_done = done.fetch_add(1, Ordering::SeqCst) + 1; if num_done == self.tids { self.use_first_done.fetch_xor(true, Ordering::SeqCst); done.store(0, Ordering::SeqCst); } else { while done.load(Ordering::SeqCst) != 0 {} } } } fn main() { println!("Hello, world!"); let barrier = &Barrier::new(10); std::thread::scope(|s| { for tid in 0..10 { s.spawn(move || loop { barrier.wait(); println!("{} a", tid); barrier.wait(); println!("{} b", tid); }); } }); } An alternative would be to use an iteration counter. For the same reason as why flipping between two done counters works, an iteration counter of two iterations (= a boolean) should be sufficient. This one works for me as well: use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; pub struct Barrier { pub done: AtomicUsize, pub iteration: AtomicBool, pub tids: usize, } impl Barrier { pub fn new(tids: usize) -> Barrier { Barrier { done: AtomicUsize::new(0), iteration: AtomicBool::new(false), tids, } } pub fn wait(&self) { let iteration = self.iteration.load(Ordering::SeqCst); let num_done = self.done.fetch_add(1, Ordering::SeqCst) + 1; if num_done == self.tids { self.done.store(0, Ordering::SeqCst); self.iteration.fetch_xor(true, Ordering::SeqCst); } else { while iteration == self.iteration.load(Ordering::SeqCst) {} } } } fn main() { println!("Hello, world!"); let barrier = &Barrier::new(10); std::thread::scope(|s| { for tid in 0..10 { s.spawn(move || loop { barrier.wait(); println!("{} a", tid); barrier.wait(); println!("{} b", tid); }); } }); } IMPORTANT: This only works if the threads are always identical. If different threads use this barrier, then it's necessary to have a bigger iteration counter. A: I like the @Finomnis solution. I also, want to improve it a little bit. Please consider my changes too. pub struct Barrier { pub done: AtomicUsize, pub iteration: AtomicBool, pub tids: usize, } impl Barrier { pub fn new(tids: usize) -> Barrier { Barrier { done: AtomicUsize::new(0), iteration: AtomicBool::new(false), tids, } } pub fn wait(&self) { ┌-----┬ let iteration = self.iteration.load(Ordering::Relaxed); | | let num_done = self.done.fetch_add(1, Ordering::AcqRel) + 1; | | if num_done == self.tids { | └-> self.done.store(0, Ordering::Relaxed); | self.iteration.fetch_xor(true, Ordering::AcqRel); X return; | } | └-----> // let iteration = self.iteration.load(Ordering::Relaxed); // Instruction couldn't be moved here because we have a request to // see all memory changes self.iteration.fetch_xor with // AcqRel ordering. It's safe to use here Relaxed ordering. // For example, we could imagine that Acquire-Release ordering is // like a sandwich. ┌----- ...instructions, could be moved inside of a sandwich | Acquire ├-----> | Release └-X--> ...instructions, but not here. // Cares only for changes in self.iteration // Let's use here the lowest memory ordering while iteration == self.iteration.load(Ordering::Relaxed) { // I think that there could be saved a few CPU cycles if we give // a compiler a hint that it's a waiting loop. // Note: It's a Clippy suggestion. std::hint::spin_loop(); // Also, could be used yield, but is better to use a hint // std::thread::yield_now(); } } }
What is wrong with this implementation of Barrier using atomics in Rust?
I've wrote the following implementation of a Barrier using atomics only: use std::sync::atomic::{AtomicUsize, Ordering}; pub struct Barrier { pub done: AtomicUsize, pub tids: usize, } impl Barrier { pub fn new(tids: usize) -> Barrier { Barrier { done: AtomicUsize::new(0), tids, } } pub fn wait(&self) { let done = self.done.fetch_add(1, Ordering::SeqCst); if done + 1 == self.tids { self.done.store(0, Ordering::SeqCst); } else { while self.done.load(Ordering::SeqCst) != 0 {} } } } It doesn't work as expected. For example, // inside threads loop barrier.wait(); println!("a"); barrier.wait(); println!("b"); Intuitively, it should work, since, once .wait() is called, it will hang on the while loop, breaking free from it after all the threads have called .wait(), and resetting the counter for the next .wait(). Instead, eventually it will hang. Below is an usage example: fn main() { println!("Hello, world!"); let barrier = &Barrier::new(10); std::thread::scope(|s| { for tid in 0 .. 10 { s.spawn(move || { loop { barrier.wait(); println!("{} a", tid); barrier.wait(); println!("{} b", tid); } }); } }); }
[ "The problem is that there is a race condition between two consecutive barriers:\n\nA thread might get unscheduled while waiting for the barrier.\nA second thread (who is the last thread the barrier waits for) enters the barrier, releases it, runs its next iteration and enters the barrier again\nThe first thread wakes up and sees a value of 1, missing the barrier release completely.\n\nIf you are sure that you are always using the same threads, you could fix that by utilizing two counters, and flipping back and forth between them. That way all threads wait either for the first or the second one. But there is no way for one thread to bypass the others, as it would have to go through the second counter to block the first one again, and the second one will only unblock if no thread is still left in the first one.\nThis one seems to work:\nuse std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};\n\npub struct Barrier {\n pub done: [AtomicUsize; 2],\n pub use_first_done: AtomicBool,\n pub tids: usize,\n}\n\nimpl Barrier {\n pub fn new(tids: usize) -> Barrier {\n Barrier {\n done: [AtomicUsize::new(0), AtomicUsize::new(0)],\n use_first_done: AtomicBool::new(true),\n tids,\n }\n }\n\n pub fn wait(&self) {\n let done = if self.use_first_done.load(Ordering::SeqCst) {\n &self.done[0]\n } else {\n &self.done[1]\n };\n\n let num_done = done.fetch_add(1, Ordering::SeqCst) + 1;\n if num_done == self.tids {\n self.use_first_done.fetch_xor(true, Ordering::SeqCst);\n done.store(0, Ordering::SeqCst);\n } else {\n while done.load(Ordering::SeqCst) != 0 {}\n }\n }\n}\n\nfn main() {\n println!(\"Hello, world!\");\n\n let barrier = &Barrier::new(10);\n\n std::thread::scope(|s| {\n for tid in 0..10 {\n s.spawn(move || loop {\n barrier.wait();\n println!(\"{} a\", tid);\n barrier.wait();\n println!(\"{} b\", tid);\n });\n }\n });\n}\n\n\nAn alternative would be to use an iteration counter.\nFor the same reason as why flipping between two done counters works, an iteration counter of two iterations (= a boolean) should be sufficient.\nThis one works for me as well:\nuse std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};\n\npub struct Barrier {\n pub done: AtomicUsize,\n pub iteration: AtomicBool,\n pub tids: usize,\n}\n\nimpl Barrier {\n pub fn new(tids: usize) -> Barrier {\n Barrier {\n done: AtomicUsize::new(0),\n iteration: AtomicBool::new(false),\n tids,\n }\n }\n\n pub fn wait(&self) {\n let iteration = self.iteration.load(Ordering::SeqCst);\n let num_done = self.done.fetch_add(1, Ordering::SeqCst) + 1;\n if num_done == self.tids {\n self.done.store(0, Ordering::SeqCst);\n self.iteration.fetch_xor(true, Ordering::SeqCst);\n } else {\n while iteration == self.iteration.load(Ordering::SeqCst) {}\n }\n }\n}\n\nfn main() {\n println!(\"Hello, world!\");\n\n let barrier = &Barrier::new(10);\n\n std::thread::scope(|s| {\n for tid in 0..10 {\n s.spawn(move || loop {\n barrier.wait();\n println!(\"{} a\", tid);\n barrier.wait();\n println!(\"{} b\", tid);\n });\n }\n });\n}\n\nIMPORTANT: This only works if the threads are always identical. If different threads use this barrier, then it's necessary to have a bigger iteration counter.\n", "I like the @Finomnis solution. I also, want to improve it a little bit. Please consider my changes too.\npub struct Barrier {\n pub done: AtomicUsize,\n pub iteration: AtomicBool,\n pub tids: usize,\n}\n\nimpl Barrier {\n pub fn new(tids: usize) -> Barrier {\n Barrier {\n done: AtomicUsize::new(0),\n iteration: AtomicBool::new(false),\n tids,\n }\n }\n\n pub fn wait(&self) {\n┌-----┬ let iteration = self.iteration.load(Ordering::Relaxed);\n| | let num_done = self.done.fetch_add(1, Ordering::AcqRel) + 1;\n| | if num_done == self.tids {\n| └-> self.done.store(0, Ordering::Relaxed);\n| self.iteration.fetch_xor(true, Ordering::AcqRel);\nX return;\n| }\n|\n└-----> // let iteration = self.iteration.load(Ordering::Relaxed);\n // Instruction couldn't be moved here because we have a request to \n // see all memory changes self.iteration.fetch_xor with \n // AcqRel ordering. It's safe to use here Relaxed ordering.\n\n // For example, we could imagine that Acquire-Release ordering is \n // like a sandwich.\n ┌----- ...instructions, could be moved inside of a sandwich\n | Acquire\n ├-----> \n | Release\n └-X--> ...instructions, but not here.\n\n\n // Cares only for changes in self.iteration\n // Let's use here the lowest memory ordering\n while iteration == self.iteration.load(Ordering::Relaxed) {\n // I think that there could be saved a few CPU cycles if we give \n // a compiler a hint that it's a waiting loop.\n // Note: It's a Clippy suggestion.\n std::hint::spin_loop();\n\n // Also, could be used yield, but is better to use a hint\n // std::thread::yield_now();\n }\n }\n}\n\n" ]
[ 3, 1 ]
[]
[]
[ "barrier", "multithreading", "rust" ]
stackoverflow_0074669890_barrier_multithreading_rust.txt
Q: Python: Assigning numbering to list of ascii Need help with making a encryption python program that encrypts with use of ascii values. I have 1-127 random number generator with no repeats and need to basically assign a value to each one. Example: list 1 is (1,2,3...127) list 2 is (54,60,27...) I need to get a list or dictionary of (1 : 54 , 2 : 60 , 3 : 27...). End goal is that after encryption, 54 is assigned to ascii 1 (soh), if the number 54 appears in the encrypted string, then original string had a soh in that slot I do not know the proper way to assign the random number list a number. I think its dictionary but I am not familiar with dict A: You can make a dict from 2 lists with: listsdict = dict(zip(list1, list2)) Additionally then you can iterate through your input string look up the Value like ascii_value = ord(char) # Look up the corresponding value in the dictionary using the ASCII value as the key encrypted_value = dict1[ascii_value] A: Welcome to StackOverflow. I urge you to take a look at the How do I ask a good question?, and How to create a Minimal, Reproducible Example pages so that we can point you in the right direction more easily. You're correct in thinking that a dictionary would be a suitable tool for this problem. You can learn all about dict and how it works in the Python docs page about built-in types. That page has a nifty example that covers what you described perfectly (through the usage of zip): c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
Python: Assigning numbering to list of ascii
Need help with making a encryption python program that encrypts with use of ascii values. I have 1-127 random number generator with no repeats and need to basically assign a value to each one. Example: list 1 is (1,2,3...127) list 2 is (54,60,27...) I need to get a list or dictionary of (1 : 54 , 2 : 60 , 3 : 27...). End goal is that after encryption, 54 is assigned to ascii 1 (soh), if the number 54 appears in the encrypted string, then original string had a soh in that slot I do not know the proper way to assign the random number list a number. I think its dictionary but I am not familiar with dict
[ "You can make a dict from 2 lists with:\nlistsdict = dict(zip(list1, list2))\nAdditionally then you can iterate through your input string look up the Value like\nascii_value = ord(char)\n\n# Look up the corresponding value in the dictionary using the ASCII value as the key\nencrypted_value = dict1[ascii_value]\n\n", "Welcome to StackOverflow. I urge you to take a look at the How do I ask a good question?, and How to create a Minimal, Reproducible Example pages so that we can point you in the right direction more easily.\nYou're correct in thinking that a dictionary would be a suitable tool for this problem.\nYou can learn all about dict and how it works in the Python docs page about built-in types.\nThat page has a nifty example that covers what you described perfectly (through the usage of zip):\nc = dict(zip(['one', 'two', 'three'], [1, 2, 3]))\n\n" ]
[ 0, 0 ]
[]
[]
[ "dictionary", "encryption", "list", "python" ]
stackoverflow_0074680717_dictionary_encryption_list_python.txt
Q: How to make a bat file so that it executes two different arguments I downloaded a project from Git that allows you to save books from various sites In order for it to work, you need to run cmd in the place where the repository is unzipped. For example, after running cmd and going to the repository location in cmd, to download the book, you need to do the following: Elib2Ebook.exe -u https://author.today/work/212721 -f epub Where "-u" is a mandatory argument followed by a link. "-f" is a mandatory argument, followed by the format (for example fb2 or epub) Elib2Ebook.exe - called program The problem is to automate the process a little bit so that you don't have to enter arguments every time. That is , at startup .bat file I just need to enter the argument twice, that is, just insert the link and just specify the format. I tried to implement it through %*, after call cmd, but I don't have enough knowledge to really do it, because the problem is that all the arguments need to be entered in one line, separated by the indication "-u" (URL) and "-f" (format) A: @echo off setlocal set /p "url=What URL https://" set /p "type=Format : " lib2Ebook.exe -u https://%url% -f %type% Save as whatever.bat Then run whatever Respond to the first prompt with author.today/work/212721 and to the second with epub Done! [untried]
How to make a bat file so that it executes two different arguments
I downloaded a project from Git that allows you to save books from various sites In order for it to work, you need to run cmd in the place where the repository is unzipped. For example, after running cmd and going to the repository location in cmd, to download the book, you need to do the following: Elib2Ebook.exe -u https://author.today/work/212721 -f epub Where "-u" is a mandatory argument followed by a link. "-f" is a mandatory argument, followed by the format (for example fb2 or epub) Elib2Ebook.exe - called program The problem is to automate the process a little bit so that you don't have to enter arguments every time. That is , at startup .bat file I just need to enter the argument twice, that is, just insert the link and just specify the format. I tried to implement it through %*, after call cmd, but I don't have enough knowledge to really do it, because the problem is that all the arguments need to be entered in one line, separated by the indication "-u" (URL) and "-f" (format)
[ "@echo off\nsetlocal\nset /p \"url=What URL https://\"\nset /p \"type=Format : \"\nlib2Ebook.exe -u https://%url% -f %type%\n\nSave as whatever.bat\nThen run whatever\nRespond to the first prompt with author.today/work/212721\nand to the second with epub\nDone!\n[untried]\n" ]
[ 0 ]
[]
[]
[ "batch_file", "cmd", "command_prompt", "windows" ]
stackoverflow_0074680559_batch_file_cmd_command_prompt_windows.txt
Q: How do you use FFMPEG to transcode h264_qsv from Apple PRORES Quicktime? I am trying to transcode an Apple Prores 444 to H.264 using qsv without success. If I use this command line: ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac -pix_fmt qsv chris.mp4 I get: ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help [h264_qsv @ 0x56265b81a800] Selected ratecontrol mode is unsupported [h264_qsv @ 0x56265b81a800] Low power mode is unsupported [h264_qsv @ 0x56265b81a800] Current frame rate is unsupported [h264_qsv @ 0x56265b81a800] Current picture structure is unsupported [h264_qsv @ 0x56265b81a800] Current resolution is unsupported [h264_qsv @ 0x56265b81a800] Current pixel format is unsupported [h264_qsv @ 0x56265b81a800] some encoding parameters are not supported by the QSV runtime. Please double check the input parameters. Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height Conversion failed! user@NUC:~$ ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac -pix_fmt qsv chris.mp4 ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scaler_0' Error reinitializing filters! Failed to inject frame into filter network: Function not implemented Error while processing the decoded data for stream #0:1 Conversion failed! If I use: ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac chris.mp4 I get: ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scaler_0' Error reinitializing filters! Failed to inject frame into filter network: Function not implemented Error while processing the decoded data for stream #0:1 Conversion failed! user@NUC:~$ ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac chris.mp4 ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help [h264_qsv @ 0x55b3bb6e8800] Selected ratecontrol mode is unsupported [h264_qsv @ 0x55b3bb6e8800] Low power mode is unsupported [h264_qsv @ 0x55b3bb6e8800] Current frame rate is unsupported [h264_qsv @ 0x55b3bb6e8800] Current picture structure is unsupported [h264_qsv @ 0x55b3bb6e8800] Current resolution is unsupported [h264_qsv @ 0x55b3bb6e8800] Current pixel format is unsupported [h264_qsv @ 0x55b3bb6e8800] some encoding parameters are not supported by the QSV runtime. Please double check the input parameters. Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height Conversion failed! I cannot get ANYTHING to work. I can transcode other h264 files without issue. I cannot seem to transcode this prores file. Here is a link to the source file if anyone can help I would REALLY appreciate it... https://www.dropbox.com/s/ejrfzad20yzaifm/10minute_Pipeline_Test.mov?dl=1 A: I use H264_QSV daily, and I find you have to declare the QSV device as being available. Try this: ffmpeg -err_detect ignore_err -hide_banner -loglevel verbose -init_hw_device qsv:qsv,child_device_type=qsv ^ -hwaccel qsv -hwaccel_output_format qsv -i "input.mov" -q:v 30 -preset slow -c:a aac output.mp4 There are many more options that can be added to improve efficiency, change the quality (the -q:v setting), etc. I've found that QSV speeds things up so much that you can use a -preset of slow or very slow to get more compression for a given quality setting without significantly increasing the time it takes to convert the file. A: I may not have done the copy as well as I should have. This is a more complete copy of how I use ffmpeg. ffmpeg -err_detect ignore_err -hide_banner -loglevel verbose -stats -benchmark -init_hw_device qsv:qsv,child_device_type=qsv ^ -hwaccel qsv -hwaccel_output_format qsv ^ -i "input file" ^ -c:a aac -q:a 1.9 -strict normal -sws_flags lanczos ^ -vf "vpp_qsv=cw=704:ch=480:cx=11:cy=0:w=640:h=480" ^ -async_depth 128 -q:v 28 -c:v h264_qsv -preset veryslow (a bunch of optimization options on how I want the compression to be done go in here, which can be discussed separately) -movflags +faststart "output file.mp4" This is on Windows so the carat "^" is the command line continuation character. -err_detect suppresses some of the more useless messages. -hide_banner suppresses things that I normally don't need to see at all. -loglevel is usually set to "info" or "quiet", but if you want to know exactly which codecs are being used, set it to "verbose" as it is here. This is the simple answer to the original question, "Am I using the QSV codec?". -strict normal is optional, but I found some applications didn't do well with some of the newer optimizations. It does not appear to increase file size to any significant extent, and I don't run into problems running videos on old equipment. I put the audio processing first as it seems to work better that way. I let the codec choose the bit rate by setting the quality, as with the video (see below). I have also included an example of the vpp_qsv video processing filter, as I find it speeds up many operations. It can, of course, be left out if you don't need it. I put it before the compression codec: ffmpeg will process them in the proper order, but I find it's easier to keep track of what's going on if I put the commands in about the same order as they will eventually be processed. When I put the commands in this order and "verbose" is on, ffmpeg reports that the output of the vpp_qsv filter remains in video memory as the input to the h264_qsv codec. This speeds things up in my tests: or, at least, it reduces the CPU load so other programs can run at the same time. -async_depth is optional, increases the number of frames that are read before compression is done; I find this also usually makes things go a bit faster. -q:v is the compression quality setting: I've found 28 to 30 gives me good results for watching videos on a reasonably large TV, but you will have to make tests for yourself to see what setting is right for you. Doing this is much, much better than guessing what bitrate you need, the codec can do better optimizations, and so on. You will, in most cases, get variable bit rate compression, and sometimes variable frame rates. This improves compression for parts of the video that don't have much going on, while still providing higher bit rates when needed. You may be surprised at how low a bit rate can be produced this way and still have a good quality video. I put -movflags +faststart in ALL of my MP4 videos. This moves a copy of the MOOV atom from the end of the video to the beginning. This does at least two things. First, for many players, the video will start playing faster as the information the player needs about the video is read immediately. Second, if an MP4 file ever gets truncated and the MOOV atom is missing, you will not be able to play the file at all. There are programs that pretend to be able to recover the missing information, but I have yet to see one actually work. But if the MOOV atom is also included at the beginning of the video, you will at least be able to start processing the video, and should at least get to the point where the file is damaged. It's cheap insurance, and only takes a moment or two. (This won't work if your output is a live stream, the video has to be "finished" before the atom is created.) -stats and -benchmark are optional, I like to see how fast processing is going and be able to compare it to other times I process videos to see if any changes I make to the options are helping or not. If there is an interest in the various vpp_qsv filter options, or in what other compression settings I use, or what settings will allow videos to work with Roku Media Player, let me know which topic I should post that in.
How do you use FFMPEG to transcode h264_qsv from Apple PRORES Quicktime?
I am trying to transcode an Apple Prores 444 to H.264 using qsv without success. If I use this command line: ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac -pix_fmt qsv chris.mp4 I get: ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help [h264_qsv @ 0x56265b81a800] Selected ratecontrol mode is unsupported [h264_qsv @ 0x56265b81a800] Low power mode is unsupported [h264_qsv @ 0x56265b81a800] Current frame rate is unsupported [h264_qsv @ 0x56265b81a800] Current picture structure is unsupported [h264_qsv @ 0x56265b81a800] Current resolution is unsupported [h264_qsv @ 0x56265b81a800] Current pixel format is unsupported [h264_qsv @ 0x56265b81a800] some encoding parameters are not supported by the QSV runtime. Please double check the input parameters. Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height Conversion failed! user@NUC:~$ ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac -pix_fmt qsv chris.mp4 ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scaler_0' Error reinitializing filters! Failed to inject frame into filter network: Function not implemented Error while processing the decoded data for stream #0:1 Conversion failed! If I use: ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac chris.mp4 I get: ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help Impossible to convert between the formats supported by the filter 'Parsed_null_0' and the filter 'auto_scaler_0' Error reinitializing filters! Failed to inject frame into filter network: Function not implemented Error while processing the decoded data for stream #0:1 Conversion failed! user@NUC:~$ ffmpeg -i 10minute_Pipeline_Test.mov -c:v h264_qsv -c:a aac chris.mp4 ffmpeg version 4.2.1 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-17ubuntu1~20.04) configuration: --prefix=/root/ffmpeg_build --extra-cflags=-I/root/ffmpeg_build/include --extra-ldflags=-L/root/ffmpeg_build/lib --bindir=/root/bin --extra-libs=-ldl --enable-gpl --enable-libass --enable-libfdk-aac --enable-libmp3lame --enable-nonfree --enable-libmfx libavutil 56. 31.100 / 56. 31.100 libavcodec 58. 54.100 / 58. 54.100 libavformat 58. 29.100 / 58. 29.100 libavdevice 58. 8.100 / 58. 8.100 libavfilter 7. 57.100 / 7. 57.100 libswscale 5. 5.100 / 5. 5.100 libswresample 3. 5.100 / 3. 5.100 libpostproc 55. 5.100 / 55. 5.100 Guessed Channel Layout for Input Stream #0.2 : mono Guessed Channel Layout for Input Stream #0.3 : mono Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '10minute_Pipeline_Test.mov': Metadata: major_brand : qt minor_version : 537134592 compatible_brands: qt creation_time : 2020-12-19T12:43:38.000000Z com.apple.quicktime.author: com.apple.quicktime.comment: com.apple.quicktime.copyright: com.apple.quicktime.description: com.apple.quicktime.director: com.apple.quicktime.genre: com.apple.quicktime.information: com.apple.quicktime.keywords: com.apple.quicktime.producer: com.apple.quicktime.displayname: timecode : 12:43:37;28 Duration: 00:10:06.72, start: 0.000000, bitrate: 167429 kb/s Stream #0:0(eng): Data: none (tmcd / 0x64636D74) Metadata: creation_time : 1970-01-04T00:49:14.000000Z timecode : 12:43:37;28 Stream #0:1(eng): Video: prores (Standard) (apcn / 0x6E637061), yuv422p10le(tv, GBR, progressive), 1280x720, 164985 kb/s, SAR 1:1 DAR 16:9, 59.94 fps, 59.94 tbr, 60k tbn, 60k tbc (default) Metadata: creation_time : 1970-01-01T00:00:04.000000Z Stream #0:2(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Stream #0:3(eng): Audio: pcm_s24le (in24 / 0x34326E69), 48000 Hz, mono, s32 (24 bit), 1152 kb/s (default) Metadata: creation_time : 2003-10-05T11:26:56.000000Z File 'chris.mp4' already exists. Overwrite ? [y/N] y Stream mapping: Stream #0:1 -> #0:0 (prores (native) -> h264 (h264_qsv)) Stream #0:2 -> #0:1 (pcm_s24le (native) -> aac (native)) Press [q] to stop, [?] for help [h264_qsv @ 0x55b3bb6e8800] Selected ratecontrol mode is unsupported [h264_qsv @ 0x55b3bb6e8800] Low power mode is unsupported [h264_qsv @ 0x55b3bb6e8800] Current frame rate is unsupported [h264_qsv @ 0x55b3bb6e8800] Current picture structure is unsupported [h264_qsv @ 0x55b3bb6e8800] Current resolution is unsupported [h264_qsv @ 0x55b3bb6e8800] Current pixel format is unsupported [h264_qsv @ 0x55b3bb6e8800] some encoding parameters are not supported by the QSV runtime. Please double check the input parameters. Error initializing output stream 0:0 -- Error while opening encoder for output stream #0:0 - maybe incorrect parameters such as bit_rate, rate, width or height Conversion failed! I cannot get ANYTHING to work. I can transcode other h264 files without issue. I cannot seem to transcode this prores file. Here is a link to the source file if anyone can help I would REALLY appreciate it... https://www.dropbox.com/s/ejrfzad20yzaifm/10minute_Pipeline_Test.mov?dl=1
[ "I use H264_QSV daily, and I find you have to declare the QSV device as being available.\nTry this:\nffmpeg -err_detect ignore_err -hide_banner -loglevel verbose -init_hw_device qsv:qsv,child_device_type=qsv ^ -hwaccel qsv -hwaccel_output_format qsv -i \"input.mov\" -q:v 30 -preset slow -c:a aac output.mp4\n\nThere are many more options that can be added to improve efficiency, change the quality (the -q:v setting), etc.\nI've found that QSV speeds things up so much that you can use a -preset of slow or very slow to get more compression for a given quality setting without significantly increasing the time it takes to convert the file.\n", "I may not have done the copy as well as I should have.\nThis is a more complete copy of how I use ffmpeg.\nffmpeg -err_detect ignore_err -hide_banner -loglevel verbose -stats -benchmark -init_hw_device qsv:qsv,child_device_type=qsv ^\n-hwaccel qsv -hwaccel_output_format qsv ^\n-i \"input file\" ^\n-c:a aac -q:a 1.9 -strict normal -sws_flags lanczos ^\n-vf \"vpp_qsv=cw=704:ch=480:cx=11:cy=0:w=640:h=480\" ^\n-async_depth 128 -q:v 28 -c:v h264_qsv -preset veryslow (a bunch of optimization options on how I want the compression to be done go in here, which can be discussed separately) -movflags +faststart \"output file.mp4\"\nThis is on Windows so the carat \"^\" is the command line continuation character.\n-err_detect suppresses some of the more useless messages. -hide_banner suppresses things that I normally don't need to see at all.\n-loglevel is usually set to \"info\" or \"quiet\", but if you want to know exactly which codecs are being used, set it to \"verbose\" as it is here.\nThis is the simple answer to the original question, \"Am I using the QSV codec?\".\n-strict normal is optional, but I found some applications didn't do well with some of the newer optimizations. It does not appear to increase file size to any significant extent, and I don't run into problems running videos on old equipment.\nI put the audio processing first as it seems to work better that way.\nI let the codec choose the bit rate by setting the quality, as with the video (see below).\nI have also included an example of the vpp_qsv video processing filter, as I find it speeds up many operations. It can, of course, be left out if you don't need it. I put it before the compression codec: ffmpeg will process them in the proper order, but I find it's easier to keep track of what's going on if I put the commands in about the same order as they will eventually be processed. When I put the commands in this order and \"verbose\" is on, ffmpeg reports that the output of the vpp_qsv filter remains in video memory as the input to the h264_qsv codec. This speeds things up in my tests: or, at least, it reduces the CPU load so other programs can run at the same time.\n-async_depth is optional, increases the number of frames that are read before compression is done; I find this also usually makes things go a bit faster. -q:v is the compression quality setting: I've found 28 to 30 gives me good results for watching videos on a reasonably large TV, but you will have to make tests for yourself to see what setting is right for you. Doing this is much, much better than guessing what bitrate you need, the codec can do better optimizations, and so on. You will, in most cases, get variable bit rate compression, and sometimes variable frame rates. This improves compression for parts of the video that don't have much going on, while still providing higher bit rates when needed. You may be surprised at how low a bit rate can be produced this way and still have a good quality video.\nI put -movflags +faststart in ALL of my MP4 videos. This moves a copy of the MOOV atom from the end of the video to the beginning. This does at least two things. First, for many players, the video will start playing faster as the information the player needs about the video is read immediately. Second, if an MP4 file ever gets truncated and the MOOV atom is missing, you will not be able to play the file at all. There are programs that pretend to be able to recover the missing information, but I have yet to see one actually work. But if the MOOV atom is also included at the beginning of the video, you will at least be able to start processing the video, and should at least get to the point where the file is damaged. It's cheap insurance, and only takes a moment or two. (This won't work if your output is a live stream, the video has to be \"finished\" before the atom is created.)\n-stats and -benchmark are optional, I like to see how fast processing is going and be able to compare it to other times I process videos to see if any changes I make to the options are helping or not.\nIf there is an interest in the various vpp_qsv filter options, or in what other compression settings I use, or what settings will allow videos to work with Roku Media Player, let me know which topic I should post that in.\n" ]
[ 0, 0 ]
[]
[]
[ "ffmpeg", "linux", "video", "video_processing" ]
stackoverflow_0065456873_ffmpeg_linux_video_video_processing.txt
Q: java task provider missing In my vs code the java is not supporting .there is some error. I can't understand and can't solve it . the error showing in the terminal](https://i.stack.imgur.com/uHYAB.png)the error showing in the terminal how should i run java in vs code I reffered lote of youtube video's and blogs but nothing is working . guide to proper working java on vs code A: Your class file is called hello.java, but the class defined in the file is called FibonacciExample1. Both names should be the same. You should either rename the file to FibonacciExample1.java or rename the class to hello.
java task provider missing
In my vs code the java is not supporting .there is some error. I can't understand and can't solve it . the error showing in the terminal](https://i.stack.imgur.com/uHYAB.png)the error showing in the terminal how should i run java in vs code I reffered lote of youtube video's and blogs but nothing is working . guide to proper working java on vs code
[ "Your class file is called hello.java, but the class defined in the file is called FibonacciExample1. Both names should be the same. You should either rename the file to FibonacciExample1.java or rename the class to hello.\n" ]
[ 1 ]
[]
[]
[ "java", "visual_studio_code" ]
stackoverflow_0074680783_java_visual_studio_code.txt
Q: SharePoint Online : manage folder permission with PowerShell I'm trying to write a Powershell script to grant user permission to a sub-folder in our SharePoint online site. I tried the solutions from the similar questions already open but without success. I've got an online SharePoint site : https://xxx.sharepoint.com/sites/MySharePoint In this SharePoint site I've got a library called Test which contains 2 sub-folders Test1 and Test2 I want the user "adtest@x.com" to be granted access to Test1 only in read/write (i.e. contributor). I used the following code : Connect-PnPOnline -Url $SiteURL -Credentials $psCred $folder = Get-PnPFolder -URL "https://xxx.sharepoint.com/sites/MySharePoint/Test/Test1" Set-PnPfolderPermission -list "Test" -identity $folder -User "adtest@x.com" -AddRole "Contribute" When I run these commands, on the last step I get an error which translates as : "Impossible to find the level of authorization". My system is in French so I had to translate the message. I tried the commands found from the other questions on the site but none worked. Has anybody any idea on the issue ? Thanks ! Fred A: In the pnp documention the identity is always the server relative path. Try that, just use as identity: "/Sites/MySharePoint/Test/Test1" A: try set the exact name of the permission role. Check it in the advanced permission level. System need the name in french language resp. in the language of site collection, not english. Example in slovak language which i use
SharePoint Online : manage folder permission with PowerShell
I'm trying to write a Powershell script to grant user permission to a sub-folder in our SharePoint online site. I tried the solutions from the similar questions already open but without success. I've got an online SharePoint site : https://xxx.sharepoint.com/sites/MySharePoint In this SharePoint site I've got a library called Test which contains 2 sub-folders Test1 and Test2 I want the user "adtest@x.com" to be granted access to Test1 only in read/write (i.e. contributor). I used the following code : Connect-PnPOnline -Url $SiteURL -Credentials $psCred $folder = Get-PnPFolder -URL "https://xxx.sharepoint.com/sites/MySharePoint/Test/Test1" Set-PnPfolderPermission -list "Test" -identity $folder -User "adtest@x.com" -AddRole "Contribute" When I run these commands, on the last step I get an error which translates as : "Impossible to find the level of authorization". My system is in French so I had to translate the message. I tried the commands found from the other questions on the site but none worked. Has anybody any idea on the issue ? Thanks ! Fred
[ "In the pnp documention the identity is always the server relative path.\nTry that, just use as identity:\n\"/Sites/MySharePoint/Test/Test1\"\n", "try set the exact name of the permission role. Check it in the advanced permission level.\nSystem need the name in french language resp. in the language of site collection, not english. Example in slovak language which i use\n" ]
[ 0, 0 ]
[]
[]
[ "powershell", "sharepoint_online" ]
stackoverflow_0072348999_powershell_sharepoint_online.txt
Q: Formula adding and removing classes JS I've been trying to make a formula that adds or removes classes from DOM. So far I've gotten this: export const short = [ { elementId: "short-sides", action: "add", className: "active" }, { elementId: "long-sides", action: "remove", className: "active" }, { elementId: "all-sides", action: "remove", className: "active" }, ]; I believe that below is what causes the problem, because after classList should be the dot, but with current set up it does not create one. const addRemoveClasses = element => { element.forEach(({ elementId, className, action }) => myDOMelement[elementId].classList[action](className)); }; myDOMelement['short-sides'].addEventListener("click", () => addRemoveClasses(short)); How shall I make it work? I've tried to insert the code below into the main script.js, but that doesn't help. export const short = [ { elementId: "short-sides", action: "add", className: "active" }, { elementId: "long-sides", action: "remove", className: "active" }, { elementId: "all-sides", action: "remove", className: "active" }, ]; inserting the dot before action obviously doesn't work too.. like .[action]. myDOMelement looks like this: const funGetX = () => { return x.reduce((acc, classX) => { acc[classX] = document.getElementById(classX); return acc; }, {}); } const myDOMelement = funGetX(); export default myDOMelement; A: If this is what you're after, I think you just need to modify the way you reference the target element... ... document.querySelector(`#${elementId}`).classList[action](className)); const short = [{ elementId: "this", action: "add", className: "active" }, { elementId: "that", action: "remove", className: "active" }, { elementId: "other", action: "remove", className: "active" }, ]; const addRemoveClasses = element => { element.forEach(({ elementId, className, action }) => document.querySelector(`#${elementId}`).classList[action](className)); }; document.querySelector('button').addEventListener("click", () => addRemoveClasses(short)); div { padding: 10px; border: 1px solid #222; } .active { background: yellow; } <div id='this'>This</div> <div id='that' class='active'>That</div> <div id='other' class='active'>Other</div> <button>test</button>
Formula adding and removing classes JS
I've been trying to make a formula that adds or removes classes from DOM. So far I've gotten this: export const short = [ { elementId: "short-sides", action: "add", className: "active" }, { elementId: "long-sides", action: "remove", className: "active" }, { elementId: "all-sides", action: "remove", className: "active" }, ]; I believe that below is what causes the problem, because after classList should be the dot, but with current set up it does not create one. const addRemoveClasses = element => { element.forEach(({ elementId, className, action }) => myDOMelement[elementId].classList[action](className)); }; myDOMelement['short-sides'].addEventListener("click", () => addRemoveClasses(short)); How shall I make it work? I've tried to insert the code below into the main script.js, but that doesn't help. export const short = [ { elementId: "short-sides", action: "add", className: "active" }, { elementId: "long-sides", action: "remove", className: "active" }, { elementId: "all-sides", action: "remove", className: "active" }, ]; inserting the dot before action obviously doesn't work too.. like .[action]. myDOMelement looks like this: const funGetX = () => { return x.reduce((acc, classX) => { acc[classX] = document.getElementById(classX); return acc; }, {}); } const myDOMelement = funGetX(); export default myDOMelement;
[ "If this is what you're after, I think you just need to modify the way you reference the target element...\n... document.querySelector(`#${elementId}`).classList[action](className));\n\n\n\nconst short = [{\n elementId: \"this\",\n action: \"add\",\n className: \"active\"\n },\n {\n elementId: \"that\",\n action: \"remove\",\n className: \"active\"\n },\n {\n elementId: \"other\",\n action: \"remove\",\n className: \"active\"\n },\n];\n\n\nconst addRemoveClasses = element => {\n element.forEach(({\n elementId,\n className,\n action\n }) => document.querySelector(`#${elementId}`).classList[action](className));\n\n};\ndocument.querySelector('button').addEventListener(\"click\", () => addRemoveClasses(short));\ndiv {\n padding: 10px;\n border: 1px solid #222;\n}\n\n.active {\n background: yellow;\n}\n<div id='this'>This</div>\n<div id='that' class='active'>That</div>\n<div id='other' class='active'>Other</div>\n<button>test</button>\n\n\n\n" ]
[ 1 ]
[]
[]
[ "javascript" ]
stackoverflow_0074680095_javascript.txt
Q: When iPhone scans a QR with built in camera capabilities it opens it is SafariI. Is it possible to detect this case with JavaScript? The problem is that in this case there is no option to install the page in Home Screen. I would like detect the situation and issue a message to guide the user on how to do it: select navigator button to open the page in Safari, which then will have the option to install in Home Screen. I don’t know if there is an user agent string specific to case when safari is opened by qr reader. A: use the navigator.userAgent property in JavaScript to access the user agent string for the current browser. if (navigator.userAgent.includes("Safari") && navigator.userAgent.includes("iPhone")) { alert("To install this page on your home screen, please open it in Safari and follow the instructions"); }
When iPhone scans a QR with built in camera capabilities it opens it is SafariI. Is it possible to detect this case with JavaScript?
The problem is that in this case there is no option to install the page in Home Screen. I would like detect the situation and issue a message to guide the user on how to do it: select navigator button to open the page in Safari, which then will have the option to install in Home Screen. I don’t know if there is an user agent string specific to case when safari is opened by qr reader.
[ "use the navigator.userAgent property in JavaScript to access the user agent string for the current browser.\nif (navigator.userAgent.includes(\"Safari\") && navigator.userAgent.includes(\"iPhone\")) {\n alert(\"To install this page on your home screen, please open it in Safari and follow the instructions\");\n}\n\n" ]
[ 0 ]
[]
[]
[ "homescreen", "iphone", "javascript", "progressive_web_apps", "safari" ]
stackoverflow_0074680762_homescreen_iphone_javascript_progressive_web_apps_safari.txt
Q: How to reduce storage(scale down) my RDS instance? I have a RDS(Postgres) instance with Storage SSD 1000GB, but the data is only 100GB of size. How can I scale down the storage resource of RDS easily ? A: RDS does not allow you to reduce the amount of storage allocated to a database instance, only increase it. To move your database to less storage you would have to create a new RDS instance with your desired storage space, then use something like pg_dump/pg_restore to move the data from the old database to the new one. Also be aware that an RDS instance with 1,000GB of SSD storage has a base IOPS of 3,000. An RDS instance with 100GB of SSD storage has a base IOPS of 300, with occasional bursts of up to 3,000. A: Based on AWS's help here, this is the full process that worked for me: 1) Dump the database to a file: run this on a machine that has network access to the database: pg_dump -Fc -v -h your-rds-endpoint.us-west-2.rds.amazonaws.com -U your-username your-databasename > your-databasename.dump 2) In the AWS console, create a new RDS instance with smaller storage. (You probably want to set it up with the same username, password, and database name.) 3) Restore the database on the new RDS instance: run this command (obviously on the same machine as the previous command): pg_restore -v -h the-new-rds-endpoint.us-west-2.rds.amazonaws.com -U your-username -d your-databasename your-databasename.dump (Note, in step 3, that I'm using the endpoint of the new RDS instance. Also note there's no :5432 at the end of the endpoint addresses.) A: Amazon doesn't allow to reduce size of HDD of RDS instance, you may have two options to reduce size of storage. 1:-if you can afford downtimes, then mysqldump backup of old instance can be restored to new instance having lesser storage size. 2:- You can use Database migration service to move data from one instance to another instance without any downtime. A: When using RDS, instead of doing typical hardware "capacity planning", you just provisioning just enough disk space for short or medium term (depends), expand it when needed. As @Mark B mentioned , you need to watchout the IOPS as well. You can use "provisioned IOPS" if you need high performance DB. You should make you cost vs performance adjustment before jump into the disk space storage part. E.g. if you reduce 1000GB to 120GB , for US west, you will save 0.125x 880GB = 110/month. But the Max IOPS will be 120x 3 = 360IOPS It will cost you $0.10 to provision additional IOPS to increase performance. Say if you actually need 800IOPS for higher online user response, (800-360) x 0.10 = $44. So the actual saving may eventually "less". You will not save any money if your RDS need constant 1100 IOPS. And also other discount factor may come into play. A: You can do this by migrating the DB to Aurora. If you don't want Aurora, the Data Migration Service is the best option in my opinion. We're moving production to Aurora, so this didn't matter, and we can always get it back out of Aurora using pg_dump or DMS. (I assume this will apply to MySQL as well, but haven't tested it.) My specific goal was to reduce RDS Postgres final snapshot sizes after decommissioning some instances that were initially created with 1TB+ storage each. Create the normal snapshot. The full provisioned storage size is allocated to the snapshot. Upgrade the snapshot to an engine version supported by Aurora, if not already supported. I chose 10.7. Migrate the snapshot to Aurora. This creates a new Aurora DB. Snapshot the new Aurora DB. The snapshot storage size starts as the full provisioned size, but drops to actual used storage after completion. Remove the new Aurora DB. Confirm your Aurora snapshot is good by restoring it again and poking around in the new new DB until you're satisfied that the original snapshots can be deleted. Remove new new Aurora DB and original snapshot. You can stop at 3 if you want and just use the Aurora DB going forward. A: The #2 answer does not work on Windows 10 because, per this dba overflow question, the shell re-encodes the output when the > operator is used. The pg_dump will generate a file, but the pg_restore gives the cryptic error: pg_restore: [archiver] did not find magic string in file header Add -E UTF8 and -f instead of >: pg_dump -Fc -v -E UTF8 -h your-rds-endpoint.us-west-2.rds.amazonaws.com -U your-username your-databasename -f your-databasename.dump
How to reduce storage(scale down) my RDS instance?
I have a RDS(Postgres) instance with Storage SSD 1000GB, but the data is only 100GB of size. How can I scale down the storage resource of RDS easily ?
[ "RDS does not allow you to reduce the amount of storage allocated to a database instance, only increase it. \nTo move your database to less storage you would have to create a new RDS instance with your desired storage space, then use something like pg_dump/pg_restore to move the data from the old database to the new one.\nAlso be aware that an RDS instance with 1,000GB of SSD storage has a base IOPS of 3,000. An RDS instance with 100GB of SSD storage has a base IOPS of 300, with occasional bursts of up to 3,000.\n", "Based on AWS's help here, this is the full process that worked for me:\n1) Dump the database to a file: run this on a machine that has network access to the database:\n\npg_dump -Fc -v -h your-rds-endpoint.us-west-2.rds.amazonaws.com -U your-username your-databasename > your-databasename.dump\n\n2) In the AWS console, create a new RDS instance with smaller storage. (You probably want to set it up with the same username, password, and database name.)\n3) Restore the database on the new RDS instance: run this command (obviously on the same machine as the previous command):\n\npg_restore -v -h the-new-rds-endpoint.us-west-2.rds.amazonaws.com -U your-username -d your-databasename your-databasename.dump\n\n(Note, in step 3, that I'm using the endpoint of the new RDS instance. Also note there's no :5432 at the end of the endpoint addresses.)\n", "Amazon doesn't allow to reduce size of HDD of RDS instance, you may have two options to reduce size of storage.\n1:-if you can afford downtimes, then mysqldump backup of old instance can be restored to new instance having lesser storage size.\n2:- You can use Database migration service to move data from one instance to another instance without any downtime.\n", "When using RDS, instead of doing typical hardware \"capacity planning\", you just provisioning just enough disk space for short or medium term (depends), expand it when needed. \nAs @Mark B mentioned , you need to watchout the IOPS as well. You can use \"provisioned IOPS\" if you need high performance DB. \nYou should make you cost vs performance adjustment before jump into the disk space storage part. \nE.g. if you reduce 1000GB to 120GB , for US west, you will save 0.125x 880GB = 110/month. But the Max IOPS will be 120x 3 = 360IOPS\nIt will cost you $0.10 to provision additional IOPS to increase performance. Say if you actually need 800IOPS for higher online user response,\n(800-360) x 0.10 = $44. So the actual saving may eventually \"less\". You will not save any money if your RDS need constant 1100 IOPS. And also other discount factor may come into play. \n", "You can do this by migrating the DB to Aurora.\nIf you don't want Aurora, the Data Migration Service is the best option in my opinion. We're moving production to Aurora, so this didn't matter, and we can always get it back out of Aurora using pg_dump or DMS. (I assume this will apply to MySQL as well, but haven't tested it.)\nMy specific goal was to reduce RDS Postgres final snapshot sizes after decommissioning some instances that were initially created with 1TB+ storage each. \n\nCreate the normal snapshot. The full provisioned storage size is allocated to the snapshot.\nUpgrade the snapshot to an engine version supported by Aurora, if not already supported. I chose 10.7.\nMigrate the snapshot to Aurora. This creates a new Aurora DB.\nSnapshot the new Aurora DB. The snapshot storage size starts as the full provisioned size, but drops to actual used storage after completion.\nRemove the new Aurora DB.\nConfirm your Aurora snapshot is good by restoring it again and poking around in the new new DB until you're satisfied that the original snapshots can be deleted.\nRemove new new Aurora DB and original snapshot.\n\nYou can stop at 3 if you want and just use the Aurora DB going forward.\n", "The #2 answer does not work on Windows 10 because, per this dba overflow question, the shell re-encodes the output when the > operator is used. The pg_dump will generate a file, but the pg_restore gives the cryptic error:\npg_restore: [archiver] did not find magic string in file header\n\nAdd -E UTF8 and -f instead of >:\npg_dump -Fc -v -E UTF8 -h your-rds-endpoint.us-west-2.rds.amazonaws.com -U your-username your-databasename -f your-databasename.dump\n\n" ]
[ 27, 18, 7, 4, 3, 0 ]
[]
[]
[ "amazon_rds", "amazon_web_services", "postgresql" ]
stackoverflow_0036746475_amazon_rds_amazon_web_services_postgresql.txt
Q: Using pm2 Inside of an Auto-Scaling Environment I am planning to use the AWS EC2 Container Service to host an auto-scaling group of Node.js + Express instances that expose a REST API. I've seen multiple articles telling me that I should be using pm2 over forever.js in order to ensure that my application restarts if it crashes, that I can have smooth application reloads, etc. However, I'm a bit confused as to what configuration I should use with pm2 inside of the container. As these instances will be scaled automatically, should I still be running the process manager in "cluster mode"? I want to be sure that I am getting the most out of my instances, and I can't seem to find any definitive answers about whether clustering is necessary in an auto-scaling environment like this (just that pm2 comes with a load-balancer and scaling technique itself). A: I would use systemd over pm2 in any case, as its native on most Linux distros now and effectively one less step (with pm2 you still need to make the pm2 daemon a service). As for running cluster, etc, I think that depends a great deal on what your Node app is doing. As such,I'd probably deploy containers that don't use it, scale as a container rather than inside, and profile for a while. This keeps things inside each container as simple as possible and lets the EVS service manager do its job. When most folks use the cluster module, they make one worker or maybe two per CPU core. Given that a container is sharing CPU cores with any other containers on the host, it seems like your not getting much bang for the additional complexity. A: We have the same situation with AWS EC2 cluster. We created 1 load balancer and 2 server with many CPUs and memory to manage all our applications. Every node.js application has own container and minimum required memory (for example 1GB). Inside every container we have PM2 with memory limit to restart every process (prevent memory leak) and no limit on CPU or memory for container. Every application has minimum 2 instances inside container (in common 4 instances for both servers). Also i wrote a small PM2 plugin to automatically scale application inside containers depends on the load and it helps us to scale application to up to MAX CPUs-1. So, you can try to use it https://www.npmjs.com/package/pm2-autoscale and share feedback. And we have autoscale configuration inside AWS cluster if cluster does not have enough power.
Using pm2 Inside of an Auto-Scaling Environment
I am planning to use the AWS EC2 Container Service to host an auto-scaling group of Node.js + Express instances that expose a REST API. I've seen multiple articles telling me that I should be using pm2 over forever.js in order to ensure that my application restarts if it crashes, that I can have smooth application reloads, etc. However, I'm a bit confused as to what configuration I should use with pm2 inside of the container. As these instances will be scaled automatically, should I still be running the process manager in "cluster mode"? I want to be sure that I am getting the most out of my instances, and I can't seem to find any definitive answers about whether clustering is necessary in an auto-scaling environment like this (just that pm2 comes with a load-balancer and scaling technique itself).
[ "I would use systemd over pm2 in any case, as its native on most Linux distros now and effectively one less step (with pm2 you still need to make the pm2 daemon a service). \nAs for running cluster, etc, I think that depends a great deal on what your Node app is doing. As such,I'd probably deploy containers that don't use it, scale as a container rather than inside, and profile for a while. This keeps things inside each container as simple as possible and lets the EVS service manager do its job. \nWhen most folks use the cluster module, they make one worker or maybe two per CPU core. Given that a container is sharing CPU cores with any other containers on the host, it seems like your not getting much bang for the additional complexity. \n", "We have the same situation with AWS EC2 cluster. We created 1 load balancer and 2 server with many CPUs and memory to manage all our applications. Every node.js application has own container and minimum required memory (for example 1GB).\nInside every container we have PM2 with memory limit to restart every process (prevent memory leak) and no limit on CPU or memory for container. Every application has minimum 2 instances inside container (in common 4 instances for both servers).\nAlso i wrote a small PM2 plugin to automatically scale application inside containers depends on the load and it helps us to scale application to up to MAX CPUs-1. So, you can try to use it https://www.npmjs.com/package/pm2-autoscale and share feedback.\nAnd we have autoscale configuration inside AWS cluster if cluster does not have enough power.\n" ]
[ 1, 0 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "docker", "node.js", "pm2" ]
stackoverflow_0040554243_amazon_ec2_amazon_web_services_docker_node.js_pm2.txt
Q: Tkinter: pass arguments when threading a function I'm trying to pass some arguments while threading a function, this is my code: import tkinter as tk from PIL import ImageTk, Image, ImageGrab import time import threading class Flashing(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.first_label = tk.Label(self, image="", foreground="black") self.first_label.pack(padx=50, side="left", anchor="w") self.button = tk.Button( self, text="start", command=threading.Thread(target=self.flash_all, args=[label, img]).start(), ) self.button.pack() def flash_all(self, label, img): for num in range(6): num += 1 if (num % 2) == 0: print("{0} is Even".format(num)) time.sleep(1) label.config(text="one) if (num % 2) == 1: print("{0} is Odd".format(num)) time.sleep(1) self.bip1.play(loops=0) label.config(text='two') if num == 6: time.sleep(1) self.bip2.play(loops=0) label.config(text='three') time.sleep(5) label.config(image="") if __name__ == "__main__": root = tk.Tk() Flashing(root).pack(side="top", fill="both", expand=True) root.mainloop() But I'm getting this error (virt) What shoudl I change to fix it? Important: I've trimmed and change some label in my code to make it more easy to read. The original work fine except for the error I've mention. Thanks you all A: It looks like the Thread object is being called immediately instead of being passed to the Button's command attribute. To fix this, you can define a new function that creates a Thread object and starts it, then pass that function to the Button's command attribute. import tkinter as tk import threading import time class Flashing(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.first_label = tk.Label(self, image="", foreground="black") self.first_label.pack(padx=50, side="left", anchor="w") self.button = tk.Button(self, text="start", command=self.start_flash_all) self.button.pack() def start_flash_all(self): # Define a new function that creates a Thread object and starts it def flash_all_thread(): for num in range(6): num += 1 if (num % 2) == 0: print("{0} is Even".format(num)) time.sleep(1) label.config(text="one") if (num % 2) == 1: print("{0} is Odd".format(num)) time.sleep(1) self.bip1.play(loops=0) label.config(text="two") if num == 6: time.sleep(1) self.bip2.play(loops=0) label.config(text="three") time.sleep(5) label.config(image="") # Create a Thread object and start it thread = threading.Thread(target=flash_all_thread) thread.start() if __name__ == "__main__": root = tk.Tk() Flashing(root).pack(side="top", fill="both", expand=True) root.mainloop() In this example, the start_flash_all function creates a new function called flash_all_thread that contains the code from your flash_all function, then creates a Thread object using that function as the target and starts it. This allows you to pass the Thread object to the Button's command attribute without calling it immediately.
Tkinter: pass arguments when threading a function
I'm trying to pass some arguments while threading a function, this is my code: import tkinter as tk from PIL import ImageTk, Image, ImageGrab import time import threading class Flashing(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.first_label = tk.Label(self, image="", foreground="black") self.first_label.pack(padx=50, side="left", anchor="w") self.button = tk.Button( self, text="start", command=threading.Thread(target=self.flash_all, args=[label, img]).start(), ) self.button.pack() def flash_all(self, label, img): for num in range(6): num += 1 if (num % 2) == 0: print("{0} is Even".format(num)) time.sleep(1) label.config(text="one) if (num % 2) == 1: print("{0} is Odd".format(num)) time.sleep(1) self.bip1.play(loops=0) label.config(text='two') if num == 6: time.sleep(1) self.bip2.play(loops=0) label.config(text='three') time.sleep(5) label.config(image="") if __name__ == "__main__": root = tk.Tk() Flashing(root).pack(side="top", fill="both", expand=True) root.mainloop() But I'm getting this error (virt) What shoudl I change to fix it? Important: I've trimmed and change some label in my code to make it more easy to read. The original work fine except for the error I've mention. Thanks you all
[ "It looks like the Thread object is being called immediately instead of being passed to the Button's command attribute. To fix this, you can define a new function that creates a Thread object and starts it, then pass that function to the Button's command attribute.\nimport tkinter as tk\nimport threading\nimport time\n\n\nclass Flashing(tk.Frame):\n def __init__(self, parent, *args, **kwargs):\n tk.Frame.__init__(self, parent, *args, **kwargs)\n\n self.first_label = tk.Label(self, image=\"\", foreground=\"black\")\n self.first_label.pack(padx=50, side=\"left\", anchor=\"w\")\n\n self.button = tk.Button(self, text=\"start\", command=self.start_flash_all)\n self.button.pack()\n\n def start_flash_all(self):\n # Define a new function that creates a Thread object and starts it\n def flash_all_thread():\n for num in range(6):\n num += 1\n if (num % 2) == 0:\n print(\"{0} is Even\".format(num))\n time.sleep(1)\n label.config(text=\"one\")\n if (num % 2) == 1:\n print(\"{0} is Odd\".format(num))\n time.sleep(1)\n self.bip1.play(loops=0)\n label.config(text=\"two\")\n if num == 6:\n time.sleep(1)\n self.bip2.play(loops=0)\n label.config(text=\"three\")\n time.sleep(5)\n label.config(image=\"\")\n\n # Create a Thread object and start it\n thread = threading.Thread(target=flash_all_thread)\n thread.start()\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n Flashing(root).pack(side=\"top\", fill=\"both\", expand=True)\n root.mainloop()\n\nIn this example, the start_flash_all function creates a new function called flash_all_thread that contains the code from your flash_all function, then creates a Thread object using that function as the target and starts it. This allows you to pass the Thread object to the Button's command attribute without calling it immediately.\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074680767_python_tkinter.txt
Q: D3 - How to turn rollup with multiple nestings into array? In my data, I did the following rollup using D3: datag = d3.rollup(kmeans_data, v => d3.sum(v,d=>d.value),d=>d.attribute,d=>d.label) The output for this is a InternMap with InternMaps. When my roullpup has only one filtering, I can turn it into an array using something like: [...datag].map(([attribute, value]) => ({ attribute, value })); My question is how to do it if I have multiple nestings, since the code above only turns the first InternMap into an array, thus, I get an Array of InternMaps, instead of an Array of Arrays. A: I think what you are/were after is flatRollup athletes = [ {name: "Floyd Mayweather", sport: "Boxing", nation: "United States", earnings: 285}, {name: "Lionel Messi", sport: "Soccer", nation: "Argentina", earnings: 111}, {name: "Cristiano Ronaldo", sport: "Soccer", nation: "Portugal", earnings: 108}, {name: "Conor McGregor", sport: "MMA", nation: "Ireland", earnings: 99}, {name: "Neymar", sport: "Soccer", nation: "Brazil", earnings: 90}, {name: "LeBron James", sport: "Basketball", nation: "United States", earnings: 85.5}, {name: "Roger Federer", sport: "Tennis", nation: "Switzerland", earnings: 77.2}, {name: "Stephen Curry", sport: "Basketball", nation: "United States", earnings: 76.9}, {name: "Matt Ryan", sport: "Football", nation: "United States", earnings: 67.3}, {name: "Matthew Stafford", sport: "Football", nation: "United States", earnings: 59.5} ] datax = d3.flatRollup(athletes, v => d3.sum(v,d=>d.earnings),d=>d.nation,d=>d.sport) console.log(datax);
D3 - How to turn rollup with multiple nestings into array?
In my data, I did the following rollup using D3: datag = d3.rollup(kmeans_data, v => d3.sum(v,d=>d.value),d=>d.attribute,d=>d.label) The output for this is a InternMap with InternMaps. When my roullpup has only one filtering, I can turn it into an array using something like: [...datag].map(([attribute, value]) => ({ attribute, value })); My question is how to do it if I have multiple nestings, since the code above only turns the first InternMap into an array, thus, I get an Array of InternMaps, instead of an Array of Arrays.
[ "I think what you are/were after is flatRollup\nathletes = [\n {name: \"Floyd Mayweather\", sport: \"Boxing\", nation: \"United States\", earnings: 285},\n {name: \"Lionel Messi\", sport: \"Soccer\", nation: \"Argentina\", earnings: 111},\n {name: \"Cristiano Ronaldo\", sport: \"Soccer\", nation: \"Portugal\", earnings: 108},\n {name: \"Conor McGregor\", sport: \"MMA\", nation: \"Ireland\", earnings: 99},\n {name: \"Neymar\", sport: \"Soccer\", nation: \"Brazil\", earnings: 90},\n {name: \"LeBron James\", sport: \"Basketball\", nation: \"United States\", earnings: 85.5},\n {name: \"Roger Federer\", sport: \"Tennis\", nation: \"Switzerland\", earnings: 77.2},\n {name: \"Stephen Curry\", sport: \"Basketball\", nation: \"United States\", earnings: 76.9},\n {name: \"Matt Ryan\", sport: \"Football\", nation: \"United States\", earnings: 67.3},\n {name: \"Matthew Stafford\", sport: \"Football\", nation: \"United States\", earnings: 59.5}\n]\n\ndatax = d3.flatRollup(athletes, v => d3.sum(v,d=>d.earnings),d=>d.nation,d=>d.sport)\nconsole.log(datax);\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "d3.js", "javascript" ]
stackoverflow_0067009122_arrays_d3.js_javascript.txt
Q: delete all words with more than 4 letters in a string (Pascal)? I was assigned a task for university where I have to write a program which deletes all words with more than 4 letters. I really have no clue at all. I would be very thankful for any kind of help. VAR UserString: string; //должна быть строка на 40 символов и точку в конце i, n: byte; BEGIN Writeln('Enter the string:'); Readln(UserString); i:=0; n:=1; repeat //MAIN LOOP: inc(i); if (UserString[i] = ' ') or (UserString[i] = '.') then begin if (i-n<3)then begin delete(UserString, n, i-n+1); i:=n-1; end; n:=i+1 end until (UserString[i] = '.') or (i>length(UserString)); Writeln('Result String: ', UserString); END. I tried this. and its working on onlinegdb but not on Delphi... and I don't know why... A: You should break up the logic into smaller utility functions for each task you need (finding a word, getting the word's length, deleting the word and any subsequent whitespace, etc). It will make the code easier to read and maintain. For example: function FindNextWordStart(const S: string; var Index: Integer): Boolean; var Len: Integer; begin Len := Length(S); while (Index <= Len) and (Ord(S[Index]) <= 32) do Inc(Index); Result := (Index <= Len); end; function GetWordLength(const S: string; Index: Integer): Integer; var StartIdx, Len: Integer; begin Len := Length(S); StartIdx := Index; while (Index <= Len) and (Ord(S[Index]) > 32) do Inc(Index); Result := (Index - StartIdx); end; procedure DeleteWord(var S: String; Index, WordLen: Integer); var StartIdx, Len: Integer; begin Len := Length(S); StartIdx := Index; Inc(Index, WordLen); while (Index <= Len) and (Ord(S[Index]) <= 32) do Inc(Index); Delete(S, StartIdx, Index - StartIdx); end; var UserString: string; StartIdx, WordLen: Integer; begin Writeln('Enter the string:'); Readln(UserString); StartIdx := 1; while FindNextWordStart(UserString, StartIdx) do begin WordLen := GetWordLength(UserString, StartIdx); if WordLen > 4 then DeleteWord(UserString, StartIdx, WordLen) else Inc(StartIdx, WordLen); end; Writeln('Result String: ', UserString); end. Online Demo A: I guess you can solve your task with TStringlist class: var AStrLst : TStringlist ; i : Integer , begin AStrLst := TStringlist.Create ; try // use this char for separation of words AStrLst.Delimiter :=' '; AStrLst.DelimitedText := ' here comes my sample string '; for I := AStrLst.Count-1 to 0 do begin // delete item from list if ... if length( trim(AStrLst[i])) <= 4 then AStrLst.Delete(i); end; finally // get the complete writeln ( AStrLst.Text ) ; AStrLst.Free; end; end; I did not test this code - but hope it helps - to get this code running, your home work
delete all words with more than 4 letters in a string (Pascal)?
I was assigned a task for university where I have to write a program which deletes all words with more than 4 letters. I really have no clue at all. I would be very thankful for any kind of help. VAR UserString: string; //должна быть строка на 40 символов и точку в конце i, n: byte; BEGIN Writeln('Enter the string:'); Readln(UserString); i:=0; n:=1; repeat //MAIN LOOP: inc(i); if (UserString[i] = ' ') or (UserString[i] = '.') then begin if (i-n<3)then begin delete(UserString, n, i-n+1); i:=n-1; end; n:=i+1 end until (UserString[i] = '.') or (i>length(UserString)); Writeln('Result String: ', UserString); END. I tried this. and its working on onlinegdb but not on Delphi... and I don't know why...
[ "You should break up the logic into smaller utility functions for each task you need (finding a word, getting the word's length, deleting the word and any subsequent whitespace, etc). It will make the code easier to read and maintain.\nFor example:\nfunction FindNextWordStart(const S: string; var Index: Integer): Boolean;\nvar\n Len: Integer;\nbegin\n Len := Length(S);\n while (Index <= Len) and (Ord(S[Index]) <= 32) do Inc(Index);\n Result := (Index <= Len);\nend;\n\nfunction GetWordLength(const S: string; Index: Integer): Integer;\nvar\n StartIdx, Len: Integer;\nbegin\n Len := Length(S);\n StartIdx := Index;\n while (Index <= Len) and (Ord(S[Index]) > 32) do Inc(Index);\n Result := (Index - StartIdx);\nend;\n\nprocedure DeleteWord(var S: String; Index, WordLen: Integer);\nvar\n StartIdx, Len: Integer;\nbegin\n Len := Length(S);\n StartIdx := Index;\n Inc(Index, WordLen);\n while (Index <= Len) and (Ord(S[Index]) <= 32) do Inc(Index);\n Delete(S, StartIdx, Index - StartIdx);\nend;\n\nvar\n UserString: string;\n StartIdx, WordLen: Integer;\nbegin\n Writeln('Enter the string:');\n Readln(UserString);\n\n StartIdx := 1;\n while FindNextWordStart(UserString, StartIdx) do\n begin\n WordLen := GetWordLength(UserString, StartIdx);\n if WordLen > 4 then\n DeleteWord(UserString, StartIdx, WordLen)\n else\n Inc(StartIdx, WordLen);\n end;\n\n Writeln('Result String: ', UserString);\nend.\n\nOnline Demo\n", "I guess you can solve your task with TStringlist class:\nvar AStrLst : TStringlist ;\n i : Integer ,\nbegin\n AStrLst := TStringlist.Create ;\n try\n // use this char for separation of words \n AStrLst.Delimiter :=' ';\n AStrLst.DelimitedText := ' here comes my sample string ';\n\n for I := AStrLst.Count-1 to 0 do\n begin\n // delete item from list if ...\n if length( trim(AStrLst[i])) <= 4 then AStrLst.Delete(i);\n end;\n finally\n // get the complete\n writeln ( AStrLst.Text ) ;\n AStrLst.Free;\n end;\nend; \n\nI did not test this code - but hope it helps - to get this code running, your home work\n" ]
[ 0, 0 ]
[]
[]
[ "delphi", "pascal" ]
stackoverflow_0074629931_delphi_pascal.txt
Q: Render object as Blazor component, not ToString() If I run the code below, the page shows just ToString() results, not the components. Is there a way to make @child rendered just as when I hardcoded <Dog> or <Cat>? I do not know what parent class or interface a Razor component inherits, so I just used an object List. Index.razor @page "/" @foreach(var child in children) { @child; } @code{ List<object> children = new(); protected override void OnInitialized() { children.Add(new Dog() { Message = "Doge" }); children.Add(new Cat() { Message = "Meow" }); } } Cat.razor <h3>The cat says @Message</h3> @code { [Parameter] public string Message{ get; set; } } Dog.razor <h3>The dog says @Message</h3> @code { [Parameter] public string Message{ get; set; } } A: You don't create instances of components and then hand them to the renderer to use. The Renderer manages component lifecycles. To do want you want in the question you need to use the DynamicComponent like this: Cat (to make it distinct) <div class="alert alert-success"> <h3>The cat says @Message</h3> </div> @code { [Parameter] public string? Message { get; set; } } Dog (again distinct): <div class="alert alert-danger"> <h3>The dog says @Message</h3> </div> @code { [Parameter] public string? Message { get; set; } } And Index to show how to use them: @page "/" <PageTitle>Index</PageTitle> <h1>Hello, world!</h1> @foreach(var component in this.Components) { <DynamicComponent Type=component.ComponentType Parameters=component.Parameters /> } @code { private List<Component> Components = new List<Component> { new Component { ComponentType = typeof(Dog), Parameters = new Dictionary<string, object>() { { "Message", "DogE" } } }, new Component { ComponentType = typeof(Cat), Parameters = new Dictionary<string, object>() { { "Message", "Meow" } } }, }; private class Component { public Type? ComponentType { get; set; } public Dictionary<string, object>? Parameters { get; set; } } } Which will give you:
Render object as Blazor component, not ToString()
If I run the code below, the page shows just ToString() results, not the components. Is there a way to make @child rendered just as when I hardcoded <Dog> or <Cat>? I do not know what parent class or interface a Razor component inherits, so I just used an object List. Index.razor @page "/" @foreach(var child in children) { @child; } @code{ List<object> children = new(); protected override void OnInitialized() { children.Add(new Dog() { Message = "Doge" }); children.Add(new Cat() { Message = "Meow" }); } } Cat.razor <h3>The cat says @Message</h3> @code { [Parameter] public string Message{ get; set; } } Dog.razor <h3>The dog says @Message</h3> @code { [Parameter] public string Message{ get; set; } }
[ "You don't create instances of components and then hand them to the renderer to use. The Renderer manages component lifecycles.\nTo do want you want in the question you need to use the DynamicComponent like this:\nCat (to make it distinct)\n<div class=\"alert alert-success\">\n <h3>The cat says @Message</h3>\n</div>\n\n@code {\n [Parameter] public string? Message { get; set; }\n}\n\nDog (again distinct):\n<div class=\"alert alert-danger\">\n <h3>The dog says @Message</h3>\n</div>\n\n@code {\n [Parameter] public string? Message { get; set; }\n}\n\nAnd Index to show how to use them:\n@page \"/\"\n\n<PageTitle>Index</PageTitle>\n\n<h1>Hello, world!</h1>\n\n@foreach(var component in this.Components)\n{\n <DynamicComponent Type=component.ComponentType Parameters=component.Parameters />\n}\n\n@code {\n\n private List<Component> Components = new List<Component> {\n new Component { ComponentType = typeof(Dog), Parameters = new Dictionary<string, object>() { { \"Message\", \"DogE\" } } },\n new Component { ComponentType = typeof(Cat), Parameters = new Dictionary<string, object>() { { \"Message\", \"Meow\" } } },\n };\n\n private class Component\n {\n public Type? ComponentType { get; set; }\n public Dictionary<string, object>? Parameters { get; set; }\n }\n}\n\nWhich will give you:\n\n" ]
[ 0 ]
[]
[]
[ "blazor" ]
stackoverflow_0074680415_blazor.txt
Q: Pandas Dataframe Matrix Multiplication using @ I am attempting to perform matrix multiplication between a Pandas DataFrame and a Pandas Series. I've set them up like so: c = pd.DataFrame({ "s1":[.04, .018, .0064], "s2":[.018, .0225, .0084], "s3":[.0064, .0084, .0064], }) x = pd.Series([0,0,0], copy = False) I want to perform x @ c @ x, but I keep getting a ValueError: matrices are not aligned error flag. Am I not setting up my matrices properly? I'm not sure where I am going wrong. A: x @ c returns a Series object which has different indices as x. You can use the underlying numpy array to do the calculation: (x @ c).values @ x.values # 0.39880000000000004
Pandas Dataframe Matrix Multiplication using @
I am attempting to perform matrix multiplication between a Pandas DataFrame and a Pandas Series. I've set them up like so: c = pd.DataFrame({ "s1":[.04, .018, .0064], "s2":[.018, .0225, .0084], "s3":[.0064, .0084, .0064], }) x = pd.Series([0,0,0], copy = False) I want to perform x @ c @ x, but I keep getting a ValueError: matrices are not aligned error flag. Am I not setting up my matrices properly? I'm not sure where I am going wrong.
[ "x @ c returns a Series object which has different indices as x. You can use the underlying numpy array to do the calculation:\n(x @ c).values @ x.values\n# 0.39880000000000004\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "matrix_multiplication", "pandas", "python_3.x", "series" ]
stackoverflow_0074680215_dataframe_matrix_multiplication_pandas_python_3.x_series.txt
Q: Access li value text jquery i'm sorry if this question is answered already but i don't find it in the search. :-) I'm trying to access a li text value to set an id for this. I tried the following. Below my jquery code $(document).ready(function() { $("#hinzubutton").click(function(){ $("#MyUL").append('<li> </li>'); $("li").append(Eingabe.value).attr("id", "Eingabe"); console.log($(Eingabe).text()); }); this is the body of my HTML Code (jquery file in the head) <body> <h1> Das ist eine Überschrift!</h1> <ul id="MyUL"> </ul> <input type="text" id="Eingabe"> <button id="hinzubutton"> Hinzu </button> <button id="loeschbutton"> Löschen </button> <script src="/js/test.js"> </script> </body> the console.log shows me my entered value correctly but i can't figure out how to get the value to set an own id. Is this possible? If i check the Code on my Browser it looks like this after add an value with the inputfield for example input is 1. <li id="Eingabe"> ::marker "1" (i want to set an id here if its possible) " " </li> Thanks a lot. I tried to access the value text but i cant append an id. My first try was to set the .attr("id", "li1") but it doesn't work for me. A: Try using jQuery appendTo because then you can set the text and any other attributes you want before finally appending it to your list: $("<li></li>").text(Eingabe.value).appendTo("#MyUL"); Snippet $("#hinzubutton").click(function() { $("<li></li>").text("testId").appendTo("#MyUL"); debug.innerHTML = MyUL.outerHTML; }); <ul id="MyUL"></ul> <input type="text" id="Eingabe"> <button id="hinzubutton"> Hinzu </button> <button id="loeschbutton"> Löschen </button> <hr> HTML: <xmp id="debug"></xmp> <!-- the xmp tag is depreciated, but still useful for debugging --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> A: Thanks for you answer, unfortunately i'm not able to set a id for my input value. I try it this way $(document).ready(function() { $("#hinzubutton").click(function(){ $("<li></li>").text(Eingabe.value).attr("id", "testid").appendTo("#MyUL"); }); But this still set my id on my li tag not on the value. It looks like <li id="testid"> ::marker "1" (is it possible to set the id for this value? or can i set it only for my li tag) </li> The Problem is i want to input a todo task but append an delete and edit button. (I have a working project but without jquery only javascript) but if i want to edit the input i can edit the whole li tag inclue the buttons. I thought this is the right way to solve my problem to edit only the input value. I use contenteditable for this and this allows the user to edit the whole li tag.
Access li value text jquery
i'm sorry if this question is answered already but i don't find it in the search. :-) I'm trying to access a li text value to set an id for this. I tried the following. Below my jquery code $(document).ready(function() { $("#hinzubutton").click(function(){ $("#MyUL").append('<li> </li>'); $("li").append(Eingabe.value).attr("id", "Eingabe"); console.log($(Eingabe).text()); }); this is the body of my HTML Code (jquery file in the head) <body> <h1> Das ist eine Überschrift!</h1> <ul id="MyUL"> </ul> <input type="text" id="Eingabe"> <button id="hinzubutton"> Hinzu </button> <button id="loeschbutton"> Löschen </button> <script src="/js/test.js"> </script> </body> the console.log shows me my entered value correctly but i can't figure out how to get the value to set an own id. Is this possible? If i check the Code on my Browser it looks like this after add an value with the inputfield for example input is 1. <li id="Eingabe"> ::marker "1" (i want to set an id here if its possible) " " </li> Thanks a lot. I tried to access the value text but i cant append an id. My first try was to set the .attr("id", "li1") but it doesn't work for me.
[ "Try using jQuery appendTo because then you can set the text and any other attributes you want before finally appending it to your list:\n$(\"<li></li>\").text(Eingabe.value).appendTo(\"#MyUL\");\n\nSnippet\n\n\n$(\"#hinzubutton\").click(function() {\n \n\n\n $(\"<li></li>\").text(\"testId\").appendTo(\"#MyUL\");\n \n debug.innerHTML = MyUL.outerHTML;\n\n\n});\n<ul id=\"MyUL\"></ul>\n<input type=\"text\" id=\"Eingabe\">\n<button id=\"hinzubutton\"> Hinzu </button>\n<button id=\"loeschbutton\"> Löschen </button>\n\n<hr>\nHTML:\n<xmp id=\"debug\"></xmp>\n<!-- the xmp tag is depreciated, but still useful for debugging -->\n\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n\n\n", "Thanks for you answer, unfortunately i'm not able to set a id for my input value. I try it this way\n$(document).ready(function() {\n $(\"#hinzubutton\").click(function(){\n $(\"<li></li>\").text(Eingabe.value).attr(\"id\", \"testid\").appendTo(\"#MyUL\");\n });\n\nBut this still set my id on my li tag not on the value. It looks like\n<li id=\"testid\">\n::marker\n\"1\" (is it possible to set the id for this value? or can i set it only for my li tag)\n</li>\n\nThe Problem is i want to input a todo task but append an delete and edit button. (I have a working project but without jquery only javascript) but if i want to edit the input i can edit the whole li tag inclue the buttons.\nI thought this is the right way to solve my problem to edit only the input value.\nI use contenteditable for this and this allows the user to edit the whole li tag.\n" ]
[ 0, 0 ]
[]
[]
[ "attr", "html", "html_lists", "javascript", "jquery" ]
stackoverflow_0074671817_attr_html_html_lists_javascript_jquery.txt
Q: How increase mysql speed in SELECT in postdata in WORDPRESS with RTRIM Today we used the consult for recive a pattern of data, and, with this pattern select the results: SELECT pm.meta_value, MONTH(RTRIM(LTRIM(SUBSTRING(pm.meta_key,23,10)))) as month FROM wp_postmeta pm The problem is: The consulting are stay slowed, and, we cant change the database. How i can make this consult stay more speed? I'm yet trying put the index, but, not solved. The pattern is filter the string in wp_postmeta and retry get the month. For example: string-with-any-name-of-day-2022-01-32, so, we filtering this string with rtrim and substring for get the month. I'm tryed put the index in table wp_postdata in column meta_key and meta_value, but this not solved my problem. I yet think in create other table for storage this meta data, but, the problem is gonna continue. A: Your query is very close indeed to being optimal. You're selecting the whole table (you have no WHERE clause) which means a full table scan. That takes time, but it's unavoidable. You're not ORDERing your result set, so MySql delivers it progressively without having to buffer it up. The only possible room for improvement is the little nest of string functions, but that cost is trivial compared to the full table scan. The real problem is that your query makes no sense on wp_postmeta. It can't possibly yield anything useful. Why not? The meta_key values in that table are all sorts of things, most of which will be made meaningless by your nest of string functions. Don't believe me? Run this query. SELECT DISTINCT meta_value FROM wp_postmeta You'll see the various meta_keys in use by Core and plugins. WooCommerce has dozens. That means you need a WHERE meta_key LIKE 'something%' clause in your query to exclude all the rando keys from your result set. As long as the LIKE clause doesn't start with % then your query will exploit one of the existing standard indexes on that table. A: i'm solve this problem. I'm need create a new table for stored this register. New table: id meta_key meta_data date And, i constructed a script for get the data in postmeta and put in for new table. The wordpress was slowed because when retrieve posts with metadata, the get_post stay very slowed for read because the number of register. The better solution is gonna parse data for a new table and cleaner postmeta table.
How increase mysql speed in SELECT in postdata in WORDPRESS with RTRIM
Today we used the consult for recive a pattern of data, and, with this pattern select the results: SELECT pm.meta_value, MONTH(RTRIM(LTRIM(SUBSTRING(pm.meta_key,23,10)))) as month FROM wp_postmeta pm The problem is: The consulting are stay slowed, and, we cant change the database. How i can make this consult stay more speed? I'm yet trying put the index, but, not solved. The pattern is filter the string in wp_postmeta and retry get the month. For example: string-with-any-name-of-day-2022-01-32, so, we filtering this string with rtrim and substring for get the month. I'm tryed put the index in table wp_postdata in column meta_key and meta_value, but this not solved my problem. I yet think in create other table for storage this meta data, but, the problem is gonna continue.
[ "Your query is very close indeed to being optimal. You're selecting the whole table (you have no WHERE clause) which means a full table scan. That takes time, but it's unavoidable. You're not ORDERing your result set, so MySql delivers it progressively without having to buffer it up. The only possible room for improvement is the little nest of string functions, but that cost is trivial compared to the full table scan.\nThe real problem is that your query makes no sense on wp_postmeta. It can't possibly yield anything useful. Why not? The meta_key values in that table are all sorts of things, most of which will be made meaningless by your nest of string functions. Don't believe me? Run this query.\nSELECT DISTINCT meta_value FROM wp_postmeta\n\nYou'll see the various meta_keys in use by Core and plugins. WooCommerce has dozens.\nThat means you need a WHERE meta_key LIKE 'something%' clause in your query to exclude all the rando keys from your result set. As long as the LIKE clause doesn't start with % then your query will exploit one of the existing standard indexes on that table.\n", "i'm solve this problem.\nI'm need create a new table for stored this register.\nNew table:\n\nid\nmeta_key\nmeta_data\ndate\n\nAnd, i constructed a script for get the data in postmeta and put in for new table.\nThe wordpress was slowed because when retrieve posts with metadata, the get_post stay very slowed for read because the number of register.\nThe better solution is gonna parse data for a new table and cleaner postmeta table.\n" ]
[ 0, 0 ]
[]
[]
[ "mysql", "wordpress" ]
stackoverflow_0074662570_mysql_wordpress.txt
Q: How to do rest authentication with Spring Social? I have implemented Spring Social + Spring Security as outlined in the Spring security examples (and with spring security java config). I reported couple of problems at the time (see https://jira.springsource.org/browse/SEC-2204) all of those are resolved and my security works fine. However, I want to change my security implementation and use RESTful authentication. Spring oauth/oauth2 (http://projects.spring.io/spring-security-oauth/) solves this problem but I can not see how Spring Social will fit into that picture? Although behind the scenes Spring social talks to Facebook/Twitter with oauth, I don't think Spring Social's signup form and other characteristics are built for a restful API. Any examples or ideas will definitely help. Update on this post: (4/6/2014) I have built a (PHP) site that consumes my API. This PHP site (let's call it the client site), uses Facebook PHP SDK to register its own users. This is a completely separate way of gathering its own members. However, once users are registered client site passes username, email, password, first name, and last name data along with its client_id and client secret and using OAuth2 grant type client_credentials authentication. This passed-in user data creates an user record on the main system! (main application) After this, each time the client site calls the main system via OAuth2 grant type password and sends client_id, client_secret, username and password, gets an "Authentication token" and be able to communicate with the main site with this token. Seems like a long way to go but solves the problem of keeping the user record on the main system. I'm curious if there are other ways to do this? Please advise. A: So you want to use Oauth2 in your application, and you want to use the password flow. You can use the spring security oauth2-resource-server project to implement a resource server. In your resource server you can use the ResourceOwnerPasswordResourceDetails to provide the client_id, client_secret, username and password, The Oauth2RestTemplate can be used to call the resource server. A: It sounds like you are looking for a way to integrate Spring Social with a RESTful authentication system based on OAuth2. Spring Social does not directly support this type of authentication, but it may be possible to use the Spring Security OAuth project to provide the necessary authentication for your RESTful API. With Spring Security OAuth, you can set up an OAuth2 authentication server that can issue access tokens to client applications. These access tokens can then be used by the client applications to access your RESTful API. You can use the client_credentials grant type to authenticate the client application itself, and the password grant type to authenticate individual users. In order to integrate Spring Social with this setup, you would need to modify the Spring Social signup process to use the OAuth2 access tokens issued by your authentication server. This would require customizing the Spring Social code to integrate with the OAuth2 authentication process. It may also be necessary to modify the Spring Social signup form to collect the necessary information for authenticating with OAuth2 (e.g. the client id and secret, and the user's username and password). Overall, it is possible to integrate Spring Social with a RESTful authentication system based on OAuth2, but it will require some customization of the Spring Social code to make it work. If you want to pursue this approach, it may be helpful to consult the documentation and examples for the Spring Security OAuth project, as well as the source code for Spring Social. A: Spring-social was deprecated in 2019. In the case that was exposed in the question (long before this deprecation), the easiest sollution is using an authorization-server capable of federating "social" identities out of the box. Keycloak is a free "on premise" sample and Auth0 a SaaS one (with free tier). Just search for "OIDC authorization-server" in your favorite search engine and pick the one best matching your needs. REST APIs are then configured as resource-servers using spring-boot-starter-oauth2-resource-server. Samples there. A: Spring Social can be used with Spring Security OAuth2 to implement RESTful authentication. To do this, you will need to set up your Spring Security configuration to use OAuth2 and configure it to use a custom UserDetailsService that retrieves user information from your Spring Social connection repository. This will allow you to authenticate users using their Spring Social connections, and issue OAuth2 access tokens that can be used to access your RESTful API. Here is an example of how you can configure Spring Security OAuth2 to use Spring Social for authentication: @Configuration @EnableAuthorizationServer public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .userDetailsService(userDetailsService) .authenticationManager(authenticationManager); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient("clientapp") .authorizedGrantTypes("password", "refresh_token") .authorities("USER") .scopes("read", "write") .resourceIds(RESOURCE_ID) .secret("123456"); } } In the above configuration, the userDetailsService bean is a custom UserDetailsService that retrieves user information from your Spring Social connection repository. The configure method is used to set this service as the user details service for the OAuth2 authentication server, and to configure the client details for the OAuth2 clients that will be accessing the server. Once you have set up your Spring Security OAuth2 configuration, you can use it to authenticate users and issue access tokens that can be used to access your RESTful API. For more information on how to use Spring Security OAuth2, see the Spring Security OAuth2 documentation. A: Wow, lots of good information already provided by others but Spring Docs provides sample config yaml file to authenticate with Google and Okta, see link below (apologies if already provided). https://docs.spring.io/spring-security/reference/5.8/reactive/oauth2/login/core.html#webflux-oauth2-login-common-oauth2-provider Configuring Custom Provider Properties There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain). For example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints. For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: spring.security.oauth2.client.provider.[providerId]. The following listing shows an example: For these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: spring.security.oauth2.client.provider.[providerId]. The following listing shows an example: spring: security: oauth2: client: registration: okta: client-id: okta-client-id client-secret: okta-client-secret provider: okta: authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo user-name-attribute: sub jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys The base property (spring.security.oauth2.client.provider.okta) allows for custom configuration of protocol endpoint locations.
How to do rest authentication with Spring Social?
I have implemented Spring Social + Spring Security as outlined in the Spring security examples (and with spring security java config). I reported couple of problems at the time (see https://jira.springsource.org/browse/SEC-2204) all of those are resolved and my security works fine. However, I want to change my security implementation and use RESTful authentication. Spring oauth/oauth2 (http://projects.spring.io/spring-security-oauth/) solves this problem but I can not see how Spring Social will fit into that picture? Although behind the scenes Spring social talks to Facebook/Twitter with oauth, I don't think Spring Social's signup form and other characteristics are built for a restful API. Any examples or ideas will definitely help. Update on this post: (4/6/2014) I have built a (PHP) site that consumes my API. This PHP site (let's call it the client site), uses Facebook PHP SDK to register its own users. This is a completely separate way of gathering its own members. However, once users are registered client site passes username, email, password, first name, and last name data along with its client_id and client secret and using OAuth2 grant type client_credentials authentication. This passed-in user data creates an user record on the main system! (main application) After this, each time the client site calls the main system via OAuth2 grant type password and sends client_id, client_secret, username and password, gets an "Authentication token" and be able to communicate with the main site with this token. Seems like a long way to go but solves the problem of keeping the user record on the main system. I'm curious if there are other ways to do this? Please advise.
[ "So you want to use Oauth2 in your application, and you want to use the password flow.\nYou can use the spring security oauth2-resource-server project to implement a resource server.\nIn your resource server you can use the ResourceOwnerPasswordResourceDetails to provide the client_id, client_secret, username and password,\nThe Oauth2RestTemplate can be used to call the resource server.\n", "It sounds like you are looking for a way to integrate Spring Social with a RESTful authentication system based on OAuth2. Spring Social does not directly support this type of authentication, but it may be possible to use the Spring Security OAuth project to provide the necessary authentication for your RESTful API.\nWith Spring Security OAuth, you can set up an OAuth2 authentication server that can issue access tokens to client applications. These access tokens can then be used by the client applications to access your RESTful API. You can use the client_credentials grant type to authenticate the client application itself, and the password grant type to authenticate individual users.\nIn order to integrate Spring Social with this setup, you would need to modify the Spring Social signup process to use the OAuth2 access tokens issued by your authentication server. This would require customizing the Spring Social code to integrate with the OAuth2 authentication process. It may also be necessary to modify the Spring Social signup form to collect the necessary information for authenticating with OAuth2 (e.g. the client id and secret, and the user's username and password).\nOverall, it is possible to integrate Spring Social with a RESTful authentication system based on OAuth2, but it will require some customization of the Spring Social code to make it work. If you want to pursue this approach, it may be helpful to consult the documentation and examples for the Spring Security OAuth project, as well as the source code for Spring Social.\n", "Spring-social was deprecated in 2019. In the case that was exposed in the question (long before this deprecation), the easiest sollution is using an authorization-server capable of federating \"social\" identities out of the box. Keycloak is a free \"on premise\" sample and Auth0 a SaaS one (with free tier). Just search for \"OIDC authorization-server\" in your favorite search engine and pick the one best matching your needs.\nREST APIs are then configured as resource-servers using spring-boot-starter-oauth2-resource-server. Samples there.\n", "Spring Social can be used with Spring Security OAuth2 to implement RESTful authentication. To do this, you will need to set up your Spring Security configuration to use OAuth2 and configure it to use a custom UserDetailsService that retrieves user information from your Spring Social connection repository. This will allow you to authenticate users using their Spring Social connections, and issue OAuth2 access tokens that can be used to access your RESTful API.\nHere is an example of how you can configure Spring Security OAuth2 to use Spring Social for authentication:\n@Configuration\n@EnableAuthorizationServer\npublic class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {\n@Autowired\nprivate UserDetailsService userDetailsService;\n\n@Bean\npublic PasswordEncoder passwordEncoder() {\n return new BCryptPasswordEncoder();\n}\n\n@Override\npublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {\n endpoints\n .userDetailsService(userDetailsService)\n .authenticationManager(authenticationManager);\n}\n\n@Override\npublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {\n clients\n .inMemory()\n .withClient(\"clientapp\")\n .authorizedGrantTypes(\"password\", \"refresh_token\")\n .authorities(\"USER\")\n .scopes(\"read\", \"write\")\n .resourceIds(RESOURCE_ID)\n .secret(\"123456\");\n}\n}\n\nIn the above configuration, the userDetailsService bean is a custom UserDetailsService that retrieves user information from your Spring Social connection repository. The configure method is used to set this service as the user details service for the OAuth2 authentication server, and to configure the client details for the OAuth2 clients that will be accessing the server.\nOnce you have set up your Spring Security OAuth2 configuration, you can use it to authenticate users and issue access tokens that can be used to access your RESTful API. For more information on how to use Spring Security OAuth2, see the Spring Security OAuth2 documentation.\n", "Wow, lots of good information already provided by others but Spring Docs provides sample config yaml file to authenticate with Google and Okta, see link below (apologies if already provided).\nhttps://docs.spring.io/spring-security/reference/5.8/reactive/oauth2/login/core.html#webflux-oauth2-login-common-oauth2-provider\nConfiguring Custom Provider Properties\nThere are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain).\n\nFor example, an OAuth Client registered with Okta is assigned to a specific sub-domain and have their own protocol endpoints.\n\nFor these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: spring.security.oauth2.client.provider.[providerId].\n\nThe following listing shows an example:\nFor these cases, Spring Boot 2.x provides the following base property for configuring custom provider properties: spring.security.oauth2.client.provider.[providerId].\n\nThe following listing shows an example:\n\nspring:\n security:\n oauth2:\n client:\n registration:\n okta:\n client-id: okta-client-id\n client-secret: okta-client-secret\n provider:\n okta: \n authorization-uri: https://your-subdomain.oktapreview.com/oauth2/v1/authorize\n token-uri: https://your-subdomain.oktapreview.com/oauth2/v1/token\n user-info-uri: https://your-subdomain.oktapreview.com/oauth2/v1/userinfo\n user-name-attribute: sub\n jwk-set-uri: https://your-subdomain.oktapreview.com/oauth2/v1/keys\n\nThe base property (spring.security.oauth2.client.provider.okta) allows for custom configuration of protocol endpoint locations.\n" ]
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "spring", "spring_security", "spring_security_oauth2", "spring_social" ]
stackoverflow_0020033549_spring_spring_security_spring_security_oauth2_spring_social.txt
Q: How To Customize Dropdown Items to use Theme Color in SPFx WebPart I want to give my dropdown items to use the text themeColor. How can I achieve this? Below is my code: const dropdownStyles: Partial<IDropdownStyles> = { dropdown: { width: "50%" }, dropdownItem: { backgroundColor:"$themePrimary", color:"$ms-color-themePrimary" } }; <Dropdown label='Select your List' styles={ dropdownStyles} placeholder='---Select an Option---' options={this.state.listNames}></Dropdown> The above does not work. The dropdown items dont use the Primary color which is #a200ff. A: As far as I know the "$ms-Bla--bla-bla" notation is only working for (statically) pre-processed fabric-ui files, there is no run-time processing of these variables in spfx. So, you may need to use the theme directly. For example, you could make your dropdownStyles a function instead of a constant. You receive the current theme in parameters then: const dropdownStyles = (styleProps: IDropdownStyleProps): Partial<IDropdownStyles> => { return { dropdown: { width: "50%" }, dropdownItem: { backgroundColor: styleProps.theme.palette.themePrimary, color: styleProps.theme.palette.themePrimary } } }; There are other options as well, like using <ThemeProvider> / useTheme pair for example, using "magic" scss rules like [theme: themePrimary, default: #0078d7] (which are pre-processed at runtime) , using window.__themeState__.theme variable
How To Customize Dropdown Items to use Theme Color in SPFx WebPart
I want to give my dropdown items to use the text themeColor. How can I achieve this? Below is my code: const dropdownStyles: Partial<IDropdownStyles> = { dropdown: { width: "50%" }, dropdownItem: { backgroundColor:"$themePrimary", color:"$ms-color-themePrimary" } }; <Dropdown label='Select your List' styles={ dropdownStyles} placeholder='---Select an Option---' options={this.state.listNames}></Dropdown> The above does not work. The dropdown items dont use the Primary color which is #a200ff.
[ "As far as I know the \"$ms-Bla--bla-bla\" notation is only working for (statically) pre-processed fabric-ui files, there is no run-time processing of these variables in spfx. So, you may need to use the theme directly. For example, you could make your dropdownStyles a function instead of a constant. You receive the current theme in parameters then:\nconst dropdownStyles = (styleProps: IDropdownStyleProps): Partial<IDropdownStyles> => {\n return {\n dropdown: { width: \"50%\" },\n dropdownItem: {\n backgroundColor: styleProps.theme.palette.themePrimary,\n color: styleProps.theme.palette.themePrimary\n }\n }\n};\n\nThere are other options as well, like using <ThemeProvider> / useTheme pair for example, using \"magic\" scss rules like [theme: themePrimary, default: #0078d7] (which are pre-processed at runtime) , using window.__themeState__.theme variable\n" ]
[ 0 ]
[]
[]
[ "office_ui_fabric", "office_ui_fabric_react", "sharepoint_online", "spfx", "web_parts" ]
stackoverflow_0074678165_office_ui_fabric_office_ui_fabric_react_sharepoint_online_spfx_web_parts.txt
Q: Why is this SQL query for Java throwing an exception? I desperately need help with my uni task. The following query throws an exception when executing the main() of my Springboot project since apparently the query fails. I tried to adapt the original findAllByKeyword() from the sample code to my project. The difference is that in the sample project the supervisor has a foreign key "id_keyword" and in my project the Professor does not have one. Tbh I am not well familiar with the syntax of the given query and tried to adapt it as best as I could. You can find the exact error msg at the bottom of this post. With this method I want to find all corresponding Professors for a given Stichpunkt (means keyword in german) @Query("SELECT DISTINCT p FROM Professor p " + "WHERE p.id_professor = professor_hat_stichpunkt.id_professor " + "AND professor_hat_stichpunkt.id_stichpunkt = stichpunkt.id_stichpunkt " + "AND stichpunkt.id_stichpunkt = :stichpunkt" + "ORDER BY p.nachname") List<Professor> findAllByKeyword(@Param("stichpunkt") Stichpunkt stichpunkt); DB image The Professor Class is as follows: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "professor") public class Professor { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_professor", nullable = false) private Integer id; @Column(name = "vorname", nullable = false) private String vorname; @Column(name = "nachname", nullable = false) private String nachname; @Column(name = "titel", nullable = false) private String titel; @Column(name = "mailadresse", nullable = false) private String mailadresse; @ManyToOne(targetEntity = Stichpunkt.class, optional = false) @JoinColumn(name = "id_stichpunkt", referencedColumnName = "id_stichpunkt", nullable = false) private Stichpunkt stichpunkt; public void setStichpunkt(Stichpunkt stichpunkt) { this.stichpunkt = stichpunkt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Professor that = (Professor) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return nachname; // + " (" + (id == null ? "<null>" : id) + ')'; } public String getVorname() { return vorname; } public String getNachname() { return nachname; } public Integer getId() { return id; } } The Stichpunkt class is as follows: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "stichpunkt") public class Stichpunkt { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_stichpunkt", nullable = false) private Integer id; @Column(name = "titel", nullable = false) private String titel; @Column(name = "beschreibung", nullable = false) private String beschreibung; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitel() { return titel; } @Override public String toString() { return titel + " (" + (id == null ? "<null>" : id) + ')'; } } ProfessorHatStichpunkt class: import javax.persistence.*; import java.io.Serializable; import java.util.Objects; @Entity @Table(name = "professor_hat_stichpunkt") public class ProfessorHatStichpunkt { @EmbeddedId private Id id; public ProfessorHatStichpunkt() { } public ProfessorHatStichpunkt(Professor professor, Stichpunkt stichpunkt) { this.id = new Id(professor, stichpunkt); } public Id getId() { return id; } public void setId(Id id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProfessorHatStichpunkt that = (ProfessorHatStichpunkt) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return "SupervisorHasKeyword{id=" + (id == null ? "<null>" : id) + '}'; } @Embeddable public static class Id implements Serializable { @ManyToOne(targetEntity = Professor.class, optional = false) @JoinColumn(name = "id_professor", referencedColumnName = "id_professor", nullable = false) private Professor professor; @ManyToOne(targetEntity = Stichpunkt.class, optional = false) @JoinColumn(name = "id_stichpunkt", referencedColumnName = "id_stichpunkt", nullable = false) private Stichpunkt stichpunkt; public Id() { } public Id(Professor professor, Stichpunkt stichpunkt) { this.professor = professor; this.stichpunkt = stichpunkt; } public Professor getProfessor() { return professor; } public void setProfessor(Professor professor) { this.professor = professor; } public Stichpunkt getStichpunkt() { return stichpunkt; } public void setStichpunkt(Stichpunkt stichpunkt) { this.stichpunkt = stichpunkt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Id id = (Id) o; return Objects.equals(getProfessor(), id.getProfessor()) && Objects.equals(getStichpunkt(), id.getStichpunkt()); } @Override public int hashCode() { return Objects.hash(getProfessor(), getStichpunkt()); } @Override public String toString() { return String.format("%s has %s", professor, stichpunkt); } } } The thing is this builds on a given sample project which works and I just adapted the code. The working sample code is the following: public interface SupervisorRepository extends JpaRepository<Supervisor, Integer> { @Query("SELECT DISTINCT s FROM Supervisor s " + "INNER JOIN SupervisorHasKeyword shk ON shk.id.supervisor = s " + "WHERE s.keyword = :keyword " + "OR shk.id.keyword = :keyword " + "ORDER BY s.name") List<Supervisor> findAllByKeyword(@Param("keyword")Keyword keyword); } sample project DB The Supervisor class is as follows: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "supervisor") public class Supervisor { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_supervisor", nullable = false) private Integer id; @Column(name = "name", nullable = false) private String name; @ManyToOne(targetEntity = Keyword.class, optional = false) @JoinColumn(name = "id_keyword", referencedColumnName = "id_keyword", nullable = false) private Keyword keyword; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Keyword getKeyword() { return keyword; } public void setKeyword(Keyword keyword) { this.keyword = keyword; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Supervisor that = (Supervisor) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return name + " (" + (id == null ? "<null>" : id) + ')'; } } Keyword class: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "keyword") public class Keyword { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_keyword", nullable = false) private Integer id; @Column(name = "text", nullable = false) private String text; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Keyword keyword = (Keyword) o; return Objects.equals(getId(), keyword.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return text + " (" + (id == null ? "<null>" : id) + ')'; } } SupervisorHasKeyword class: import javax.persistence.*; import java.io.Serializable; import java.util.Objects; @Entity @Table(name = "supervisor_has_keyword") public class SupervisorHasKeyword { @EmbeddedId private Id id; public SupervisorHasKeyword() { } public SupervisorHasKeyword(Supervisor supervisor, Keyword keyword) { this.id = new Id(supervisor, keyword); } public Id getId() { return id; } public void setId(Id id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SupervisorHasKeyword that = (SupervisorHasKeyword) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return "SupervisorHasKeyword{id=" + (id == null ? "<null>" : id) + '}'; } @Embeddable public static class Id implements Serializable { @ManyToOne(targetEntity = Supervisor.class, optional = false) @JoinColumn(name = "id_supervisor", referencedColumnName = "id_supervisor", nullable = false) private Supervisor supervisor; @ManyToOne(targetEntity = Keyword.class, optional = false) @JoinColumn(name = "id_keyword", referencedColumnName = "id_keyword", nullable = false) private Keyword keyword; public Id() { } public Id(Supervisor supervisor, Keyword keyword) { this.supervisor = supervisor; this.keyword = keyword; } public Supervisor getSupervisor() { return supervisor; } public void setSupervisor(Supervisor supervisor) { this.supervisor = supervisor; } public Keyword getKeyword() { return keyword; } public void setKeyword(Keyword keyword) { this.keyword = keyword; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Id id = (Id) o; return Objects.equals(getSupervisor(), id.getSupervisor()) && Objects.equals(getKeyword(), id.getKeyword()); } @Override public int hashCode() { return Objects.hash(getSupervisor(), getKeyword()); } @Override public String toString() { return String.format("%s has %s", supervisor, keyword); } } } Error: Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'professorService' defined in file [C:\Users\...\camunda\database\service\ProfessorService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'professorRepository' defined in de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository.findAllByKeyword(de.ostfalia.bips.ws22.camunda.database.domain.Stichpunkt); Reason: Validation failed for query for method public abstract java.util.List de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository.findAllByKeyword(de.ostfalia.bips.ws22.camunda.database.domain.Stichpunkt)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository.findAllByKeyword(de.ostfalia.bips.ws22.camunda.database.domain.Stichpunkt)! A: since apparently the query fails The query itself is not failing, it hasn't been executed at the point you get the exception. The exception is telling you that professorRepository can't be instantiated because you're referencing a bean in it's constructor that either doesn't exist, or is not a managed bean, but take a look at the first parameter in your constructor ("Unsatisfied dependency expressed through constructor parameter 0;")
Why is this SQL query for Java throwing an exception?
I desperately need help with my uni task. The following query throws an exception when executing the main() of my Springboot project since apparently the query fails. I tried to adapt the original findAllByKeyword() from the sample code to my project. The difference is that in the sample project the supervisor has a foreign key "id_keyword" and in my project the Professor does not have one. Tbh I am not well familiar with the syntax of the given query and tried to adapt it as best as I could. You can find the exact error msg at the bottom of this post. With this method I want to find all corresponding Professors for a given Stichpunkt (means keyword in german) @Query("SELECT DISTINCT p FROM Professor p " + "WHERE p.id_professor = professor_hat_stichpunkt.id_professor " + "AND professor_hat_stichpunkt.id_stichpunkt = stichpunkt.id_stichpunkt " + "AND stichpunkt.id_stichpunkt = :stichpunkt" + "ORDER BY p.nachname") List<Professor> findAllByKeyword(@Param("stichpunkt") Stichpunkt stichpunkt); DB image The Professor Class is as follows: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "professor") public class Professor { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_professor", nullable = false) private Integer id; @Column(name = "vorname", nullable = false) private String vorname; @Column(name = "nachname", nullable = false) private String nachname; @Column(name = "titel", nullable = false) private String titel; @Column(name = "mailadresse", nullable = false) private String mailadresse; @ManyToOne(targetEntity = Stichpunkt.class, optional = false) @JoinColumn(name = "id_stichpunkt", referencedColumnName = "id_stichpunkt", nullable = false) private Stichpunkt stichpunkt; public void setStichpunkt(Stichpunkt stichpunkt) { this.stichpunkt = stichpunkt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Professor that = (Professor) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return nachname; // + " (" + (id == null ? "<null>" : id) + ')'; } public String getVorname() { return vorname; } public String getNachname() { return nachname; } public Integer getId() { return id; } } The Stichpunkt class is as follows: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "stichpunkt") public class Stichpunkt { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_stichpunkt", nullable = false) private Integer id; @Column(name = "titel", nullable = false) private String titel; @Column(name = "beschreibung", nullable = false) private String beschreibung; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitel() { return titel; } @Override public String toString() { return titel + " (" + (id == null ? "<null>" : id) + ')'; } } ProfessorHatStichpunkt class: import javax.persistence.*; import java.io.Serializable; import java.util.Objects; @Entity @Table(name = "professor_hat_stichpunkt") public class ProfessorHatStichpunkt { @EmbeddedId private Id id; public ProfessorHatStichpunkt() { } public ProfessorHatStichpunkt(Professor professor, Stichpunkt stichpunkt) { this.id = new Id(professor, stichpunkt); } public Id getId() { return id; } public void setId(Id id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProfessorHatStichpunkt that = (ProfessorHatStichpunkt) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return "SupervisorHasKeyword{id=" + (id == null ? "<null>" : id) + '}'; } @Embeddable public static class Id implements Serializable { @ManyToOne(targetEntity = Professor.class, optional = false) @JoinColumn(name = "id_professor", referencedColumnName = "id_professor", nullable = false) private Professor professor; @ManyToOne(targetEntity = Stichpunkt.class, optional = false) @JoinColumn(name = "id_stichpunkt", referencedColumnName = "id_stichpunkt", nullable = false) private Stichpunkt stichpunkt; public Id() { } public Id(Professor professor, Stichpunkt stichpunkt) { this.professor = professor; this.stichpunkt = stichpunkt; } public Professor getProfessor() { return professor; } public void setProfessor(Professor professor) { this.professor = professor; } public Stichpunkt getStichpunkt() { return stichpunkt; } public void setStichpunkt(Stichpunkt stichpunkt) { this.stichpunkt = stichpunkt; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Id id = (Id) o; return Objects.equals(getProfessor(), id.getProfessor()) && Objects.equals(getStichpunkt(), id.getStichpunkt()); } @Override public int hashCode() { return Objects.hash(getProfessor(), getStichpunkt()); } @Override public String toString() { return String.format("%s has %s", professor, stichpunkt); } } } The thing is this builds on a given sample project which works and I just adapted the code. The working sample code is the following: public interface SupervisorRepository extends JpaRepository<Supervisor, Integer> { @Query("SELECT DISTINCT s FROM Supervisor s " + "INNER JOIN SupervisorHasKeyword shk ON shk.id.supervisor = s " + "WHERE s.keyword = :keyword " + "OR shk.id.keyword = :keyword " + "ORDER BY s.name") List<Supervisor> findAllByKeyword(@Param("keyword")Keyword keyword); } sample project DB The Supervisor class is as follows: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "supervisor") public class Supervisor { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_supervisor", nullable = false) private Integer id; @Column(name = "name", nullable = false) private String name; @ManyToOne(targetEntity = Keyword.class, optional = false) @JoinColumn(name = "id_keyword", referencedColumnName = "id_keyword", nullable = false) private Keyword keyword; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Keyword getKeyword() { return keyword; } public void setKeyword(Keyword keyword) { this.keyword = keyword; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Supervisor that = (Supervisor) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return name + " (" + (id == null ? "<null>" : id) + ')'; } } Keyword class: import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "keyword") public class Keyword { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_keyword", nullable = false) private Integer id; @Column(name = "text", nullable = false) private String text; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Keyword keyword = (Keyword) o; return Objects.equals(getId(), keyword.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return text + " (" + (id == null ? "<null>" : id) + ')'; } } SupervisorHasKeyword class: import javax.persistence.*; import java.io.Serializable; import java.util.Objects; @Entity @Table(name = "supervisor_has_keyword") public class SupervisorHasKeyword { @EmbeddedId private Id id; public SupervisorHasKeyword() { } public SupervisorHasKeyword(Supervisor supervisor, Keyword keyword) { this.id = new Id(supervisor, keyword); } public Id getId() { return id; } public void setId(Id id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SupervisorHasKeyword that = (SupervisorHasKeyword) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return "SupervisorHasKeyword{id=" + (id == null ? "<null>" : id) + '}'; } @Embeddable public static class Id implements Serializable { @ManyToOne(targetEntity = Supervisor.class, optional = false) @JoinColumn(name = "id_supervisor", referencedColumnName = "id_supervisor", nullable = false) private Supervisor supervisor; @ManyToOne(targetEntity = Keyword.class, optional = false) @JoinColumn(name = "id_keyword", referencedColumnName = "id_keyword", nullable = false) private Keyword keyword; public Id() { } public Id(Supervisor supervisor, Keyword keyword) { this.supervisor = supervisor; this.keyword = keyword; } public Supervisor getSupervisor() { return supervisor; } public void setSupervisor(Supervisor supervisor) { this.supervisor = supervisor; } public Keyword getKeyword() { return keyword; } public void setKeyword(Keyword keyword) { this.keyword = keyword; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Id id = (Id) o; return Objects.equals(getSupervisor(), id.getSupervisor()) && Objects.equals(getKeyword(), id.getKeyword()); } @Override public int hashCode() { return Objects.hash(getSupervisor(), getKeyword()); } @Override public String toString() { return String.format("%s has %s", supervisor, keyword); } } } Error: Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'professorService' defined in file [C:\Users\...\camunda\database\service\ProfessorService.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'professorRepository' defined in de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository.findAllByKeyword(de.ostfalia.bips.ws22.camunda.database.domain.Stichpunkt); Reason: Validation failed for query for method public abstract java.util.List de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository.findAllByKeyword(de.ostfalia.bips.ws22.camunda.database.domain.Stichpunkt)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List de.ostfalia.bips.ws22.camunda.database.repository.ProfessorRepository.findAllByKeyword(de.ostfalia.bips.ws22.camunda.database.domain.Stichpunkt)!
[ "\nsince apparently the query fails\n\nThe query itself is not failing, it hasn't been executed at the point you get the exception. The exception is telling you that professorRepository can't be instantiated because you're referencing a bean in it's constructor that either doesn't exist, or is not a managed bean, but take a look at the first parameter in your constructor (\"Unsatisfied dependency expressed through constructor parameter 0;\")\n" ]
[ 0 ]
[]
[]
[ "java", "mysql", "spring_boot" ]
stackoverflow_0074680147_java_mysql_spring_boot.txt
Q: Missing numpy lib when trying to install tensorflow I have numpy install as shown. I'm using the instructions for the M1 chip https://developer.apple.com/metal/tensorflow-plugin/ (base) cody@Codys-MBP ~ % pip install numpy --upgrade --force-reinstall Defaulting to user installation because normal site-packages is not writeable Collecting numpy Using cached numpy-1.23.5-cp39-cp39-macosx_11_0_arm64.whl (13.4 MB) Installing collected packages: numpy Attempting uninstall: numpy Found existing installation: numpy 1.23.5 Uninstalling numpy-1.23.5: Successfully uninstalled numpy-1.23.5 WARNING: The scripts f2py, f2py3 and f2py3.9 are installed in '/Users/cody/Library/Python/3.9/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed numpy-1.23.5 (base) cody@Codys-MBP ~ % python3 -c "import tensorflow as tf;" RuntimeError: module compiled against API version 0x10 but this version of numpy is 0xf RuntimeError: module compiled against API version 0x10 but this version of numpy is 0xf ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import A: It was a numpy version issue. I uninstalled everything , then let tensor flow resolve its dependency.
Missing numpy lib when trying to install tensorflow
I have numpy install as shown. I'm using the instructions for the M1 chip https://developer.apple.com/metal/tensorflow-plugin/ (base) cody@Codys-MBP ~ % pip install numpy --upgrade --force-reinstall Defaulting to user installation because normal site-packages is not writeable Collecting numpy Using cached numpy-1.23.5-cp39-cp39-macosx_11_0_arm64.whl (13.4 MB) Installing collected packages: numpy Attempting uninstall: numpy Found existing installation: numpy 1.23.5 Uninstalling numpy-1.23.5: Successfully uninstalled numpy-1.23.5 WARNING: The scripts f2py, f2py3 and f2py3.9 are installed in '/Users/cody/Library/Python/3.9/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed numpy-1.23.5 (base) cody@Codys-MBP ~ % python3 -c "import tensorflow as tf;" RuntimeError: module compiled against API version 0x10 but this version of numpy is 0xf RuntimeError: module compiled against API version 0x10 but this version of numpy is 0xf ImportError: numpy.core._multiarray_umath failed to import ImportError: numpy.core.umath failed to import
[ "It was a numpy version issue. I uninstalled everything , then let tensor flow resolve its dependency.\n" ]
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0074662366_python_tensorflow.txt
Q: Mockery Laravel Elequent chained queries I have a question regarding mockery in combination with Laravel. I have sucessfully created a mockery object to mock all the public static methods such as where and find on the elequent model instance. $userMock = \Mockery::mock('alias:App\Models\User'); This works great, however testing chained queries like I ran into some issues: User::where("name", "test")->first() The only solution I could find is to use mock the demeter chain using: http://docs.mockery.io/en/latest/reference/demeter_chains.html So for example: $userMock->shouldReceive('where->first')->andReturn($user); But I would like to test the arguments that are provided to the where query as well: $userMock->shouldReceive("where")->with("slug", "test")->andReturn($user); But that is not really working since it should return the Elequent builder, any ideas how I can test this properly? A: $userMock->shouldReceive('where') ->with("slug", "test") ->andReturn(Mockery::self()) ->shouldReceive("first") ->andReturn($user); Using Mockery::self you can complete the chain.
Mockery Laravel Elequent chained queries
I have a question regarding mockery in combination with Laravel. I have sucessfully created a mockery object to mock all the public static methods such as where and find on the elequent model instance. $userMock = \Mockery::mock('alias:App\Models\User'); This works great, however testing chained queries like I ran into some issues: User::where("name", "test")->first() The only solution I could find is to use mock the demeter chain using: http://docs.mockery.io/en/latest/reference/demeter_chains.html So for example: $userMock->shouldReceive('where->first')->andReturn($user); But I would like to test the arguments that are provided to the where query as well: $userMock->shouldReceive("where")->with("slug", "test")->andReturn($user); But that is not really working since it should return the Elequent builder, any ideas how I can test this properly?
[ "$userMock->shouldReceive('where')\n ->with(\"slug\", \"test\")\n ->andReturn(Mockery::self())\n ->shouldReceive(\"first\")\n ->andReturn($user);\n\nUsing Mockery::self you can complete the chain.\n" ]
[ 0 ]
[]
[]
[ "laravel", "mockery", "unit_testing" ]
stackoverflow_0074680796_laravel_mockery_unit_testing.txt
Q: DotnetFramework runtimes + SDKs installed but VS2022 & Win10 don't recognize them Found either a bug in windows 10 or a bug in VS2022 or both whereby the DotNetFramework Dev tools and runtimes are installed, yet they do not show up from the command line prompt nor in Programs & Features. Attempting to reinstall any of them (4.52, 4.62, 4.72, 4.82) yields an error message stating they are already installed. Like Schroedinger's Cat, they are both installed and uninstalled simultaneously. C:\WINDOWS\system32>dotnet --info .NET SDK: Version: 7.0.100 Commit: e12b7af219 Runtime Environment: OS Name: Windows OS Version: 10.0.19045 OS Platform: Windows RID: win10-x64 Base Path: D:\Program Files\dotnet\sdk\7.0.100\ Host (useful for support): Version: 6.0.5 Commit: 70ae3df4a6 .NET SDKs installed: 3.1.425 [D:\Program Files\dotnet\sdk] 5.0.203 [C:\Program Files\dotnet\sdk] 5.0.214 [D:\Program Files\dotnet\sdk] 5.0.401 [C:\Program Files\dotnet\sdk] 5.0.403 [C:\Program Files\dotnet\sdk] 5.0.408 [C:\Program Files\dotnet\sdk] 6.0.202 [C:\Program Files\dotnet\sdk] 6.0.403 [D:\Program Files\dotnet\sdk] 7.0.100 [D:\Program Files\dotnet\sdk] .NET runtimes installed: Microsoft.AspNetCore.All 2.1.28 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.1.30 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.App 2.1.28 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.1.30 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.15 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.19 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.21 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.31 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.10 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.13 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.17 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 6.0.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 6.0.11 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 7.0.0 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.NETCore.App 2.1.28 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.1.30 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.15 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.19 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.21 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.31 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.10 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.12 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.13 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.17 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.11 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 7.0.0 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.WindowsDesktop.App 3.1.15 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.19 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.21 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.31 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.6 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.9 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.10 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.12 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.13 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.17 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.4 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.5 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.11 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 7.0.0 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] To install additional .NET runtimes or SDKs: https://aka.ms/dotnet-download Only DotNet Core SDKs and runtimes are displayed, but none of the older DotNetFrameworks (of any version), even though they're installed. I'm at loss and about to blow the machine away and completely start from scratch, but, would rather not. Any ideas? (I've tried MS's "fix dotnet" tool, but that achieved nothing) Looks like VS2022 is corrupted after their latest update - I attempted to Repair the installation and got "Sorry, something went wrong" Couldn't repair Microsoft.Net.4.8.FullRedist.20H2 There was an option to report the problem to MS, so I did. I still believe this is a path problem (VS2022 was installed on D:\ drive and VS2019 - which had been removed a few months ago - was installed on the C:\ drive), so I may have to uninstall VS2022 and reinstall to the c:\ drive back. A: The dotnet tool only works for things related to ".NET" (or previously ".NET Core"), it doesn't do anything for ".NET Framework". ".NET Framework" is a Windows component, you can't not have it installed. As for Visual Studio, depending on the type of project you create, it will either be for .NET Framework or for .NET, but not both – unless you manually edit the project file. See here as an example of the different project types. If you are still having problems, posting further details on what you're specifically trying to accomplish will help.
DotnetFramework runtimes + SDKs installed but VS2022 & Win10 don't recognize them
Found either a bug in windows 10 or a bug in VS2022 or both whereby the DotNetFramework Dev tools and runtimes are installed, yet they do not show up from the command line prompt nor in Programs & Features. Attempting to reinstall any of them (4.52, 4.62, 4.72, 4.82) yields an error message stating they are already installed. Like Schroedinger's Cat, they are both installed and uninstalled simultaneously. C:\WINDOWS\system32>dotnet --info .NET SDK: Version: 7.0.100 Commit: e12b7af219 Runtime Environment: OS Name: Windows OS Version: 10.0.19045 OS Platform: Windows RID: win10-x64 Base Path: D:\Program Files\dotnet\sdk\7.0.100\ Host (useful for support): Version: 6.0.5 Commit: 70ae3df4a6 .NET SDKs installed: 3.1.425 [D:\Program Files\dotnet\sdk] 5.0.203 [C:\Program Files\dotnet\sdk] 5.0.214 [D:\Program Files\dotnet\sdk] 5.0.401 [C:\Program Files\dotnet\sdk] 5.0.403 [C:\Program Files\dotnet\sdk] 5.0.408 [C:\Program Files\dotnet\sdk] 6.0.202 [C:\Program Files\dotnet\sdk] 6.0.403 [D:\Program Files\dotnet\sdk] 7.0.100 [D:\Program Files\dotnet\sdk] .NET runtimes installed: Microsoft.AspNetCore.All 2.1.28 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.1.30 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.App 2.1.28 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.1.30 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.15 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.19 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.21 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.31 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.6 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.10 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.13 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 5.0.17 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 6.0.5 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 6.0.11 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 7.0.0 [D:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.NETCore.App 2.1.28 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.1.30 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.15 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.19 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.21 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.31 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.6 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.10 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.12 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.13 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 5.0.17 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.4 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.5 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 6.0.11 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 7.0.0 [D:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.WindowsDesktop.App 3.1.15 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.19 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.21 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.31 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.6 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.9 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.10 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.12 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.13 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 5.0.17 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.4 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.5 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 6.0.11 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 7.0.0 [D:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] To install additional .NET runtimes or SDKs: https://aka.ms/dotnet-download Only DotNet Core SDKs and runtimes are displayed, but none of the older DotNetFrameworks (of any version), even though they're installed. I'm at loss and about to blow the machine away and completely start from scratch, but, would rather not. Any ideas? (I've tried MS's "fix dotnet" tool, but that achieved nothing) Looks like VS2022 is corrupted after their latest update - I attempted to Repair the installation and got "Sorry, something went wrong" Couldn't repair Microsoft.Net.4.8.FullRedist.20H2 There was an option to report the problem to MS, so I did. I still believe this is a path problem (VS2022 was installed on D:\ drive and VS2019 - which had been removed a few months ago - was installed on the C:\ drive), so I may have to uninstall VS2022 and reinstall to the c:\ drive back.
[ "The dotnet tool only works for things related to \".NET\" (or previously \".NET Core\"), it doesn't do anything for \".NET Framework\". \".NET Framework\" is a Windows component, you can't not have it installed.\nAs for Visual Studio, depending on the type of project you create, it will either be for .NET Framework or for .NET, but not both – unless you manually edit the project file. See here as an example of the different project types.\nIf you are still having problems, posting further details on what you're specifically trying to accomplish will help.\n" ]
[ 1 ]
[]
[]
[ ".net", "visual_studio_2022", "windows" ]
stackoverflow_0074680354_.net_visual_studio_2022_windows.txt
Q: How to split several columns into one column with several records in SQL? I need to transform the data using SQL but I'm struggling with one thing currently. I have a table Person with these columns: phone_number; name_1; name_2; name3; name4. I need to transform this table to table like this: phone_number; name Where would be such records as (phone_number; name_1) (phone_number; name_2) (phone_number; name_3) Please help me (example is below) CREATE TABLE Person ( phone_number int, name_1 varchar(50), name_2 varchar(50), name_3 varchar(50) ); INSERT INTO Person (phone_number, name_1, name_2, name_3) VALUES (123, 'Billy', 'Bill', 'Bi') /* Expected: */ /* phone_number | name 123: Billy, 123: Bill, 123: Bi */ I've tried to do this but I'm an absolute beginner and have no idea what to do with raw SQL. Any ideas are welcome! A: UNION ALL combine the values from multiple rows into one row, with each column from a different row as a separate record. SELECT phone_number, name_1 as name FROM Person UNION ALL SELECT phone_number, name_2 as name FROM Person UNION ALL SELECT phone_number, name_3 as name FROM Person A: You can use UNION ALL statement. SELECT phone_number, name_1 FROM Person UNION ALL SELECT phone_number, name_2 FROM Person UNION ALL SELECT phone_number, name_3 FROM Person Please note that UNION ALL will not remove duplicates (in case you have the same names for a single phone_number.
How to split several columns into one column with several records in SQL?
I need to transform the data using SQL but I'm struggling with one thing currently. I have a table Person with these columns: phone_number; name_1; name_2; name3; name4. I need to transform this table to table like this: phone_number; name Where would be such records as (phone_number; name_1) (phone_number; name_2) (phone_number; name_3) Please help me (example is below) CREATE TABLE Person ( phone_number int, name_1 varchar(50), name_2 varchar(50), name_3 varchar(50) ); INSERT INTO Person (phone_number, name_1, name_2, name_3) VALUES (123, 'Billy', 'Bill', 'Bi') /* Expected: */ /* phone_number | name 123: Billy, 123: Bill, 123: Bi */ I've tried to do this but I'm an absolute beginner and have no idea what to do with raw SQL. Any ideas are welcome!
[ "UNION ALL combine the values from multiple rows into one row, with each column from a different row as a separate record.\nSELECT phone_number, name_1 as name FROM Person\nUNION ALL\nSELECT phone_number, name_2 as name FROM Person\nUNION ALL\nSELECT phone_number, name_3 as name FROM Person\n\n", "You can use UNION ALL statement.\nSELECT phone_number, name_1\nFROM Person\n\nUNION ALL\n\nSELECT phone_number, name_2\nFROM Person\n\nUNION ALL\n\nSELECT phone_number, name_3\nFROM Person\n\nPlease note that UNION ALL will not remove duplicates (in case you have the same names for a single phone_number.\n" ]
[ 3, 1 ]
[]
[]
[ "sql" ]
stackoverflow_0074680816_sql.txt
Q: Is there any way to make the SwiftPackage use only languages supported by the root module? I have a project that supports limited amount of languages. For example: I have a Package that supports a wider amount of languages Is there any way to make the Package use only languages supported by the root module? The Package uses a system language that is present in the Package but is not supported by the root module. So the app looks not consistent. Possible solutions Add a local Package and remove other languages by hand. But I won't get all the updates from the Package in this case. Also, I can make a branch in the Package repo, and specify the branch instead version. But it also won't update automatically. A: One possible solution is to use the "exclude" parameter in the Package.swift file to specify the languages that should not be included in the package. For example: let package = Package( name: "MyPackage", exclude: ["UnsupportedLanguage1", "UnsupportedLanguage2"] ) This way, the package will only include the languages that are supported by the root module, and you can still get updates from the package repository automatically.
Is there any way to make the SwiftPackage use only languages supported by the root module?
I have a project that supports limited amount of languages. For example: I have a Package that supports a wider amount of languages Is there any way to make the Package use only languages supported by the root module? The Package uses a system language that is present in the Package but is not supported by the root module. So the app looks not consistent. Possible solutions Add a local Package and remove other languages by hand. But I won't get all the updates from the Package in this case. Also, I can make a branch in the Package repo, and specify the branch instead version. But it also won't update automatically.
[ "One possible solution is to use the \"exclude\" parameter in the Package.swift file to specify the languages that should not be included in the package. For example:\nlet package = Package(\n name: \"MyPackage\",\n exclude: [\"UnsupportedLanguage1\", \"UnsupportedLanguage2\"]\n)\n\nThis way, the package will only include the languages that are supported by the root module, and you can still get updates from the package repository automatically.\n" ]
[ 0 ]
[]
[]
[ "localization", "swift", "swiftpm", "xcode" ]
stackoverflow_0073622715_localization_swift_swiftpm_xcode.txt
Q: Flutter auto_route | Pass data to outer router in nested navigation I am using Flutter auto_route for my nested navigation, where I would like to pass data (A dynamic string for the AppBar-title and a Widget for the floatingActionButton) from a nested route to an outer route (two levels up from the according to the route tree). The navigation (tree) has the following structure: @MaterialAutoRouter( routes: <AutoRoute>[ AutoRoute( page: MainNavigationView, children: [ AutoRoute( path: 'manage', page: EmptyRouterPage, name: 'ManageRouter', children: [ AutoRoute( path: 'object', page: ObjectView, initial: true, ), AutoRoute( path: 'detail', page: ObjectDetailView, ), ] ) ] ) ] ) My Page uses nested navigation, where MainNavigationView represents the Scaffold which holds an AppBar and SpeedDial as floatingActionButton of the Scaffold: class MainNavigationView extends StatefulWidget { ... } class _MainNavigationViewState extends State<MainNavigationView> { final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>(); @override Widget build(BuildContext context) { return AutoTabsRouter( routes: [ const ManageRouter(), ... ], builder: (context, child, __) { final tabsRouter = AutoTabsRouter.of(context); return Scaffold( key: _scaffoldkey, appBar: AppBar(...), //Title needs to be set dynamically body: child, floatingActionButton: SpeedDial( ... //This needs to be set dynamically ), ... ); }, ); } ... } Inside the route ManageRouter, I can navigate from ObjectView to ObjectDetailView. From both views, I need to pass a dynamic string for the AppBar and the necessary Objects for the floatingActionButton. The only solution I came up with was a Provider, for the MainNavigationView which would allow me the send the data in a decoupled manner. But it seems like overkill, for something this general. A: I think AutoRouter package doesn't have any functionality to pass a parameter between Nested routes. Your situation can be solved much easier! AutoTabsRouter have field named activeIndex. And this field will updates in AutoTabsRouter builder method when you select an page from your MainNavigationView children. I use this in my applications to display the selected page icon in the bottomNavigationBar and selected page title in appBar. Solution for your situation: class MainNavigationView extends StatefulWidget { ... } class _MainNavigationViewState extends State<MainNavigationView> { final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>(); @override Widget build(BuildContext context) { return AutoTabsRouter( routes: [ const ManageRouter(), ... ], builder: (context, child, __) { final tabsRouter = AutoTabsRouter.of(context); return Scaffold( key: _scaffoldkey, appBar: AppBar( title: tabsRouter.activeIndex == 1? 'ObjectViewTitle' : 'ObjectDetailViewTitle' ), //Title needs to be set dynamically body: child, floatingActionButton: SpeedDial( child: tabsRouter.activeIndex == 1? ObjectViewFab() : ObjectDetailViewFab() ), ... ); }, ); } ... }
Flutter auto_route | Pass data to outer router in nested navigation
I am using Flutter auto_route for my nested navigation, where I would like to pass data (A dynamic string for the AppBar-title and a Widget for the floatingActionButton) from a nested route to an outer route (two levels up from the according to the route tree). The navigation (tree) has the following structure: @MaterialAutoRouter( routes: <AutoRoute>[ AutoRoute( page: MainNavigationView, children: [ AutoRoute( path: 'manage', page: EmptyRouterPage, name: 'ManageRouter', children: [ AutoRoute( path: 'object', page: ObjectView, initial: true, ), AutoRoute( path: 'detail', page: ObjectDetailView, ), ] ) ] ) ] ) My Page uses nested navigation, where MainNavigationView represents the Scaffold which holds an AppBar and SpeedDial as floatingActionButton of the Scaffold: class MainNavigationView extends StatefulWidget { ... } class _MainNavigationViewState extends State<MainNavigationView> { final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>(); @override Widget build(BuildContext context) { return AutoTabsRouter( routes: [ const ManageRouter(), ... ], builder: (context, child, __) { final tabsRouter = AutoTabsRouter.of(context); return Scaffold( key: _scaffoldkey, appBar: AppBar(...), //Title needs to be set dynamically body: child, floatingActionButton: SpeedDial( ... //This needs to be set dynamically ), ... ); }, ); } ... } Inside the route ManageRouter, I can navigate from ObjectView to ObjectDetailView. From both views, I need to pass a dynamic string for the AppBar and the necessary Objects for the floatingActionButton. The only solution I came up with was a Provider, for the MainNavigationView which would allow me the send the data in a decoupled manner. But it seems like overkill, for something this general.
[ "I think AutoRouter package doesn't have any functionality to pass a parameter between Nested routes. Your situation can be solved much easier!\nAutoTabsRouter have field named activeIndex.\nAnd this field will updates in AutoTabsRouter builder method when you select an page from your MainNavigationView children.\nI use this in my applications to display the selected page icon in the bottomNavigationBar and selected page title in appBar.\nSolution for your situation:\nclass MainNavigationView extends StatefulWidget {\n...\n}\n\nclass _MainNavigationViewState extends State<MainNavigationView> {\n final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();\n\n @override\n Widget build(BuildContext context) {\n\n return AutoTabsRouter(\n routes: [\n const ManageRouter(),\n ...\n ],\n builder: (context, child, __) {\n final tabsRouter = AutoTabsRouter.of(context);\n return Scaffold(\n key: _scaffoldkey,\n appBar: AppBar(\n title: tabsRouter.activeIndex == 1? 'ObjectViewTitle' : 'ObjectDetailViewTitle'\n ), //Title needs to be set dynamically\n body: child,\n floatingActionButton: SpeedDial(\n child: tabsRouter.activeIndex == 1? ObjectViewFab() : ObjectDetailViewFab() \n ),\n ...\n );\n },\n );\n }\n ...\n}\n\n" ]
[ 0 ]
[]
[]
[ "flutter", "navigation", "nested", "state_management" ]
stackoverflow_0074634694_flutter_navigation_nested_state_management.txt
Q: TypeError: unhashable type: 'CatBoostClassifier' Context: I'm trying to use catboost classifier using a dictionary with parameters as such: from catboost import CatBoostClassifier model_params_grid_search = { naive_bayes.MultinomialNB(): { 'param_grid': { 'alpha': [0.01, 0.1, 0.5, 1.0, 10.0], } }, linear_model.LogisticRegression(): { 'param_grid': { 'C': [0.01, 0.1, 0.5, 1.0], 'penalty': ['l1', 'l2'], 'solver': ['liblinear', 'lbfgs', 'saga'], } }, CatBoostClassifier(): { 'param_grid':{...} }, svm.SVC(): { 'param_grid': { 'C': [0.01, 0.1, 0.5, 1.0], 'kernel': ['linear', 'rbf'], 'gamma': ['auto'] } },... To then apply the model class and do some hyperparameter gridsearch. However I keep getting the error TypeError: unhashable type: 'CatBoostClassifier' when running it for CatBoostClassifier(). All other models work fine this way, not sure why CatBoost is giving this error. I just wanted to loop through all the models to find the best one. Thank you!
TypeError: unhashable type: 'CatBoostClassifier'
Context: I'm trying to use catboost classifier using a dictionary with parameters as such: from catboost import CatBoostClassifier model_params_grid_search = { naive_bayes.MultinomialNB(): { 'param_grid': { 'alpha': [0.01, 0.1, 0.5, 1.0, 10.0], } }, linear_model.LogisticRegression(): { 'param_grid': { 'C': [0.01, 0.1, 0.5, 1.0], 'penalty': ['l1', 'l2'], 'solver': ['liblinear', 'lbfgs', 'saga'], } }, CatBoostClassifier(): { 'param_grid':{...} }, svm.SVC(): { 'param_grid': { 'C': [0.01, 0.1, 0.5, 1.0], 'kernel': ['linear', 'rbf'], 'gamma': ['auto'] } },... To then apply the model class and do some hyperparameter gridsearch. However I keep getting the error TypeError: unhashable type: 'CatBoostClassifier' when running it for CatBoostClassifier(). All other models work fine this way, not sure why CatBoost is giving this error. I just wanted to loop through all the models to find the best one. Thank you!
[]
[]
[ "I have the same issue. Did you find a solution?\n" ]
[ -3 ]
[ "catboost", "python" ]
stackoverflow_0073192979_catboost_python.txt
Q: R ggraph facets I'm having difficulty figuring out how to facet a graph properly. See for example the following. library(tidyverse) library(tidygraph) library(ggraph) myedges <- data.frame(from=rep(letters[1:5],2), to=c(rep(LETTERS[12:13],2), rep(LETTERS[14],3), LETTERS[15:16], LETTERS[17]), n_user=sample(1:20, 10, replace=TRUE), f=rep(c("face_A", "face_B"),5) ) mynodes <- myedges %>% pivot_longer(cols = c(from, to), names_to = "od", values_to = "node_name") %>% group_by(node_name) %>% summarise(n_user=sum(n_user)) g<-tbl_graph(nodes = mynodes, edges= myedges) # Arc diagram with edge faceting, it seems ok but the nodes ggraph(g, layout = 'linear') + geom_edge_arc(aes(edge_width=n_user, label=n_user), label_pos=0.1, edge_alpha=0.2)+ geom_node_point(aes(size=n_user), alpha=0.5, show.legend = FALSE)+ geom_node_text(aes(label = node_name), size=3, nudge_y = - 0.5)+ facet_edges(facets = vars(f), scales = "free") The graph is almost fine except that I would like to have for each panel just the nodes that are effectively connected by edges: i.e. not having "orphan" nodes like the node "O" in the panel "face_A" or the node "P" in the panel "face_B". Given that, I expect facet_nodes would be my potential solution by drawing just the nodes mapped by a variable and the corresponding edges for the nodes present in that panel. I expect to accomplish that I need to introduce the mapping variable in nodes but here comes the problem because I can not conceive a proper way to do that. The expected result is a graph with each panel node connected by edges Any suggestions for that? A: I think the problem here is that you are trying to plot two subgraphs using facets, but the nodes are not mutually exclusive across the faceting variable. This means you can't use facet_node. Since you are faceting by an edge attribute, you need to use facet_edge, but unfortunately facet_edge plots all the nodes, with no option to remove isolated nodes. The obvious way to get round this (even though it's a bit laborious) is to plot two different subgraphs and join them with patchwork: library(patchwork) gA <- g %>% activate(edges) %>% filter(f == "face_A") %>% activate(nodes) %>% filter(!node_is_isolated()) gB <- g %>% activate(edges) %>% filter(f == "face_B") %>% activate(nodes) %>% filter(!node_is_isolated()) p1 <- ggraph(gA, layout = 'linear') + geom_edge_arc(aes(edge_width = n_user, label = n_user), label_pos = 0.1, edge_alpha = 0.2) + geom_node_point(aes(size=n_user), alpha = 0.5, show.legend = FALSE) + geom_node_text(aes(label = node_name), size = 3, nudge_y = - 0.5) + facet_grid(.~f) + theme(legend.position = "none") p2 <- ggraph(gB, layout = 'linear') + geom_edge_arc(aes(edge_width = n_user, label = n_user), label_pos = 0.1, edge_alpha = 0.2) + geom_node_point(aes(size = n_user), alpha = 0.5, show.legend = FALSE) + geom_node_text(aes(label = node_name), size = 3, nudge_y = - 0.5) + facet_grid(.~f) p1 + p2 A: by further considering the above approach I came out with this sort of solution that still needs to be rounded off in some corners; some passages of the code are rather rough but the overall solution deserves to point in the direction I would like to go further I'm posting here the complete code library(tidyverse) library(tidygraph) library(ggraph) myedges <- data.frame(from=rep(letters[1:5],2), to=c(rep(LETTERS[12:13],2), rep(LETTERS[14],3), LETTERS[15:16], LETTERS[17]), n_user=sample(1:20, 10, replace=TRUE), f=rep(c("face_A", "face_B"),5) ) mynodes <- myedges %>% pivot_longer(cols = c(from, to), names_to = "od", values_to = "node_name") %>% group_by(node_name) %>% summarise(n_user=sum(n_user)) g<-tbl_graph(nodes = mynodes, edges= myedges) graph_list <- list() for(i in unique(myedges$f)) { gr <- g %>% activate(edges) %>% filter(f == i) %>% activate(nodes) %>% filter(!node_is_isolated()) graph_list[[i]] <- gr } plot_list <- list() for(i in seq_along(graph_list)){ pl<-ggraph(graph_list[[i]], layout = 'linear') + geom_edge_arc(aes(edge_width = n_user, label = n_user), label_pos = 0.1, edge_alpha = 0.2) + geom_node_point(aes(size=n_user), alpha = 0.5, show.legend = FALSE) + geom_node_text(aes(label = node_name), size = 3, nudge_y = - 0.5) + facet_grid(.~f) + theme(legend.position = "none") plot_list[[i]] <- pl } library(ggpubr) ggarrange(plotlist = plot_list, ncol = max(seq_along(graph_list)) ) thank you for the hints
R ggraph facets
I'm having difficulty figuring out how to facet a graph properly. See for example the following. library(tidyverse) library(tidygraph) library(ggraph) myedges <- data.frame(from=rep(letters[1:5],2), to=c(rep(LETTERS[12:13],2), rep(LETTERS[14],3), LETTERS[15:16], LETTERS[17]), n_user=sample(1:20, 10, replace=TRUE), f=rep(c("face_A", "face_B"),5) ) mynodes <- myedges %>% pivot_longer(cols = c(from, to), names_to = "od", values_to = "node_name") %>% group_by(node_name) %>% summarise(n_user=sum(n_user)) g<-tbl_graph(nodes = mynodes, edges= myedges) # Arc diagram with edge faceting, it seems ok but the nodes ggraph(g, layout = 'linear') + geom_edge_arc(aes(edge_width=n_user, label=n_user), label_pos=0.1, edge_alpha=0.2)+ geom_node_point(aes(size=n_user), alpha=0.5, show.legend = FALSE)+ geom_node_text(aes(label = node_name), size=3, nudge_y = - 0.5)+ facet_edges(facets = vars(f), scales = "free") The graph is almost fine except that I would like to have for each panel just the nodes that are effectively connected by edges: i.e. not having "orphan" nodes like the node "O" in the panel "face_A" or the node "P" in the panel "face_B". Given that, I expect facet_nodes would be my potential solution by drawing just the nodes mapped by a variable and the corresponding edges for the nodes present in that panel. I expect to accomplish that I need to introduce the mapping variable in nodes but here comes the problem because I can not conceive a proper way to do that. The expected result is a graph with each panel node connected by edges Any suggestions for that?
[ "I think the problem here is that you are trying to plot two subgraphs using facets, but the nodes are not mutually exclusive across the faceting variable. This means you can't use facet_node. Since you are faceting by an edge attribute, you need to use facet_edge, but unfortunately facet_edge plots all the nodes, with no option to remove isolated nodes.\nThe obvious way to get round this (even though it's a bit laborious) is to plot two different subgraphs and join them with patchwork:\nlibrary(patchwork)\n\ngA <- g %>% \n activate(edges) %>% \n filter(f == \"face_A\") %>% \n activate(nodes) %>% \n filter(!node_is_isolated())\n\ngB <- g %>% \n activate(edges) %>% \n filter(f == \"face_B\") %>% \n activate(nodes) %>% \n filter(!node_is_isolated())\n\np1 <- ggraph(gA, layout = 'linear') + \n geom_edge_arc(aes(edge_width = n_user, label = n_user), \n label_pos = 0.1, edge_alpha = 0.2) +\n geom_node_point(aes(size=n_user), alpha = 0.5, show.legend = FALSE) +\n geom_node_text(aes(label = node_name), size = 3, nudge_y = - 0.5) +\n facet_grid(.~f) +\n theme(legend.position = \"none\")\n\np2 <- ggraph(gB, layout = 'linear') + \n geom_edge_arc(aes(edge_width = n_user, label = n_user), \n label_pos = 0.1, edge_alpha = 0.2) +\n geom_node_point(aes(size = n_user), alpha = 0.5, show.legend = FALSE) +\n geom_node_text(aes(label = node_name), size = 3, nudge_y = - 0.5) +\n facet_grid(.~f)\n\np1 + p2\n\n\n", "by further considering the above approach I came out with this sort of solution that still needs to be rounded off in some corners;\nsome passages of the code are rather rough but the overall solution deserves to point in the direction I would like to go further\nI'm posting here the complete code\nlibrary(tidyverse)\nlibrary(tidygraph)\nlibrary(ggraph)\n\nmyedges <- data.frame(from=rep(letters[1:5],2),\n to=c(rep(LETTERS[12:13],2),\n rep(LETTERS[14],3),\n LETTERS[15:16], \n LETTERS[17]),\n n_user=sample(1:20, 10, replace=TRUE),\n f=rep(c(\"face_A\", \"face_B\"),5)\n) \n\n\nmynodes <- myedges %>% \n pivot_longer(cols = c(from, to),\n names_to = \"od\",\n values_to = \"node_name\") %>% \n group_by(node_name) %>% \n summarise(n_user=sum(n_user)) \n\ng<-tbl_graph(nodes = mynodes, edges= myedges)\n\n\ngraph_list <- list() \nfor(i in unique(myedges$f)) {\n \n gr <- g %>% \n activate(edges) %>% \n filter(f == i) %>% \n activate(nodes) %>% \n filter(!node_is_isolated()) \n \n graph_list[[i]] <- gr\n}\n\nplot_list <- list()\nfor(i in seq_along(graph_list)){\n \n pl<-ggraph(graph_list[[i]], layout = 'linear') + \n geom_edge_arc(aes(edge_width = n_user, label = n_user), \n label_pos = 0.1, edge_alpha = 0.2) +\n geom_node_point(aes(size=n_user), alpha = 0.5, show.legend = FALSE) +\n geom_node_text(aes(label = node_name), size = 3, nudge_y = - 0.5) +\n facet_grid(.~f) +\n theme(legend.position = \"none\")\n \n plot_list[[i]] <- pl\n} \n\nlibrary(ggpubr)\n\nggarrange(plotlist = plot_list, \n ncol = max(seq_along(graph_list))\n)\n\nthank you for the hints\n" ]
[ 1, 1 ]
[]
[]
[ "facet", "ggraph", "r" ]
stackoverflow_0074674180_facet_ggraph_r.txt
Q: Reload JS function after reload DIV the context: I have a div (#container) with js inside that return planet rise and planet set. When I reload my div (#container) like this: $("#container").load(location.href + " #container"); It doesn't reload my js inside it and therefore does not display planet rise and planet set. I try to reload the js function that calcul planet rise and planet set (loadPlanetComponent()) ,like this: function loadTonight() { $("#container").load(location.href + " #container"); loadPlanetComponent(); } But when I do that, it reload my function before or at the same time it reload my div so variables (planet rise and planet set) are not displayed. Also I try 2 things: Put a delay to reload loadPlanetComponent(), but sometimes, when the div takes time to load, it doesn't work Wait the reload of the div but it does'nt work. A: jQuery's load() function accepts a callback function to execute after the status is set to complete: If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. So to solve the issue, you simply need to provide a callback function to your load() function: $("#container").load(location.href + " #container", function(){ loadPlanetComponent(); });
Reload JS function after reload DIV
the context: I have a div (#container) with js inside that return planet rise and planet set. When I reload my div (#container) like this: $("#container").load(location.href + " #container"); It doesn't reload my js inside it and therefore does not display planet rise and planet set. I try to reload the js function that calcul planet rise and planet set (loadPlanetComponent()) ,like this: function loadTonight() { $("#container").load(location.href + " #container"); loadPlanetComponent(); } But when I do that, it reload my function before or at the same time it reload my div so variables (planet rise and planet set) are not displayed. Also I try 2 things: Put a delay to reload loadPlanetComponent(), but sometimes, when the div takes time to load, it doesn't work Wait the reload of the div but it does'nt work.
[ "jQuery's load() function accepts a callback function to execute after the status is set to complete:\n\nIf a \"complete\" callback is provided, it is executed after post-processing and HTML insertion has been performed.\n\nSo to solve the issue, you simply need to provide a callback function to your load() function:\n$(\"#container\").load(location.href + \" #container\", function(){ \n loadPlanetComponent();\n});\n\n" ]
[ 0 ]
[]
[]
[ "ajax", "html", "javascript", "jquery" ]
stackoverflow_0074680483_ajax_html_javascript_jquery.txt
Q: Chrome Extension with injected Javascript - Cannot read properties of undefined (reading 'sendMessage') I have a script that I inject in the DOM and I want to send messages to my service worker in the background. I am getting an error and I don't understand why. Here is my background.js file: chrome.runtime.onMessage.addListener((req, sender, sendRes) => { console.log('this has worked', req, sender, sendRes('this worked')); return true; }); Here is my inject.js file that injects the injected.js (see below) code: const s = document.createElement('script'); s.src = chrome.runtime.getURL('injected.js'); s.onload = function () { this.remove(); }; (document.head || document.documentElement).appendChild(s); injected.js: console.log('fetch interceptor started'); const { fetch: origFetch } = window; chrome.runtime.sendMessage({ works: 'This worked at least' }, (res) => console.log(res)); // Error is thrown immediately window.fetch = async (...args) => { const response = await origFetch(...args); const url = new URL(args[0].url); // sendMessageToBackground({ pathname, ...url.searchParams }); // not in use because it throws error at the top already response .clone() .json() .then(async (body) => await sendMessageToBackground({ pathname, body })) .catch((err) => console.error(err)); return response; }; async function sendMessageToBackground(msg) { const res = await chrome.runtime.sendMessage(msg); console.log('result message', res); console.log('msg', msg); } manifest.json in case required: { ... "permissions": ["storage", "activeTab", "scripting", "webRequest"], "host_permissions": ["https://REDACTED.com/*"], "manifest_version": 3, "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["https://REDACTED.com/*"], "run_at": "document_start", "js": ["inject.js"] } ], "web_accessible_resources": [{ "resources": ["injected.js"], "matches": ["https://REDACTED.com/*"] }], ... } A: By injecting a content script declaratively or in a programmed way through the methods allowed by the "scripting" and\or "tabs" permissions, you bring to the web page a set of objects belonging to the world of extensions to which you would normally not be able to access. Therefore, the inject.js script will be able to access these objects (in your case chrome.runtime), while the injectED.js script will not. I don't know what purpose your Chinese box system has, but I would try to skip inject.js and inject injectED.js declaratively. For the await speech together with .then, in my opinion there are no contraindications (at least at first sight). I've written routines before where I use this mix and never had a issue.
Chrome Extension with injected Javascript - Cannot read properties of undefined (reading 'sendMessage')
I have a script that I inject in the DOM and I want to send messages to my service worker in the background. I am getting an error and I don't understand why. Here is my background.js file: chrome.runtime.onMessage.addListener((req, sender, sendRes) => { console.log('this has worked', req, sender, sendRes('this worked')); return true; }); Here is my inject.js file that injects the injected.js (see below) code: const s = document.createElement('script'); s.src = chrome.runtime.getURL('injected.js'); s.onload = function () { this.remove(); }; (document.head || document.documentElement).appendChild(s); injected.js: console.log('fetch interceptor started'); const { fetch: origFetch } = window; chrome.runtime.sendMessage({ works: 'This worked at least' }, (res) => console.log(res)); // Error is thrown immediately window.fetch = async (...args) => { const response = await origFetch(...args); const url = new URL(args[0].url); // sendMessageToBackground({ pathname, ...url.searchParams }); // not in use because it throws error at the top already response .clone() .json() .then(async (body) => await sendMessageToBackground({ pathname, body })) .catch((err) => console.error(err)); return response; }; async function sendMessageToBackground(msg) { const res = await chrome.runtime.sendMessage(msg); console.log('result message', res); console.log('msg', msg); } manifest.json in case required: { ... "permissions": ["storage", "activeTab", "scripting", "webRequest"], "host_permissions": ["https://REDACTED.com/*"], "manifest_version": 3, "background": { "service_worker": "background.js" }, "content_scripts": [ { "matches": ["https://REDACTED.com/*"], "run_at": "document_start", "js": ["inject.js"] } ], "web_accessible_resources": [{ "resources": ["injected.js"], "matches": ["https://REDACTED.com/*"] }], ... }
[ "By injecting a content script declaratively or in a programmed way through the methods allowed by the \"scripting\" and\\or \"tabs\" permissions, you bring to the web page a set of objects belonging to the world of extensions to which you would normally not be able to access.\nTherefore, the inject.js script will be able to access these objects (in your case chrome.runtime), while the injectED.js script will not.\nI don't know what purpose your Chinese box system has, but I would try to skip inject.js and inject injectED.js declaratively.\nFor the await speech together with .then, in my opinion there are no contraindications (at least at first sight).\nI've written routines before where I use this mix and never had a issue.\n" ]
[ 0 ]
[]
[]
[ "google_chrome_extension", "javascript" ]
stackoverflow_0074678830_google_chrome_extension_javascript.txt
Q: How do I structure classes in the header so that they work in the cpp file? Ok so I guess this is a multi-layer question. I'm trying to take this procedural program I wrote and challenge myself by using classes and objects to simplify it. Also just to practice. I've been working on this specific program for over a month and a half now and I'm having issues with the structure of the header file and actually creating objects in the cpp file. I'll include the code below. HEADER FILE ` #include <cmath> #include <iomanip> #include <iostream> #include <string> #pragma once using namespace std; class calculations { public: double rate, tax, taxable, income, mortgageCred, interest; int deduction, mortgage, age = 1, taxCredit; bool hasMortgage, blind, senior, single; string answer1, answer2, answer3, answer4, answer5; calculations(){}; calculations(double i, int d) { income = i; deduction = d; }; calculations(double in, string a5, int mor) { interest = in; answer5 = a5; mortgage = mor; }; calculations(string a1, string a2, string a3, bool sin, bool sen, bool bld, int d) { answer1 = a1; answer2 = a2; answer3 = a3; single = sin; senior = sen; blind = bld; deduction = d; }; calculations(string a4, int tC) { answer4 = a4; taxCredit = tC; }; void finalcalc(double i, int d) { deduction = d; income = i; do { cout << "What was your income for the 2022 tax year?: "; cin >> income; taxable = income - deduction; if (taxable < 1) { tax = 0; break; } if (taxable >= 1 && taxable <= 10000) { rate = 0.10; tax = rate * taxable; break; } if (taxable > 10000 && taxable <= 40000) { rate = 0.12; tax = (rate * (taxable - 10000.00)) + 1000.00; break; } if (taxable > 40000 && taxable <= 89000) { rate = 0.22; tax = (rate * (taxable - 40000.00)) + 4600.00; break; } if (taxable > 80000 && taxable <= 170000) { rate = 0.24; tax = (rate * (taxable - 80000.00)) + 12400.00; break; } if (taxable > 170000 && taxable <= 216000) { rate = 0.32; tax = (rate * (taxable - 170000.00)) + 34200.00; break; } if (taxable > 216000 && taxable <= 540000) { rate = 0.35; tax = (rate * (taxable - 216000.00)) + 48920.00; break; } if (taxable > 540000) { rate = 0.37; tax = (rate * (taxable - 540000.00)) + 162320.00; break; } } while (age == 3); cout << "Taxes due total $" << tax << "." << endl; } void mortgageCalc(double in, string a5, int mor) { interest = in; answer5 = a5; mortgage = mor; do { cout << "Did you pay a mortgage on your home this year?: "; cin >> answer5; if (answer5 == "yes") { hasMortgage = true; cout << "Great! Youll get a deduction for that." << endl; cout << "What was the principal of the mortgage (ie. 2000)?: "; cin >> mortgage; cout << endl; cout << "Thanks! Now we need the interest rate on the mortgage." << endl; cout << "You can enter it as you would a percentage ie 3.15. : "; cin >> interest; interest = interest * 0.01; mortgageCred = mortgage * interest; deduction = deduction + mortgageCred; age = 1; break; } else if (answer5 == "no") { hasMortgage = false; cout << "Thats ok! lets move on to some other stuff." << endl; age = 1; break; } else { age = 3; } } while (age == 3); } void deductionCalc(string a1, string a2, string a3, bool sin, bool sen, bool bld, int ded) { answer1 = a1; answer2 = a2; answer3 = a3; single = sin; senior = sen; blind = bld; deduction = ded; do { cout << "Are you filing single?: "; cin >> answer1; if (answer1 == "yes") { single = true; deduction = 13850; } else if (answer1 == "no") { single = false; deduction = 20800; } else { age = 3; } cout << "Are you over 65 years old?: "; cin >> answer2; if (answer2 == "yes") { senior = true; deduction += 1850; } else if (answer2 == "no") { senior = false; } else { age = 3; } cout << "Are you considered legally blind?: "; cin >> answer3; if (answer3 == "yes") { blind = true; deduction += 1850; age = 1; } else if (answer3 == "no") { blind = false; age = 1; } else { age = 3; } while (age == 3); } void charityCalc(string a4, int tC) { answer4 = a4; taxCredit = tC; do { cout << "Did you make any contributions to a charitable organization in 2022?: " << endl; cin >> answer4; if (answer4 == "yes") { cout << "Great! That will help your deduction" << endl; cout << "Please enter how much money you gave to charity in 2022: "; cin >> taxCredit; deduction = deduction + taxCredit; } else if (answer4 == "no") { cout << "OK! Next question!" << endl; } else { age = 3; } } while (age == 3); } int getStats() { cout << "Marital Status: " << answer1 << endl; cout << "Over 65: " << answer2 << endl; cout << "Legally Blind: " << answer3 << endl; if (answer4 == "yes") { cout << "Charitable Donation: " << answer4 << endl; cout << "Charitable Donation Amount: $" << taxCredit << endl; } else { cout << "Charitable Donation: " << answer4 << endl; } } }; ` CPP FILE ` #include <iostream> #include <iomanip> #include <string> #include <cmath> #include "Taxes.h" #include "C:\Users\samfi\Desktop\Taxes.h" using namespace std; int main() { double income, rate, tax, taxable, interest, mortgageCred; string more, answer1, answer2, answer3, answer4, answer5; bool senior, single, blind, hasMortgage; int deduction = 0, times, taxCredit = 0, mortgage = 0, age = 1; cout << "Welcome to the Simple Tax Calculator. Let's get started!" << endl; cout << endl; for (times = 0; times < 5; times++) { // standard deduction calculator calculations::deductionCalc(answer1, answer2, answer3, single, senior, blind, deduction); //charitible donation calculations::charityCalc(answer4, taxCredit); // nortgage calculation and deduction. calculations::mortgageCalc(interest, answer5, mortgage); // details cout << "Lets go over your details just to make sure we got them right." << endl; calculations::getStats(); // tax calculator calculations::finalcalc(income, deduction); //restart?? {cout << "Would you like to calculate another tax estimate?: "; cin >> more; if (more == "yes") { cout << "Restarting..." << endl; cout << endl; } else if (more == "no") { times = 5; break; } else { cout << "Exception Thrown: " << more << ", is not a valid answer." << endl; } } } } ` I've tried so many different suggestions. I've tried creating objects in the cpp, I've tried creating multiple constructors, I've tried changing the methods to non voids. nothing seems to be working so I thought I could get another set of eyes on it. Ideally the program is supposed to calculate tax deductions and taxes owed based on income brackets and then your deduction is obviously increased by certain parameters. I'm not too concerned with whether its accurate per the IRS or not I just want it to work. I'm trying to learn how multifile programs work and this was a good place to start. the main questions here are: What is wrong with the structure of the the class/header? How can I make the two files work together to get the program running? How would I create objects in the CPP to call methods from the header? Anything you would add take away from this to make it more efficient/effective? Something to note: I was once in school for this but found I work better on my own with the help of other people and google. So I thought why waste my money if I'm not getting anything of value from this and I can learn much easier for free. The point of saying that is to make known that this isn't for school or something so it's not like youre doing my homework for me or anything.
How do I structure classes in the header so that they work in the cpp file?
Ok so I guess this is a multi-layer question. I'm trying to take this procedural program I wrote and challenge myself by using classes and objects to simplify it. Also just to practice. I've been working on this specific program for over a month and a half now and I'm having issues with the structure of the header file and actually creating objects in the cpp file. I'll include the code below. HEADER FILE ` #include <cmath> #include <iomanip> #include <iostream> #include <string> #pragma once using namespace std; class calculations { public: double rate, tax, taxable, income, mortgageCred, interest; int deduction, mortgage, age = 1, taxCredit; bool hasMortgage, blind, senior, single; string answer1, answer2, answer3, answer4, answer5; calculations(){}; calculations(double i, int d) { income = i; deduction = d; }; calculations(double in, string a5, int mor) { interest = in; answer5 = a5; mortgage = mor; }; calculations(string a1, string a2, string a3, bool sin, bool sen, bool bld, int d) { answer1 = a1; answer2 = a2; answer3 = a3; single = sin; senior = sen; blind = bld; deduction = d; }; calculations(string a4, int tC) { answer4 = a4; taxCredit = tC; }; void finalcalc(double i, int d) { deduction = d; income = i; do { cout << "What was your income for the 2022 tax year?: "; cin >> income; taxable = income - deduction; if (taxable < 1) { tax = 0; break; } if (taxable >= 1 && taxable <= 10000) { rate = 0.10; tax = rate * taxable; break; } if (taxable > 10000 && taxable <= 40000) { rate = 0.12; tax = (rate * (taxable - 10000.00)) + 1000.00; break; } if (taxable > 40000 && taxable <= 89000) { rate = 0.22; tax = (rate * (taxable - 40000.00)) + 4600.00; break; } if (taxable > 80000 && taxable <= 170000) { rate = 0.24; tax = (rate * (taxable - 80000.00)) + 12400.00; break; } if (taxable > 170000 && taxable <= 216000) { rate = 0.32; tax = (rate * (taxable - 170000.00)) + 34200.00; break; } if (taxable > 216000 && taxable <= 540000) { rate = 0.35; tax = (rate * (taxable - 216000.00)) + 48920.00; break; } if (taxable > 540000) { rate = 0.37; tax = (rate * (taxable - 540000.00)) + 162320.00; break; } } while (age == 3); cout << "Taxes due total $" << tax << "." << endl; } void mortgageCalc(double in, string a5, int mor) { interest = in; answer5 = a5; mortgage = mor; do { cout << "Did you pay a mortgage on your home this year?: "; cin >> answer5; if (answer5 == "yes") { hasMortgage = true; cout << "Great! Youll get a deduction for that." << endl; cout << "What was the principal of the mortgage (ie. 2000)?: "; cin >> mortgage; cout << endl; cout << "Thanks! Now we need the interest rate on the mortgage." << endl; cout << "You can enter it as you would a percentage ie 3.15. : "; cin >> interest; interest = interest * 0.01; mortgageCred = mortgage * interest; deduction = deduction + mortgageCred; age = 1; break; } else if (answer5 == "no") { hasMortgage = false; cout << "Thats ok! lets move on to some other stuff." << endl; age = 1; break; } else { age = 3; } } while (age == 3); } void deductionCalc(string a1, string a2, string a3, bool sin, bool sen, bool bld, int ded) { answer1 = a1; answer2 = a2; answer3 = a3; single = sin; senior = sen; blind = bld; deduction = ded; do { cout << "Are you filing single?: "; cin >> answer1; if (answer1 == "yes") { single = true; deduction = 13850; } else if (answer1 == "no") { single = false; deduction = 20800; } else { age = 3; } cout << "Are you over 65 years old?: "; cin >> answer2; if (answer2 == "yes") { senior = true; deduction += 1850; } else if (answer2 == "no") { senior = false; } else { age = 3; } cout << "Are you considered legally blind?: "; cin >> answer3; if (answer3 == "yes") { blind = true; deduction += 1850; age = 1; } else if (answer3 == "no") { blind = false; age = 1; } else { age = 3; } while (age == 3); } void charityCalc(string a4, int tC) { answer4 = a4; taxCredit = tC; do { cout << "Did you make any contributions to a charitable organization in 2022?: " << endl; cin >> answer4; if (answer4 == "yes") { cout << "Great! That will help your deduction" << endl; cout << "Please enter how much money you gave to charity in 2022: "; cin >> taxCredit; deduction = deduction + taxCredit; } else if (answer4 == "no") { cout << "OK! Next question!" << endl; } else { age = 3; } } while (age == 3); } int getStats() { cout << "Marital Status: " << answer1 << endl; cout << "Over 65: " << answer2 << endl; cout << "Legally Blind: " << answer3 << endl; if (answer4 == "yes") { cout << "Charitable Donation: " << answer4 << endl; cout << "Charitable Donation Amount: $" << taxCredit << endl; } else { cout << "Charitable Donation: " << answer4 << endl; } } }; ` CPP FILE ` #include <iostream> #include <iomanip> #include <string> #include <cmath> #include "Taxes.h" #include "C:\Users\samfi\Desktop\Taxes.h" using namespace std; int main() { double income, rate, tax, taxable, interest, mortgageCred; string more, answer1, answer2, answer3, answer4, answer5; bool senior, single, blind, hasMortgage; int deduction = 0, times, taxCredit = 0, mortgage = 0, age = 1; cout << "Welcome to the Simple Tax Calculator. Let's get started!" << endl; cout << endl; for (times = 0; times < 5; times++) { // standard deduction calculator calculations::deductionCalc(answer1, answer2, answer3, single, senior, blind, deduction); //charitible donation calculations::charityCalc(answer4, taxCredit); // nortgage calculation and deduction. calculations::mortgageCalc(interest, answer5, mortgage); // details cout << "Lets go over your details just to make sure we got them right." << endl; calculations::getStats(); // tax calculator calculations::finalcalc(income, deduction); //restart?? {cout << "Would you like to calculate another tax estimate?: "; cin >> more; if (more == "yes") { cout << "Restarting..." << endl; cout << endl; } else if (more == "no") { times = 5; break; } else { cout << "Exception Thrown: " << more << ", is not a valid answer." << endl; } } } } ` I've tried so many different suggestions. I've tried creating objects in the cpp, I've tried creating multiple constructors, I've tried changing the methods to non voids. nothing seems to be working so I thought I could get another set of eyes on it. Ideally the program is supposed to calculate tax deductions and taxes owed based on income brackets and then your deduction is obviously increased by certain parameters. I'm not too concerned with whether its accurate per the IRS or not I just want it to work. I'm trying to learn how multifile programs work and this was a good place to start. the main questions here are: What is wrong with the structure of the the class/header? How can I make the two files work together to get the program running? How would I create objects in the CPP to call methods from the header? Anything you would add take away from this to make it more efficient/effective? Something to note: I was once in school for this but found I work better on my own with the help of other people and google. So I thought why waste my money if I'm not getting anything of value from this and I can learn much easier for free. The point of saying that is to make known that this isn't for school or something so it's not like youre doing my homework for me or anything.
[]
[]
[ "// It looks like your header file is missing the closing }; for the calculations class. The header file should look like this:\n\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#pragma once\nusing namespace std;\n\n\nclass calculations {\n public:\n double rate, tax, taxable, income, mortgageCred, interest;\n int deduction, mortgage, age = 1, taxCredit;\n bool hasMortgage, blind, senior, single;\n string answer1, answer2, answer3, answer4, answer5;\n\n calculations(){};\n calculations(double i, int d) {\n income = i;\n deduction = d;\n };\n calculations(double in, string a5, int mor) {\n interest = in;\n answer5 = a5;\n mortgage = mor;\n };\n calculations(string a1, string a2, string a3, bool sin, bool sen, bool bld, int d) {\n answer1 = a1;\n answer2 = a2;\n answer3 = a3;\n single = sin;\n senior = sen;\n blind = bld;\n deduction = d;\n };\n calculations(string a4, int tC) {\n answer4 = a4;\n taxCredit = tC;\n };\n calculations(int d, int tC, int mor, int a, double tb, double t, double r, double i,double mC, double in, string a1, string a2, string a3, string a4, string a5, bool h, bool bld, bool sin, bool sen) {\n deduction = d;\n taxable = tb;\n tax = t;\n rate = r;\n income = i;\n hasMortgage = h;\n answer1 = a1;\n answer2 = a2;\n answer3 = a3;\n answer4 = a4;\n answer5 = a5;\n mortgage = mor;\n mortgageCred = mC;\n interest = in;\n age = a;\n single = sin;\n senior = sen;\n blind = bld;\n taxCredit = tC;\n }\n\n void finalcalc(double i, int d) {\n deduction = d;\n income = i;\n\n do {\n cout << \"What was your income for the 2022 tax year?: \";\n cin >> income;\n\n taxable = income - deduction;\n\n if (taxable < 1) {\n\n tax = 0;\n break;\n }\n if (taxable >= 1 && taxable <= 10000) {\n\n rate = 0.10;\n tax = rate * taxable;\n break;\n }\n if (taxable > 10000 && taxable <= 40000) {\n\n rate = 0.12;\n tax = (rate * (taxable - 10000.00)) + 1000.00;\n break;\n }\n if (taxable > 40000 && taxable <= 89000) {\n\n rate = 0.22;\n tax = (rate * (taxable - 40000.00)) + 4600.00;\n break;\n }\n if (tax\n\n" ]
[ -1 ]
[ "c++", "class", "header_files", "object", "oop" ]
stackoverflow_0074680853_c++_class_header_files_object_oop.txt
Q: function that only returns specified column with getSymbols() So i was trying to build this simple function that only returns adjusted price on google using getSymbols(). yahoo<-function(a){ a<-getSymbols("a", from= as.Date("1/1/13", format="%m/%d/%y"),to=Sys.time(), auto.assign = FALSE) a[,6] } However, this literally gets Symbol that is named a or x whatever it is. i was expecting something like yahoo(GOOG) will return google's adjusted price. Any idea how i can do this? Thanks! A: If we need to return the values, then get substitute the argument and deparse it to a string library(quantmod) yahoo <- function(a){ a <- deparse(substitute(a)) res <- getSymbols(a, from= as.Date("1/1/13", format="%m/%d/%y"),to=Sys.time(), auto.assign = FALSE) res[,6] } out <- yahoo(GOOG) head(out) # GOOG.Adjusted #2013-01-02 359.2882 #2013-01-03 359.4968 #2013-01-04 366.6006 #2013-01-07 365.0010 #2013-01-08 364.2807 #2013-01-09 366.6751 tail(out) # GOOG.Adjusted #2018-02-13 1052.10 #2018-02-14 1069.70 #2018-02-15 1089.52 #2018-02-16 1094.80 #2018-02-20 1102.46 #2018-02-21 1111.34 Another option would be using tidyquant and tidyverse libraries library(dplyr) library(tidyquant) yahoo2 <- function(a) { a <- quo_name(enquo(a)) tq_get(a, from = "2013-01-01", to = Sys.Date()) %>% select(date, adjusted) } yahoo2(GOOG) # A tibble: 1,294 x 2 # date adjusted # <date> <dbl> # 1 2013-01-02 359 # 2 2013-01-03 359 # 3 2013-01-04 367 # 4 2013-01-07 365 # 5 2013-01-08 364 # 6 2013-01-09 367 # 7 2013-01-10 368 # 8 2013-01-11 368 # 9 2013-01-14 359 #10 2013-01-15 360 # ... with 1,284 more rows A: Using assign will do it. assign('AAPL',getSymbols(‘AAPL,from='2018-02-01',auto.assign = F)[,6] ) If you want to do this in a function: yahoo <- function(ticker, from){ assign(ticker, getSymbols(ticker,from=from,auto.assign = F)[,6], pos = 1 ) } yahoo(‘AAPL’) Be aware that some Yahoo tickers are using special characters like ^ or @ that will be removed/replaced (i.e. "^GSPC”). You have more flexibility with the non-function method in naming your objects. A: You can use the quantmod functions Op(), Hi(), Lo(), Cl() and Ad() For example like this: a <- Ad(getSymbols("a", from= as.Date("1/1/13", format="%m/%d/%y"),to=Sys.time(), auto.assign = FALSE))
function that only returns specified column with getSymbols()
So i was trying to build this simple function that only returns adjusted price on google using getSymbols(). yahoo<-function(a){ a<-getSymbols("a", from= as.Date("1/1/13", format="%m/%d/%y"),to=Sys.time(), auto.assign = FALSE) a[,6] } However, this literally gets Symbol that is named a or x whatever it is. i was expecting something like yahoo(GOOG) will return google's adjusted price. Any idea how i can do this? Thanks!
[ "If we need to return the values, then get substitute the argument and deparse it to a string\nlibrary(quantmod) \nyahoo <- function(a){\n a <- deparse(substitute(a))\n res <- getSymbols(a, from= as.Date(\"1/1/13\", \n format=\"%m/%d/%y\"),to=Sys.time(), auto.assign = FALSE)\n res[,6]\n\n }\n\nout <- yahoo(GOOG)\nhead(out)\n# GOOG.Adjusted\n#2013-01-02 359.2882\n#2013-01-03 359.4968\n#2013-01-04 366.6006\n#2013-01-07 365.0010\n#2013-01-08 364.2807\n#2013-01-09 366.6751\n\ntail(out)\n# GOOG.Adjusted\n#2018-02-13 1052.10\n#2018-02-14 1069.70\n#2018-02-15 1089.52\n#2018-02-16 1094.80\n#2018-02-20 1102.46\n#2018-02-21 1111.34\n\n\nAnother option would be using tidyquant and tidyverse libraries\nlibrary(dplyr)\nlibrary(tidyquant)\nyahoo2 <- function(a) {\n a <- quo_name(enquo(a))\n tq_get(a, from = \"2013-01-01\", to = Sys.Date()) %>%\n select(date, adjusted)\n } \n\nyahoo2(GOOG)\n# A tibble: 1,294 x 2\n# date adjusted\n# <date> <dbl>\n# 1 2013-01-02 359\n# 2 2013-01-03 359\n# 3 2013-01-04 367\n# 4 2013-01-07 365\n# 5 2013-01-08 364\n# 6 2013-01-09 367\n# 7 2013-01-10 368\n# 8 2013-01-11 368\n# 9 2013-01-14 359\n#10 2013-01-15 360\n# ... with 1,284 more rows\n\n", "Using assign will do it.\nassign('AAPL',getSymbols(‘AAPL,from='2018-02-01',auto.assign = F)[,6] )\n\nIf you want to do this in a function:\nyahoo <- function(ticker, from){\n assign(ticker,\n getSymbols(ticker,from=from,auto.assign = F)[,6],\n pos = 1\n )\n}\nyahoo(‘AAPL’)\n\nBe aware that some Yahoo tickers are using special characters like ^ or @ that will be removed/replaced (i.e. \"^GSPC”). You have more flexibility with the non-function method in naming your objects. \n", "You can use the quantmod functions Op(), Hi(), Lo(), Cl() and Ad()\nFor example like this:\na <- Ad(getSymbols(\"a\", from= as.Date(\"1/1/13\", format=\"%m/%d/%y\"),to=Sys.time(), auto.assign = FALSE))\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "quantmod", "r" ]
stackoverflow_0048933291_quantmod_r.txt
Q: OPEN AI WHISPER : These errors make me mad (help please) I have a problem so I hope some programmers can help me solve it. Basically I run this : import whisper model = whisper.load_model("base") result = model.transcribe('test.mp3', fp16=False) And I get this : Output exceeds the size limit. Open the full output data in a text editor. Error Traceback (most recent call last) File 38 try: 39 # This launches a subprocess to decode audio while down-mixing and resampling as necessary. 40 # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed. 41 out, _ = ( ---> 42 ffmpeg.input(file, threads=0) 43 .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sr) 44 .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True) 45 ) 46 except ffmpeg.Error as e: File 324 if retcode: --> 325 raise Error('ffmpeg', out, err) 326 return out, err ` Error: ffmpeg error (see stderr output for detail) The above exception was the direct cause of the following exception: RuntimeError Traceback (most recent call last) Cell In[25], line 4 1 import whisper ... libswscale 6. 7.100 / 6. 7.100 libswresample 4. 7.100 / 4. 7.100 libpostproc 56. 6.100 / 56. 6.100 test.mp3: No such file or directory My goal is just to transcribe an mp3 audio file "test.mp3" into text, via the AI Whisper of OpenAI. I just want to make working Whisper with some audio files but these errors prevent me from doing so. And honestly, I've been at it for two days now and I'm not getting anywhere, I've opened the files in question, located lines 42 and 325 but I don't know what to do next. Thank you in advance for your help and your explanations. A: Use os module. import os # get the current working dir cwd = os.getcwd() # construct the full path to the file file_path = os.path.join(cwd, 'test.mp3') # transcribe the file result = model.transcribe(file_path, fp16=False)
OPEN AI WHISPER : These errors make me mad (help please)
I have a problem so I hope some programmers can help me solve it. Basically I run this : import whisper model = whisper.load_model("base") result = model.transcribe('test.mp3', fp16=False) And I get this : Output exceeds the size limit. Open the full output data in a text editor. Error Traceback (most recent call last) File 38 try: 39 # This launches a subprocess to decode audio while down-mixing and resampling as necessary. 40 # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed. 41 out, _ = ( ---> 42 ffmpeg.input(file, threads=0) 43 .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sr) 44 .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True) 45 ) 46 except ffmpeg.Error as e: File 324 if retcode: --> 325 raise Error('ffmpeg', out, err) 326 return out, err ` Error: ffmpeg error (see stderr output for detail) The above exception was the direct cause of the following exception: RuntimeError Traceback (most recent call last) Cell In[25], line 4 1 import whisper ... libswscale 6. 7.100 / 6. 7.100 libswresample 4. 7.100 / 4. 7.100 libpostproc 56. 6.100 / 56. 6.100 test.mp3: No such file or directory My goal is just to transcribe an mp3 audio file "test.mp3" into text, via the AI Whisper of OpenAI. I just want to make working Whisper with some audio files but these errors prevent me from doing so. And honestly, I've been at it for two days now and I'm not getting anywhere, I've opened the files in question, located lines 42 and 325 but I don't know what to do next. Thank you in advance for your help and your explanations.
[ "Use os module.\nimport os\n\n# get the current working dir\ncwd = os.getcwd()\n\n# construct the full path to the file\nfile_path = os.path.join(cwd, 'test.mp3')\n\n# transcribe the file\nresult = model.transcribe(file_path, fp16=False)\n\n" ]
[ 0 ]
[]
[]
[ "openai", "python", "runtime_error", "speech_to_text", "whisper" ]
stackoverflow_0074680851_openai_python_runtime_error_speech_to_text_whisper.txt
Q: CSS How do you override the custom font family set in the all selector? I downloaded two custom fonts for my website, and I am trying to make one of them the default font for almost everywhere in the website, and the other one for some certain areas. So my code look something like this: function App() { return ( <div className="App"> <nav> <ul className="Navbar"> <li className="link1"><Link to="/">Home</Link></li> <li className="link2"><Link to="/AboutMe">AboutMe</Link></li> </ul> </nav> <Routes> <Route path="/" element={<Home />}/> <Route path="/AboutMe" element={<AboutMe />}/> </Routes> </div> ); } CSS: *{ box-sizing: border-box; margin: 0; padding: 0; line-height: 18px; font-family: 'Montserrat-VariableFont_wght'; } @font-face { font-family: 'BowlbyOneSC-Regular'; src: url('../fonts/BowlbyOneSC-Regular.ttf') format('truetype'); font-weight: bold; } @font-face { font-family: 'Montserrat-VariableFont_wght'; src: url('../fonts/Montserrat-VariableFont_wght.ttf') format('truetype'); } .link1{ font-family: 'BowlbyOneSC-Regular'; } Both link1 and link2 are now in the font of Montserrat-VariableFont_wght, and when I remove font-family: 'Montserrat-VariableFont_wght';from the * selector. Link1 will then be BowlbyOneSC-Regular and then link2 become some random default font provided by browser, which is not what I want. So, how should I do it? A: You can make the .link1{ font-family: 'BowlbyOneSC-Regular' !important; } notice ! important this will override the link1 css and link2 will be default one defined. You can do something like a utility class with the font face. I usually do .ff-roboto .ff-arial and implement font family there. .ff-BowlbyOneSC';{ font-family: 'BowlbyOneSC-Regular'; } now you can use link2 as ff-BowlbyOneSC <li className="link2 ff-BowlbyOneSC"><Link to="/AboutMe">AboutMe</Link></li> * is not a good way of defining css property as it apply this font family to all the html element. body{ box-sizing: border-box; margin: 0; padding: 0; line-height: 18px; font-family: 'Montserrat-VariableFont_wght'; } you can also see I have removed regular from the name. It means you can also have font weight related utility functions like .fw-300 or fw-bold fw-black this how you can create reusable classes.
CSS How do you override the custom font family set in the all selector?
I downloaded two custom fonts for my website, and I am trying to make one of them the default font for almost everywhere in the website, and the other one for some certain areas. So my code look something like this: function App() { return ( <div className="App"> <nav> <ul className="Navbar"> <li className="link1"><Link to="/">Home</Link></li> <li className="link2"><Link to="/AboutMe">AboutMe</Link></li> </ul> </nav> <Routes> <Route path="/" element={<Home />}/> <Route path="/AboutMe" element={<AboutMe />}/> </Routes> </div> ); } CSS: *{ box-sizing: border-box; margin: 0; padding: 0; line-height: 18px; font-family: 'Montserrat-VariableFont_wght'; } @font-face { font-family: 'BowlbyOneSC-Regular'; src: url('../fonts/BowlbyOneSC-Regular.ttf') format('truetype'); font-weight: bold; } @font-face { font-family: 'Montserrat-VariableFont_wght'; src: url('../fonts/Montserrat-VariableFont_wght.ttf') format('truetype'); } .link1{ font-family: 'BowlbyOneSC-Regular'; } Both link1 and link2 are now in the font of Montserrat-VariableFont_wght, and when I remove font-family: 'Montserrat-VariableFont_wght';from the * selector. Link1 will then be BowlbyOneSC-Regular and then link2 become some random default font provided by browser, which is not what I want. So, how should I do it?
[ "You can make the\n.link1{\n font-family: 'BowlbyOneSC-Regular' !important;\n}\n\nnotice ! important this will override the link1 css and link2 will be default one defined.\nYou can do something like a utility class with the font face. I usually do .ff-roboto .ff-arial and implement font family there.\n.ff-BowlbyOneSC';{\n font-family: 'BowlbyOneSC-Regular';\n}\n\nnow you can use link2 as ff-BowlbyOneSC\n<li className=\"link2 ff-BowlbyOneSC\"><Link to=\"/AboutMe\">AboutMe</Link></li>\n\n* is not a good way of defining css property as it apply this font family to all the html element.\nbody{\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n line-height: 18px;\n font-family: 'Montserrat-VariableFont_wght';\n}\n\nyou can also see I have removed regular from the name. It means you can also have font weight related utility functions like .fw-300 or fw-bold fw-black this how you can create reusable classes.\n" ]
[ 0 ]
[]
[]
[ "css", "font_family", "fonts" ]
stackoverflow_0074680655_css_font_family_fonts.txt
Q: Use value out of ActionListener in Java I am juste starting to code, and I am trying to write a program were I would need a button to change a value (alea) that would be used out of actionPerformed methode. What I have currently wrote goes like this : import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ThreadLocalRandom; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.*; public class Quiz { public static void main(String[] args) { JButton btn = new JButton("Next"); btn.setBounds(200, 400, 200, 40); int alea = 0; btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { alea = ThreadLocalRandom.current().nextInt(1, 4 + 1); // I get the error "Local variable name defined in an enclosing scope must be final or effectively final" String test = "hello"; } }); String sp = Integer.toString(alea); String vue = sp + ".png"; String imgUrl="./images/"+vue; ImageIcon imageIcon = new ImageIcon(imgUrl); .... But like this the alea defined before the button doesn't seem to be the same as the one in the button. I searched the internet for an answer, and I don't understand why it doesn't work... Sorry for my crappy english. Thanks a lot in advance ! I tried not to declare alea before the button action, but inside the methode, and it did not work. I tried to use a getter and setter, but did not succeed. I searched the internet for solution, I encountered similar problem but the solution of which did not help me. A: You're coding this as if it were a linear console program, where this code is called: btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { alea = ThreadLocalRandom.current().nextInt(1, 4 + 1); String test = "hello"; } }); Before this is called: String sp = Integer.toString(alea); assuming that therefore the value of alea has been updated at this point. But that is not how this code works as it is most definitely not a linear program but rather an event-driven GUI program, and so alea won't change until the button's ActionListener changes it. So that is where you should get the new value and do what is needed with it. Suggestions: First and foremost, get all that code out of the static main method and into the OOP realm of instance methods and fields. Make the alea variable a private instance (non-static) field, if it is needed in multiple locations in your program. You're programming an event-driven GUI and so you should be listener for events and changing variable state in response to the events. This includes handling changes to the alea variable in the button's ActionListener, as noted above, because that is where you will be notified that it should be changed. Avoid null layouts and setBounds(...) as this will lead to inflexible and hard to maintain GUIs and instead learn and use the Swing layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info. This error, ""Local variable name defined in an enclosing scope must be final or effectively final", will go away if alea is an instance field of the class (not a local variable). For example import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.util.concurrent.ThreadLocalRandom; import javax.swing.*; @SuppressWarnings("serial") public class QuizFoo extends JPanel { public static final int ORIGIN = 1; public static final int SPREAD = 4; private int alea = 0; private JButton nextButton; private JTextArea outputArea;; public QuizFoo() { // add a listener to the button and add it to a JPanel nextButton = new JButton("Next"); nextButton.addActionListener(e -> nextActionPerformed(e)); JPanel buttonPanel = new JPanel(); buttonPanel.add(nextButton); // text area to display our GUI output. put it in a scroll pane int rows = 30; int columns = 50; outputArea = new JTextArea(rows, columns); outputArea.setFocusable(false); JScrollPane scrollPane = new JScrollPane(outputArea); // make the main jpanel use a borderlayout, and add our components to it setLayout(new BorderLayout()); add(buttonPanel, BorderLayout.PAGE_START); add(scrollPane, BorderLayout.CENTER); } // action listener called when button pressed private void nextActionPerformed(ActionEvent e) { alea = ThreadLocalRandom.current().nextInt(ORIGIN, ORIGIN + SPREAD); // USE ALEA HERE **** // for example: String textToAppend = "Alea: " + String.valueOf(alea) + "\n"; outputArea.append(textToAppend); } public static void main(String[] args) { // create the GUI in a Swing thread-safe way SwingUtilities.invokeLater(() -> { QuizFoo mainPanel = new QuizFoo(); JFrame frame = new JFrame("Quiz"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(mainPanel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }); } }
Use value out of ActionListener in Java
I am juste starting to code, and I am trying to write a program were I would need a button to change a value (alea) that would be used out of actionPerformed methode. What I have currently wrote goes like this : import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.ThreadLocalRandom; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.*; public class Quiz { public static void main(String[] args) { JButton btn = new JButton("Next"); btn.setBounds(200, 400, 200, 40); int alea = 0; btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { alea = ThreadLocalRandom.current().nextInt(1, 4 + 1); // I get the error "Local variable name defined in an enclosing scope must be final or effectively final" String test = "hello"; } }); String sp = Integer.toString(alea); String vue = sp + ".png"; String imgUrl="./images/"+vue; ImageIcon imageIcon = new ImageIcon(imgUrl); .... But like this the alea defined before the button doesn't seem to be the same as the one in the button. I searched the internet for an answer, and I don't understand why it doesn't work... Sorry for my crappy english. Thanks a lot in advance ! I tried not to declare alea before the button action, but inside the methode, and it did not work. I tried to use a getter and setter, but did not succeed. I searched the internet for solution, I encountered similar problem but the solution of which did not help me.
[ "You're coding this as if it were a linear console program, where this code is called:\nbtn.addActionListener(new ActionListener() { \n @Override\n public void actionPerformed(ActionEvent e) {\n alea = ThreadLocalRandom.current().nextInt(1, 4 + 1);\n String test = \"hello\";\n }\n});\n\nBefore this is called:\nString sp = Integer.toString(alea);\n\nassuming that therefore the value of alea has been updated at this point.\nBut that is not how this code works as it is most definitely not a linear program but rather an event-driven GUI program, and so alea won't change until the button's ActionListener changes it. So that is where you should get the new value and do what is needed with it.\nSuggestions:\n\nFirst and foremost, get all that code out of the static main method and into the OOP realm of instance methods and fields.\nMake the alea variable a private instance (non-static) field, if it is needed in multiple locations in your program.\nYou're programming an event-driven GUI and so you should be listener for events and changing variable state in response to the events. This includes handling changes to the alea variable in the button's ActionListener, as noted above, because that is where you will be notified that it should be changed.\nAvoid null layouts and setBounds(...) as this will lead to inflexible and hard to maintain GUIs and instead learn and use the Swing layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.\nThis error, \"\"Local variable name defined in an enclosing scope must be final or effectively final\", will go away if alea is an instance field of the class (not a local variable).\n\n\nFor example\nimport java.awt.BorderLayout;\nimport java.awt.event.ActionEvent;\nimport java.util.concurrent.ThreadLocalRandom;\nimport javax.swing.*;\n\n@SuppressWarnings(\"serial\")\npublic class QuizFoo extends JPanel {\n public static final int ORIGIN = 1;\n public static final int SPREAD = 4;\n private int alea = 0;\n private JButton nextButton;\n private JTextArea outputArea;;\n \n public QuizFoo() {\n // add a listener to the button and add it to a JPanel\n nextButton = new JButton(\"Next\");\n nextButton.addActionListener(e -> nextActionPerformed(e));\n JPanel buttonPanel = new JPanel();\n buttonPanel.add(nextButton);\n \n // text area to display our GUI output. put it in a scroll pane\n int rows = 30;\n int columns = 50;\n outputArea = new JTextArea(rows, columns);\n outputArea.setFocusable(false);\n JScrollPane scrollPane = new JScrollPane(outputArea);\n \n // make the main jpanel use a borderlayout, and add our components to it\n setLayout(new BorderLayout());\n add(buttonPanel, BorderLayout.PAGE_START);\n add(scrollPane, BorderLayout.CENTER);\n }\n \n // action listener called when button pressed\n private void nextActionPerformed(ActionEvent e) {\n alea = ThreadLocalRandom.current().nextInt(ORIGIN, ORIGIN + SPREAD);\n \n // USE ALEA HERE ****\n \n // for example:\n String textToAppend = \"Alea: \" + String.valueOf(alea) + \"\\n\";\n outputArea.append(textToAppend);\n }\n \n public static void main(String[] args) {\n // create the GUI in a Swing thread-safe way\n SwingUtilities.invokeLater(() -> {\n QuizFoo mainPanel = new QuizFoo();\n\n JFrame frame = new JFrame(\"Quiz\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.add(mainPanel);\n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n });\n }\n}\n\n" ]
[ 0 ]
[]
[]
[ "actionlistener", "java", "variables" ]
stackoverflow_0074680839_actionlistener_java_variables.txt
Q: [Vue warn]: Property or method is not defined on the instance but referenced during render The following code has been written to handle an event after a button click var MainTable = Vue.extend({ template: "<ul>" + "<li v-for='(set,index) in settings'>" + "{{index}}) " + "{{set.title}}" + "<button @click='changeSetting(index)'> Info </button>" + "</li>" + "</ul>", data: function() { return data; } }); Vue.component("main-table", MainTable); data.settingsSelected = {}; var app = new Vue({ el: "#settings", data: data, methods: { changeSetting: function(index) { data.settingsSelected = data.settings[index]; } } }); But the following error occurred: [Vue warn]: Property or method "changeSetting" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <MainTable>) A: Problem [Vue warn]: Property or method "changeSetting" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <MainTable>) The error is occurring because the changeSetting method is being referenced in the MainTable component here: "<button @click='changeSetting(index)'> Info </button>" + However the changeSetting method is not defined in the MainTable component. It is being defined in the root component here: var app = new Vue({ el: "#settings", data: data, methods: { changeSetting: function(index) { data.settingsSelected = data.settings[index]; } } }); What needs to be remembered is that properties and methods can only be referenced in the scope where they are defined. Everything in the parent template is compiled in parent scope; everything in the child template is compiled in child scope. You can read more about component compilation scope in Vue's documentation. What can I do about it? So far there has been a lot of talk about defining things in the correct scope so the fix is just to move the changeSetting definition into the MainTable component? It seems that simple but here's what I recommend. You'd probably want your MainTable component to be a dumb/presentational component. (Here is something to read if you don't know what it is but a tl;dr is that the component is just responsible for rendering something – no logic). The smart/container element is responsible for the logic – in the example given in your question the root component would be the smart/container component. With this architecture you can use Vue's parent-child communication methods for the components to interact. You pass down the data for MainTable via props and emit user actions from MainTable to its parent via events. It might look something like this: Vue.component('main-table', { template: "<ul>" + "<li v-for='(set, index) in settings'>" + "{{index}}) " + "{{set.title}}" + "<button @click='changeSetting(index)'> Info </button>" + "</li>" + "</ul>", props: ['settings'], methods: { changeSetting(value) { this.$emit('change', value); }, }, }); var app = new Vue({ el: '#settings', template: '<main-table :settings="data.settings" @change="changeSetting"></main-table>', data: data, methods: { changeSetting(value) { // Handle changeSetting }, }, }), The above should be enough to give you a good idea of what to do and kickstart resolving your issue. A: Should anybody land with the same silly problem I had, make sure your component has the 'data' property spelled correctly. (eg. data, and not date) <template> <span>{{name}}</span> </template> <script> export default { name: "MyComponent", data() { return { name: "" }; } </script> A: In my case the reason was, I only forgot the closing </script> tag. But that caused the same error message. A: It's probably caused by spelling error I got a typo at script closing tag </sscript> A: If you're experiencing this problem, check to make sure you don't have methods: { ... } or computed: { ... } declared twice A: Remember to return the property Another reason of seeing the Property "search" was accessed during render but is not defined on instance is when you forget to return the variable in the setup(){} function So remember to add the return statement at the end: export default { setup(){ const search = ref('') //Whatever code return {search} } } Note: I'm using the Composition API A: Adding my bit as well, should anybody struggle like me, notice that methods is a case-sensitive word: <template> <span>{{name}}</span> </template> <script> export default { name: "MyComponent", Methods: { name() {return '';} } </script> 'Methods' should be 'methods' A: I got this error when I tried assigning a component property to a state property during instantiation export default { props: ['value1'], data() { return { value2: this.value1 // throws the error } }, created(){ this.value2 = this.value1 // safe } } A: My issue was I was placing the methods inside my data object. just format it like this and it'll work nicely. <script> module.exports = { data: () => { return { name: "" } }, methods: { myFunc() { // code } } } </script> A: If you use two times vue instance. Then it will give you this error. For example in app.js and your own script tag in view file. Just use one time const app = new Vue({ el: '#app', }); A: In my case, I wrote it as "method" instead of "methods". So stupid. Wasted around 1 hour. A: Some common cases of this error Make sure your component has the data property spelled correctly Make sure your template is bot defined within another component’s template. Make sure you defined the variable inside data object Make sure your router name in string Get some more sollution A: It is most likely a spelling error of reserved vuejs variables. I got here because I misspelled computed: and vuejs would not recognize my computed property variables. So if you have an error like this, check your spelling first! A: I had two methods: in the <script>, goes to show, that you can spend hours looking for something that was such a simple mistake. A: if you have any props or imported variables (from external .js file) make sure to set them properly using created like this; make sure to init those vars: import { var1, var2} from './constants' //or export default { data(){ return { var1: 0, var2: 0, var3: 0, }, }, props: ['var3'], created(){ this.var1 = var1; this.var2 = var2; this.var3 = var3; } A: In my case it was a property that gave me the error, the correct writing and still gave me the error in the console. I searched so much and nothing worked for me, until I gave him Ctrl + F5 and Voilá! error was removed. :'v A: Look twice the warning : Property _____ was accessed during render but is not defined on instance. So you have to define it ... in the data function for example which commonly instantiate variables in a Vuejs app. and, it was my case and that way the problem has been fixed. That's all folk's ! A: In my case, I forgot to add the return keyword: computed: { image(){ this.productVariants[this.selectedVariant].image; }, inStock(){ this.productVariants[this.selectedVariant].quantity; } } Change to: computed: { image(){ return this.productVariants[this.selectedVariant].image; }, inStock(){ return this.productVariants[this.selectedVariant].quantity; } } A: Although some answers here maybe great, none helped my case (which is very similar to OP's error message). This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data). To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did: // pulled data in this life cycle hook, saving it to my store created() { FetchData.getProfile() .then(myProfile => { const mp = myProfile.data; console.log(mp) this.$store.dispatch('dispatchMyProfile', mp) this.propsToPass = mp; }) .catch(error => { console.log('There was an error:', error.response) }) } // called my store here computed: { menu() { return this.$store.state['myProfile'].profile } }, // then in my template, I pass this "menu" method in child component <LeftPanel :data="menu" /> This cleared that error away. I deployed it again to firebase hosting, and voila! Hope this bit helps you. A: In my case due to router name not in string: :to="{name: route-name, params: {id:data.id}}" change to router name in string: :to="{name: 'router-name', params: {id:data.id}}" A: In my case I was trying to pass a hard coded text value to another component with: ChildComponent(:displayMode="formMode") when it should be: ChildComponent(:displayMode="'formMode'") note the single quotes to indicate text instead of calling a local var inside the component. A: If you're using the Vue3 <script setup> style, make sure you've actually specified setup in the opening script tag: <script setup> I had lapsed into old habits and only created a block with <script>, but it took a while to notice it. https://v3.vuejs.org/api/sfc-script-setup.html A: It seems there are many scenarios that can trigger this error. Here's another one which I just resolved. I had the variable actionRequiredCount declared in the data section, but I failed to capitalize the C in Count when passing the variable as a params to a component. Here the variable is correct: data: () => { return{ actionRequiredCount: '' } } In my template it was incorrect (notd the no caps c in "count"): <MyCustomModule :actionRequiredCount="actionRequiredcount"/> Hope this helps someone. A: Most people do have an error here because of: a typo or something that they forgot to declare/use the opposite, did it in several places To avoid the typo issues, I recommend always using Vue VSCode Snippets so that you don't write anything by hand by rather use vbase, vdata, vmethod and get those parts generated for you. Here are the ones for Vue3. You can of course also create your own snippets by doing the following. Also make sure that you're properly writing all the correct names as shown here, here is a list: data props computed methods watch emits expose As for the second part, I usually recommend either searching the given keyword in your codebase. So like cmd + f + changeSetting in OP's case to see if it's missing a declaration somewhere in data, methods or alike. Or even better, use an ESlint configuration so that you will be warned in case you have any kind of issues in your codebase. Here is how to achieve such setup with a Nuxt project + ESlint + Prettier for the most efficient way to prevent bad practices while still getting a fast formatting! A: One other common scenario is: You have a component (child) extending another component (parent) You have a property or a method xyz defined under methods or computed on the parent component. Your are trying to use parent's xyz, but your child component defines its own methods or computed Sample code with the problem // PARENT COMPONENT export default { computed() { abc() {}, xyz() {} // <= needs to be used in child component }, ... } // CHILD COMPONENT export default { extends: myParentComponent, computed() { childProprty1() {}, childProprty2() {} } } The solution In this case you will need to redefine your xyz computed property under computed Solution 1: Redefine xyz and copy the code from the parent component // CHILD COMPONENT export default { extends: myParentComponent, computed() { xyz() { // do something cool! }, childProprty1() {}, childProprty2() {} } } Solution 2 Redefine xyz property reusing parent component code (no code redundancy) // CHILD COMPONENT export default { extends: myParentComponent, computed() { xyz() { return this.$parent.$options.computed.xyz }, childProprty1() {}, childProprty2() {} } } A: For me it happened because I wrote method: instead of methods: (plural). It's a silly mistake but it can happen :)
[Vue warn]: Property or method is not defined on the instance but referenced during render
The following code has been written to handle an event after a button click var MainTable = Vue.extend({ template: "<ul>" + "<li v-for='(set,index) in settings'>" + "{{index}}) " + "{{set.title}}" + "<button @click='changeSetting(index)'> Info </button>" + "</li>" + "</ul>", data: function() { return data; } }); Vue.component("main-table", MainTable); data.settingsSelected = {}; var app = new Vue({ el: "#settings", data: data, methods: { changeSetting: function(index) { data.settingsSelected = data.settings[index]; } } }); But the following error occurred: [Vue warn]: Property or method "changeSetting" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <MainTable>)
[ "Problem\n\n[Vue warn]: Property or method \"changeSetting\" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <MainTable>)\n\nThe error is occurring because the changeSetting method is being referenced in the MainTable component here:\n \"<button @click='changeSetting(index)'> Info </button>\" +\n\nHowever the changeSetting method is not defined in the MainTable component. It is being defined in the root component here:\nvar app = new Vue({\n el: \"#settings\",\n data: data,\n methods: {\n changeSetting: function(index) {\n data.settingsSelected = data.settings[index];\n }\n }\n});\n\nWhat needs to be remembered is that properties and methods can only be referenced in the scope where they are defined.\n\nEverything in the parent template is compiled in parent scope; everything in the child template is compiled in child scope.\n\nYou can read more about component compilation scope in Vue's documentation.\nWhat can I do about it?\nSo far there has been a lot of talk about defining things in the correct scope so the fix is just to move the changeSetting definition into the MainTable component?\nIt seems that simple but here's what I recommend.\nYou'd probably want your MainTable component to be a dumb/presentational component. (Here is something to read if you don't know what it is but a tl;dr is that the component is just responsible for rendering something – no logic). The smart/container element is responsible for the logic – in the example given in your question the root component would be the smart/container component. With this architecture you can use Vue's parent-child communication methods for the components to interact. You pass down the data for MainTable via props and emit user actions from MainTable to its parent via events. It might look something like this:\nVue.component('main-table', {\n template: \"<ul>\" +\n \"<li v-for='(set, index) in settings'>\" +\n \"{{index}}) \" +\n \"{{set.title}}\" +\n \"<button @click='changeSetting(index)'> Info </button>\" +\n \"</li>\" +\n \"</ul>\",\n props: ['settings'],\n methods: {\n changeSetting(value) {\n this.$emit('change', value);\n },\n },\n});\n\n\nvar app = new Vue({\n el: '#settings',\n template: '<main-table :settings=\"data.settings\" @change=\"changeSetting\"></main-table>',\n data: data,\n methods: {\n changeSetting(value) {\n // Handle changeSetting\n },\n },\n}),\n\nThe above should be enough to give you a good idea of what to do and kickstart resolving your issue.\n", "Should anybody land with the same silly problem I had, make sure your component has the 'data' property spelled correctly. (eg. data, and not date)\n<template>\n <span>{{name}}</span>\n</template>\n\n<script>\nexport default {\nname: \"MyComponent\",\ndata() {\n return {\n name: \"\"\n };\n}\n</script>\n\n", "In my case the reason was, I only forgot the closing\n</script>\n\ntag.\nBut that caused the same error message.\n", "It's probably caused by spelling error\nI got a typo at script closing tag\n</sscript>\n\n", "If you're experiencing this problem, check to make sure you don't have\nmethods: {\n...\n}\n\nor\ncomputed: {\n...\n}\n\ndeclared twice\n", "Remember to return the property\nAnother reason of seeing the Property \"search\" was accessed during render but is not defined on instance is when you forget to return the variable in the setup(){} function\nSo remember to add the return statement at the end:\nexport default {\n\n setup(){\n\n const search = ref('')\n //Whatever code\n\n return {search}\n\n }\n}\n\nNote: I'm using the Composition API\n", "Adding my bit as well, should anybody struggle like me, notice that methods is a case-sensitive word:\n<template>\n <span>{{name}}</span>\n</template>\n\n<script>\nexport default {\n name: \"MyComponent\",\n Methods: {\n name() {return '';}\n }\n</script>\n\n'Methods' should be 'methods'\n", "I got this error when I tried assigning a component property to a state property during instantiation\nexport default {\n props: ['value1'],\n data() {\n return {\n value2: this.value1 // throws the error\n }\n }, \n created(){\n this.value2 = this.value1 // safe\n }\n}\n\n", "My issue was I was placing the methods inside my data object. just format it like this and it'll work nicely.\n<script>\nmodule.exports = {\n data: () => {\n return {\n name: \"\"\n }\n },\n methods: {\n myFunc() {\n // code\n }\n }\n}\n</script>\n\n", "If you use two times vue instance. Then it will give you this error. For example in app.js and your own script tag in view file. Just use one time \n const app = new Vue({\n el: '#app',\n});\n\n", "In my case, I wrote it as \"method\" instead of \"methods\". So stupid. Wasted around 1 hour.\n", "Some common cases of this error\n\nMake sure your component has the data property spelled correctly\nMake sure your template is bot defined within another component’s template.\nMake sure you defined the variable inside data object\nMake sure your router name in string\n\nGet some more sollution\n", "It is most likely a spelling error of reserved vuejs variables. I got here because I misspelled computed: and vuejs would not recognize my computed property variables. So if you have an error like this, check your spelling first! \n", "I had two methods: in the <script>, goes to show, that you can spend hours looking for something that was such a simple mistake.\n", "if you have any props or imported variables (from external .js file) make sure to set them properly using created like this;\nmake sure to init those vars:\nimport { var1, var2} from './constants'\n\n//or\n\nexport default {\n data(){\n return {\n var1: 0,\n var2: 0,\n var3: 0,\n },\n },\n props: ['var3'],\n created(){\n this.var1 = var1;\n this.var2 = var2;\n this.var3 = var3;\n }\n \n\n", "In my case it was a property that gave me the error, the correct writing and still gave me the error in the console. I searched so much and nothing worked for me, until I gave him Ctrl + F5 and Voilá! error was removed. :'v\n", "Look twice the warning : Property _____ was accessed during render but is not defined on instance.\nSo you have to define it ... in the data function for example which commonly instantiate variables in a Vuejs app. and, it was my case and that way the problem has been fixed.\nThat's all folk's !\n", "In my case, I forgot to add the return keyword:\ncomputed: {\n image(){\n this.productVariants[this.selectedVariant].image;\n },\n inStock(){\n this.productVariants[this.selectedVariant].quantity;\n }\n}\n\nChange to:\ncomputed: {\n image(){\n return this.productVariants[this.selectedVariant].image;\n },\n inStock(){\n return this.productVariants[this.selectedVariant].quantity;\n }\n}\n\n\n", "Although some answers here maybe great, none helped my case (which is very similar to OP's error message).\nThis error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).\nTo fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:\n// pulled data in this life cycle hook, saving it to my store\ncreated() {\n FetchData.getProfile()\n .then(myProfile => {\n const mp = myProfile.data;\n console.log(mp)\n this.$store.dispatch('dispatchMyProfile', mp)\n this.propsToPass = mp;\n })\n .catch(error => {\n console.log('There was an error:', error.response)\n })\n}\n// called my store here\ncomputed: {\n menu() {\n return this.$store.state['myProfile'].profile\n }\n},\n\n// then in my template, I pass this \"menu\" method in child component\n <LeftPanel :data=\"menu\" />\n\nThis cleared that error away. I deployed it again to firebase hosting, and voila!\nHope this bit helps you.\n", "In my case due to router name not in string:\n:to=\"{name: route-name, params: {id:data.id}}\"\n\nchange to router name in string:\n:to=\"{name: 'router-name', params: {id:data.id}}\"\n\n", "In my case I was trying to pass a hard coded text value to another component with:\n ChildComponent(:displayMode=\"formMode\")\n\nwhen it should be:\nChildComponent(:displayMode=\"'formMode'\")\n\nnote the single quotes to indicate text instead of calling a local var inside the component.\n", "If you're using the Vue3 <script setup> style, make sure you've actually specified setup in the opening script tag:\n<script setup>\n\nI had lapsed into old habits and only created a block with <script>, but it took a while to notice it.\nhttps://v3.vuejs.org/api/sfc-script-setup.html\n", "It seems there are many scenarios that can trigger this error. Here's another one which I just resolved.\nI had the variable actionRequiredCount declared in the data section, but I failed to capitalize the C in Count when passing the variable as a params to a component.\nHere the variable is correct:\ndata: () => {\n return{\n actionRequiredCount: ''\n }\n}\n\nIn my template it was incorrect (notd the no caps c in \"count\"):\n <MyCustomModule :actionRequiredCount=\"actionRequiredcount\"/>\n\nHope this helps someone.\n", "Most people do have an error here because of:\n\na typo or something that they forgot to declare/use\nthe opposite, did it in several places\n\nTo avoid the typo issues, I recommend always using Vue VSCode Snippets so that you don't write anything by hand by rather use vbase, vdata, vmethod and get those parts generated for you.\nHere are the ones for Vue3.\nYou can of course also create your own snippets by doing the following.\nAlso make sure that you're properly writing all the correct names as shown here, here is a list:\n\ndata\nprops\ncomputed\nmethods\nwatch\nemits\nexpose\n\n\nAs for the second part, I usually recommend either searching the given keyword in your codebase. So like cmd + f + changeSetting in OP's case to see if it's missing a declaration somewhere in data, methods or alike.\nOr even better, use an ESlint configuration so that you will be warned in case you have any kind of issues in your codebase.\nHere is how to achieve such setup with a Nuxt project + ESlint + Prettier for the most efficient way to prevent bad practices while still getting a fast formatting!\n", "One other common scenario is:\n\nYou have a component (child) extending another component (parent)\nYou have a property or a method xyz defined under methods or computed on the parent component.\nYour are trying to use parent's xyz, but your child component defines its own methods or computed\n\nSample code with the problem\n// PARENT COMPONENT\nexport default {\n computed() {\n abc() {},\n xyz() {} // <= needs to be used in child component\n },\n ...\n}\n\n// CHILD COMPONENT\nexport default {\n extends: myParentComponent,\n computed() {\n childProprty1() {},\n childProprty2() {}\n }\n}\n\n\nThe solution\nIn this case you will need to redefine your xyz computed property under computed\nSolution 1:\nRedefine xyz and copy the code from the parent component\n// CHILD COMPONENT\nexport default {\n extends: myParentComponent,\n computed() {\n xyz() {\n // do something cool!\n },\n childProprty1() {},\n childProprty2() {}\n }\n}\n\nSolution 2\nRedefine xyz property reusing parent component code (no code redundancy)\n// CHILD COMPONENT\nexport default {\n extends: myParentComponent,\n computed() {\n xyz() {\n return this.$parent.$options.computed.xyz\n },\n childProprty1() {},\n childProprty2() {}\n }\n}\n\n", "For me it happened because I wrote method: instead of methods: (plural). It's a silly mistake but it can happen :)\n" ]
[ 137, 49, 33, 8, 8, 7, 4, 4, 4, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "javascript", "vue.js", "vue_component", "vuejs2" ]
stackoverflow_0042908525_javascript_vue.js_vue_component_vuejs2.txt
Q: Query/Script to delete an order in SAP Hybris (backend) To free-up storage in the database and increase the performance, we need to delete the previously placed orders in SAP Hybris Commerce. The orders should be deleted for a particular time frame such that only the orders older than X days should be deleted. Can anyone help me with impex/script for deleting the previously placed orders? Impex for selecting all orders : SELECT * from {orders} A: These operations will create huge system load. Hybris has own functionality for these: Data Retention Framework You will also need to add your own select questions. You wrote that older than X days. When this X days counter start: order creation/update, delivery, return, payment, etc?
Query/Script to delete an order in SAP Hybris (backend)
To free-up storage in the database and increase the performance, we need to delete the previously placed orders in SAP Hybris Commerce. The orders should be deleted for a particular time frame such that only the orders older than X days should be deleted. Can anyone help me with impex/script for deleting the previously placed orders? Impex for selecting all orders : SELECT * from {orders}
[ "These operations will create huge system load.\nHybris has own functionality for these: Data Retention Framework\nYou will also need to add your own select questions. You wrote that older than X days. When this X days counter start: order creation/update, delivery, return, payment, etc?\n" ]
[ 0 ]
[]
[]
[ "impex", "sap", "sap_commerce_cloud", "sql" ]
stackoverflow_0074670060_impex_sap_sap_commerce_cloud_sql.txt
Q: Questions regarding sharedPreferences (Kotlin) I am experimenting around with Kotlin's sharedPreferences, however I cannot seem to get the updated value to stick. val sharedPreferences = getSharedPreferences("Files", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putInt("numbers",1).apply() val textview = findViewById<TextView>(R.id.textview) textview.text = sharedPreferences.getInt("numbers",0).toString() val button = findViewById<Button>(R.id.button) button.setOnClickListener { editor.putInt("numbers",2).apply() textview.text = sharedPreferences.getInt("numbers",0).toString() } In the code above I set the initial value of the sharedPreference to 1, upon clicking the button the value will be updated to 2 and displayed.That works fine however when closing the app and reopening it, the value reverts to 1. Is there a way to permanatly keep the updated value? A: You are setting it to that value every time you open the activity, since onCreate() is called every time it opens. You should check if the value is already set, and if it is, skip that line of code. if ("numbers" !in sharedPreferences) { val editor = sharedPreferences.edit() editor.putInt("numbers",1).apply() } By the way, there is an extension function for editing without having to call apply and editor. repeatedly: if ("numbers" !in sharedPreferences) { sharedPreferences.edit { putInt("numbers",1) } }
Questions regarding sharedPreferences (Kotlin)
I am experimenting around with Kotlin's sharedPreferences, however I cannot seem to get the updated value to stick. val sharedPreferences = getSharedPreferences("Files", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putInt("numbers",1).apply() val textview = findViewById<TextView>(R.id.textview) textview.text = sharedPreferences.getInt("numbers",0).toString() val button = findViewById<Button>(R.id.button) button.setOnClickListener { editor.putInt("numbers",2).apply() textview.text = sharedPreferences.getInt("numbers",0).toString() } In the code above I set the initial value of the sharedPreference to 1, upon clicking the button the value will be updated to 2 and displayed.That works fine however when closing the app and reopening it, the value reverts to 1. Is there a way to permanatly keep the updated value?
[ "You are setting it to that value every time you open the activity, since onCreate() is called every time it opens. You should check if the value is already set, and if it is, skip that line of code.\nif (\"numbers\" !in sharedPreferences) {\n val editor = sharedPreferences.edit()\n editor.putInt(\"numbers\",1).apply()\n}\n\nBy the way, there is an extension function for editing without having to call apply and editor. repeatedly:\nif (\"numbers\" !in sharedPreferences) {\n sharedPreferences.edit {\n putInt(\"numbers\",1)\n }\n}\n\n" ]
[ 1 ]
[]
[]
[ "android", "kotlin" ]
stackoverflow_0074680307_android_kotlin.txt
Q: Is there a way to switch Bash or zsh from Emacs mode to vi mode with a keystroke? I'd like to be able to switch temporarily from emacs mode to vi mode, since vi mode is sometimes better, but I'm usually half-way through typing something before I realize I want to use vi mode. I don't want to switch permanently to vi mode, because I normally prefer emacs mode on the command line, mostly because it's what I'm used to, and over the years many of the keystrokes have become second nature. (As an editor I generally use emacs in viper mode, so that I can use both vi and emacs keystrokes, since I found myself accidentally using them in vi all the time, and screwing things up, and because in some cases I find vi keystrokes more memorable and handy, and in other cases emacs.) A: You can create a toggle since the key bindings are separate between vi mode and emacs mode. $ set -o emacs $ bind '"\ee": vi-editing-mode' $ set -o vi $ bind '"\ee": emacs-editing-mode' Now Alt-e (or Esc e) will toggle between modes. Add this somewhere in your definition for PS1 so you have an indicator in your prompt of which mode you're in. It won't show the change immediately when you toggle modes, but it will update when a new prompt is issued. $(set -o | grep emacs.*on >/dev/null 2>&1 && echo E || echo V) A: Aha! I looked at the readline source, and found out that you can do this: "\M-v": vi-editing-mode "\M-e": emacs-editing-mode There doesn't appear to be a toggle, but that's probably good enough! For posterity's sake, here's my original answer, which could be useful for people trying to do things for which there is no readline function. Here's a way you could set it up, clearing the current command line in the process. Not what you want, I know, but maybe it'll help someone else who finds this question. In ~/.inputrc: "\M-v": "\C-k\C-uset -o vi\C-j" # alt (meta)-v: set vi mode "\M-e": "\C-k\C-uset -o vi\C-j" # alt (meta)-e: set emacs mode or to toggle...this should work: "\M-t": "\C-k\C-u[[ \"$SHELLOPTS\" =~ '\\bemacs\\b' ]] && set -o vi || set -o emacs\C-j" These are essentially aliases, taken one step farther to map to keys in readline so that you don't have to type an alias name and hit enter. A: The following .inputrc lines allow Meta / Alt+E to switch between emacs and vi-insert modes. Mooshing both j and k simultaneously will take you to vi-command mode. Note: The only English word with "kj" is "blackjack", no words contain "jk") set keymap emacs "\ee": vi-editing-mode "jk": "\eejk" "kj": "\eejk" set keymap vi-insert "\ee": emacs-editing-mode "jk": vi-movement-mode "kj": vi-movement-mode set keymap vi-command "\ee": emacs-editing-mode Note: If you add a binding under keymap emacs to vi-movement-mode to try to switch straight to vi-command mode, the prompt doesn't update if you have show-mode-in-prompt on, hence the above work-around is needed. A: I finally found out how to toggle vi and emacs mode with a singel key e.g. [alt]+[i] in zsh: # in the .zshrc # toggle vi and emacs mode vi-mode() { set -o vi; } emacs-mode() { set -o emacs; } zle -N vi-mode zle -N emacs-mode bindkey '\ei' vi-mode # switch to vi "insert" mode bindkey -M viins 'jk' vi-cmd-mode # (optionally) exit to vi "cmd" mode bindkey -M viins '\ei' emacs-mode # switch to emacs mode
Is there a way to switch Bash or zsh from Emacs mode to vi mode with a keystroke?
I'd like to be able to switch temporarily from emacs mode to vi mode, since vi mode is sometimes better, but I'm usually half-way through typing something before I realize I want to use vi mode. I don't want to switch permanently to vi mode, because I normally prefer emacs mode on the command line, mostly because it's what I'm used to, and over the years many of the keystrokes have become second nature. (As an editor I generally use emacs in viper mode, so that I can use both vi and emacs keystrokes, since I found myself accidentally using them in vi all the time, and screwing things up, and because in some cases I find vi keystrokes more memorable and handy, and in other cases emacs.)
[ "You can create a toggle since the key bindings are separate between vi mode and emacs mode.\n$ set -o emacs\n$ bind '\"\\ee\": vi-editing-mode'\n$ set -o vi\n$ bind '\"\\ee\": emacs-editing-mode'\n\nNow Alt-e (or Esc e) will toggle between modes.\nAdd this somewhere in your definition for PS1 so you have an indicator in your prompt of which mode you're in. It won't show the change immediately when you toggle modes, but it will update when a new prompt is issued.\n$(set -o | grep emacs.*on >/dev/null 2>&1 && echo E || echo V)\n\n", "Aha! I looked at the readline source, and found out that you can do this:\n \"\\M-v\": vi-editing-mode\n \"\\M-e\": emacs-editing-mode\n\nThere doesn't appear to be a toggle, but that's probably good enough!\nFor posterity's sake, here's my original answer, which could be useful for people trying to do things for which there is no readline function.\nHere's a way you could set it up, clearing the current command line in the process. Not what you want, I know, but maybe it'll help someone else who finds this question. In ~/.inputrc:\n\"\\M-v\": \"\\C-k\\C-uset -o vi\\C-j\" # alt (meta)-v: set vi mode\n\"\\M-e\": \"\\C-k\\C-uset -o vi\\C-j\" # alt (meta)-e: set emacs mode\n\nor to toggle...this should work:\n\"\\M-t\": \"\\C-k\\C-u[[ \\\"$SHELLOPTS\\\" =~ '\\\\bemacs\\\\b' ]] && set -o vi || set -o emacs\\C-j\"\n\nThese are essentially aliases, taken one step farther to map to keys in readline so that you don't have to type an alias name and hit enter.\n", "The following .inputrc lines allow Meta / Alt+E to switch between emacs and vi-insert modes.\nMooshing both j and k simultaneously will take you to vi-command mode.\nNote: The only English word with \"kj\" is \"blackjack\", no words contain \"jk\")\nset keymap emacs\n\"\\ee\": vi-editing-mode\n\"jk\": \"\\eejk\"\n\"kj\": \"\\eejk\"\n\nset keymap vi-insert\n\"\\ee\": emacs-editing-mode\n\"jk\": vi-movement-mode\n\"kj\": vi-movement-mode\n\nset keymap vi-command\n\"\\ee\": emacs-editing-mode\n\nNote: If you add a binding under keymap emacs to vi-movement-mode to try to switch straight to vi-command mode, the prompt doesn't update if you have show-mode-in-prompt on, hence the above work-around is needed.\n", "I finally found out how to toggle vi and emacs mode with a singel key e.g. [alt]+[i] in zsh:\n# in the .zshrc\n# toggle vi and emacs mode\nvi-mode() { set -o vi; }\nemacs-mode() { set -o emacs; }\nzle -N vi-mode\nzle -N emacs-mode\nbindkey '\\ei' vi-mode # switch to vi \"insert\" mode\nbindkey -M viins 'jk' vi-cmd-mode # (optionally) exit to vi \"cmd\" mode\nbindkey -M viins '\\ei' emacs-mode # switch to emacs mode\n\n" ]
[ 14, 5, 3, 0 ]
[]
[]
[ "bash", "history", "zsh" ]
stackoverflow_0002640141_bash_history_zsh.txt
Q: Type error trying to pass an array of interfaces as a prop I am trying to pass array of interfaces that are stored in a useState hook to a child functional component. Here is the hook. It only becomes populated after user interaction: const [districtData, setDistrictData] = useState<DistrictData[]>([]); Here is the interface which is imported into the parent tsx file. export interface DistrictData { lng: number, lat: number, id: string } Here is where I pass it to the child component <ListOfSchools/> THIS is the line where TS is giving the error. <ListOfSchools districtData={districtData} /> This is what the child component ListOfSchools.tsx looks like: import { DistrictData } from "@utils/nces"; interface Props { propWhichIsArray: DistrictData[]; } export const ListOfSchools: React.FC<Props> = ({ propWhichIsArray }) => { return <div></div>; }; Here is the error I am getting: Type '{ districtData: DistrictData[]; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'. Property 'districtData' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'. I believe the goal is the set the prop to be of the type that the child component expects. I have also tried below, along with many other attempts from stackoverflow articles: export const ListOfSchools: React.FC<DistrictData[]> = ({ props: DistricData[] }) => { return <div></div>; }; Thank you very much for any help here. A: Based on the code you've provided, it looks like you're trying to pass the districtData prop to the ListOfSchools component, but you're trying to access it as propWhichIsArray in the child component. To fix the error you're getting, you'll need to make sure that the prop name you're using in the child component matches the name of the prop you're passing from the parent. In this case, you can either change the name of the prop in the parent component when you pass it, like this: <ListOfSchools propWhichIsArray={districtData} /> Or, you can change the name of the prop in the child component to match the name that it's being passed with and update the type accordingly, like this: import { DistrictData } from "@utils/nces"; interface Props { districtData: DistrictData[]; } export const ListOfSchools: React.FC<Props> = ({ districtData }) => { return <div></div>; };
Type error trying to pass an array of interfaces as a prop
I am trying to pass array of interfaces that are stored in a useState hook to a child functional component. Here is the hook. It only becomes populated after user interaction: const [districtData, setDistrictData] = useState<DistrictData[]>([]); Here is the interface which is imported into the parent tsx file. export interface DistrictData { lng: number, lat: number, id: string } Here is where I pass it to the child component <ListOfSchools/> THIS is the line where TS is giving the error. <ListOfSchools districtData={districtData} /> This is what the child component ListOfSchools.tsx looks like: import { DistrictData } from "@utils/nces"; interface Props { propWhichIsArray: DistrictData[]; } export const ListOfSchools: React.FC<Props> = ({ propWhichIsArray }) => { return <div></div>; }; Here is the error I am getting: Type '{ districtData: DistrictData[]; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'. Property 'districtData' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'. I believe the goal is the set the prop to be of the type that the child component expects. I have also tried below, along with many other attempts from stackoverflow articles: export const ListOfSchools: React.FC<DistrictData[]> = ({ props: DistricData[] }) => { return <div></div>; }; Thank you very much for any help here.
[ "Based on the code you've provided, it looks like you're trying to pass the districtData prop to the ListOfSchools component, but you're trying to access it as propWhichIsArray in the child component.\nTo fix the error you're getting, you'll need to make sure that the prop name you're using in the child component matches the name of the prop you're passing from the parent. In this case, you can either change the name of the prop in the parent component when you pass it, like this:\n<ListOfSchools propWhichIsArray={districtData} />\n\nOr, you can change the name of the prop in the child component to match the name that it's being passed with and update the type accordingly, like this:\nimport { DistrictData } from \"@utils/nces\";\n\ninterface Props {\n districtData: DistrictData[];\n}\n\nexport const ListOfSchools: React.FC<Props> = ({ districtData }) => {\n return <div></div>;\n};\n\n" ]
[ 1 ]
[]
[]
[ "interface", "reactjs", "typescript" ]
stackoverflow_0074680856_interface_reactjs_typescript.txt
Q: Posting Selected UITableView rows to a MySQL database table via UIButton This is how my storyboard looks like Basically I have two UITableViews which are connected to tables on my MySQL database. I want it to send the selected rows(or if possible the rows with the accessory type .checkmark) as a POST to a table in my database by pressing a button. I have the PHP code ready and I am able to make POST requests and update a table in MySQL, that's not the problem here. I want the selected rows in my UITableView to be sent to that specific PHP code when the button is pressed. @IBAction func selected(_ sender: UIButton) { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell let currentItem = currentCell.textLabel!.text let alertController = UIAlertController(title: "", message: "You Selected " + currentItem! , preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Close", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) let url = NSURL(string: "url") // locahost MAMP - change to point to your database server var request = URLRequest(url: url! as URL) request.httpMethod = "POST" var dataString = "secretWord=---" // starting POST string with a secretWord // the POST string has entries separated by & dataString = dataString + "&currentitem=\(currentItem!)" // add items as name and value // convert the post string to utf8 format let dataD = dataString.data(using: .utf8) // convert to utf8 string do { // the upload task, uploadJob, is defined here let uploadJob = URLSession.shared.uploadTask(with: request, from: dataD) { data, response, error in if error != nil { } } uploadJob.resume() } } } I have tried to do this, which I guess is just a mess of a code since I'm still a beginner but yeah i hope this kind of sends a general message of my problem to you I know you can use a IBAction to call a function that could send it to the php code but I'm just not sure on how to exactly code it. I tried to use if statements with the tableView and the didSelectRowAt function inside of an IBAction but nothing seemed to work. I have not found any sources online about it when I tried to search for it. A: If the question is how to permit the selection of multiple rows in a table, we use allowsMultipleSelection, which you can set either programmatically or in Interface Builder. Then in didSelectRowAt (and didDeselectRowAt), rather than just using the indexPath that was passed to the delegate method, instead use indexPathsForSelectedRows. And if you don't want to send the updates to the server every time a row is selected and deselected, but instead in an @IBAction method associated with a button, then remove the network request from didSelectRowAt (and didDeselectRowAt), and instead put it in your button’s @IBAction, again using indexPathsForSelectedRows. Note, rather than currentitem=..., you will likely want to send it as an array, e.g. currentitems[0]=13 and currentitems[1]=42, etc., separated with &.
Posting Selected UITableView rows to a MySQL database table via UIButton
This is how my storyboard looks like Basically I have two UITableViews which are connected to tables on my MySQL database. I want it to send the selected rows(or if possible the rows with the accessory type .checkmark) as a POST to a table in my database by pressing a button. I have the PHP code ready and I am able to make POST requests and update a table in MySQL, that's not the problem here. I want the selected rows in my UITableView to be sent to that specific PHP code when the button is pressed. @IBAction func selected(_ sender: UIButton) { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell let currentItem = currentCell.textLabel!.text let alertController = UIAlertController(title: "", message: "You Selected " + currentItem! , preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Close", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) let url = NSURL(string: "url") // locahost MAMP - change to point to your database server var request = URLRequest(url: url! as URL) request.httpMethod = "POST" var dataString = "secretWord=---" // starting POST string with a secretWord // the POST string has entries separated by & dataString = dataString + "&currentitem=\(currentItem!)" // add items as name and value // convert the post string to utf8 format let dataD = dataString.data(using: .utf8) // convert to utf8 string do { // the upload task, uploadJob, is defined here let uploadJob = URLSession.shared.uploadTask(with: request, from: dataD) { data, response, error in if error != nil { } } uploadJob.resume() } } } I have tried to do this, which I guess is just a mess of a code since I'm still a beginner but yeah i hope this kind of sends a general message of my problem to you I know you can use a IBAction to call a function that could send it to the php code but I'm just not sure on how to exactly code it. I tried to use if statements with the tableView and the didSelectRowAt function inside of an IBAction but nothing seemed to work. I have not found any sources online about it when I tried to search for it.
[ "If the question is how to permit the selection of multiple rows in a table, we use allowsMultipleSelection, which you can set either programmatically or in Interface Builder.\nThen in didSelectRowAt (and didDeselectRowAt), rather than just using the indexPath that was passed to the delegate method, instead use indexPathsForSelectedRows.\nAnd if you don't want to send the updates to the server every time a row is selected and deselected, but instead in an @IBAction method associated with a button, then remove the network request from didSelectRowAt (and didDeselectRowAt), and instead put it in your button’s @IBAction, again using indexPathsForSelectedRows.\n\nNote, rather than currentitem=..., you will likely want to send it as an array, e.g. currentitems[0]=13 and currentitems[1]=42, etc., separated with &.\n" ]
[ 0 ]
[]
[]
[ "mysql", "php", "storyboard", "swift", "uitableview" ]
stackoverflow_0074680260_mysql_php_storyboard_swift_uitableview.txt
Q: selenium-python cannot locate element I need to enter credentials on garmin connect website. I use python 3.10 and chrome=108.0.5359.94. The username element code: <input class="login_email" name="username" id="username" value="" type="email" spellcheck="false" autocorrect="off" autocapitalize="off" aria-required="true"> And I tried the following: browser.maximize_window() browser.implicitly_wait(3) browser.find_element(By.ID, "username") browser.find_element(By.CLASS_NAME, 'input#username.login_email') browser.find_element(By.CLASS_NAME, 'login_email') browser.find_element(By.XPATH, '/html/body/div/div/div[1]/form/div[2]/input') browser.find_element(By.XPATH, '//*[@id="username"]') I get the following error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: I searched some info and some say it could be due to shadow dom. But I think it's not my case as I cannot see shadow-smth in html structure. Any ideas? A: The login form is inside an iframe. So, to access elements inside it you first need to switch into that iframe. The following code works: from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC options = Options() options.add_argument("start-maximized") webdriver_service = Service('C:\webdrivers\chromedriver.exe') driver = webdriver.Chrome(service=webdriver_service, options=options) wait = WebDriverWait(driver, 20) url = "https://connect.garmin.com/signin/" driver.get(url) wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe"))) wait.until(EC.element_to_be_clickable((By.ID, "username"))).send_keys("my_name") wait.until(EC.element_to_be_clickable((By.ID, "password"))).send_keys("my_password") The result is When finished working inside the iframe don't forget to switch to the default content with driver.switch_to.default_content()
selenium-python cannot locate element
I need to enter credentials on garmin connect website. I use python 3.10 and chrome=108.0.5359.94. The username element code: <input class="login_email" name="username" id="username" value="" type="email" spellcheck="false" autocorrect="off" autocapitalize="off" aria-required="true"> And I tried the following: browser.maximize_window() browser.implicitly_wait(3) browser.find_element(By.ID, "username") browser.find_element(By.CLASS_NAME, 'input#username.login_email') browser.find_element(By.CLASS_NAME, 'login_email') browser.find_element(By.XPATH, '/html/body/div/div/div[1]/form/div[2]/input') browser.find_element(By.XPATH, '//*[@id="username"]') I get the following error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: I searched some info and some say it could be due to shadow dom. But I think it's not my case as I cannot see shadow-smth in html structure. Any ideas?
[ "The login form is inside an iframe. So, to access elements inside it you first need to switch into that iframe.\nThe following code works:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\noptions = Options()\noptions.add_argument(\"start-maximized\")\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(service=webdriver_service, options=options)\nwait = WebDriverWait(driver, 20)\n\nurl = \"https://connect.garmin.com/signin/\"\n\ndriver.get(url)\n\nwait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, \"iframe\")))\n\nwait.until(EC.element_to_be_clickable((By.ID, \"username\"))).send_keys(\"my_name\")\nwait.until(EC.element_to_be_clickable((By.ID, \"password\"))).send_keys(\"my_password\")\n\nThe result is\n\nWhen finished working inside the iframe don't forget to switch to the default content with\ndriver.switch_to.default_content()\n\n" ]
[ 0 ]
[]
[]
[ "iframe", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074680627_iframe_python_selenium_selenium_webdriver_xpath.txt
Q: python for each run async function without await and parallel I have 10 links in my CSV which I'm trying to run all at the same time in a loop from getTasks function. However, the way it's working now, it send a request to link 1, waits for it to complete, then link 2, etc, etc. I want the 10 links that I have to run all whenever startTask is called, leading to 10 requests a second. Anyone know how to code that using the code below? Thanks in advance. import requests from bs4 import BeautifulSoup import asyncio def getTasks(tasks): for task in tasks: asyncio.run(startTask(task)) async def startTask(task): success = await getProduct(task) if success is None: return startTask(task) success = await addToCart(task) if success is None: return startTask(task) ... ... ... getTasks(tasks) A: import asyncio async def getTasks(tasks): # Use asyncio.gather to run multiple tasks concurrently # This will start all the tasks at the same time await asyncio.gather(*[startTask(task) for task in tasks]) async def startTask(task): # Your existing code goes here success = await getProduct(task) if success is None: return startTask(task) success = await addToCart(task) if success is None: return startTask(task) ... ... ... # Use asyncio.run to start the main task asyncio.run(getTasks(tasks))
python for each run async function without await and parallel
I have 10 links in my CSV which I'm trying to run all at the same time in a loop from getTasks function. However, the way it's working now, it send a request to link 1, waits for it to complete, then link 2, etc, etc. I want the 10 links that I have to run all whenever startTask is called, leading to 10 requests a second. Anyone know how to code that using the code below? Thanks in advance. import requests from bs4 import BeautifulSoup import asyncio def getTasks(tasks): for task in tasks: asyncio.run(startTask(task)) async def startTask(task): success = await getProduct(task) if success is None: return startTask(task) success = await addToCart(task) if success is None: return startTask(task) ... ... ... getTasks(tasks)
[ "import asyncio\n\nasync def getTasks(tasks):\n # Use asyncio.gather to run multiple tasks concurrently\n # This will start all the tasks at the same time\n await asyncio.gather(*[startTask(task) for task in tasks])\n\nasync def startTask(task):\n # Your existing code goes here\n success = await getProduct(task)\n if success is None:\n return startTask(task)\n\n success = await addToCart(task)\n if success is None:\n return startTask(task)\n\n ...\n ...\n ...\n\n# Use asyncio.run to start the main task\nasyncio.run(getTasks(tasks))\n\n" ]
[ 0 ]
[]
[]
[ "async_await", "asynchronous", "parallel_processing", "python", "request" ]
stackoverflow_0074661156_async_await_asynchronous_parallel_processing_python_request.txt
Q: How to map JSON with array object to Model in SwiftUI? `Missing argument for parameter 'from' in call` I am new to SwiftUI and have been stuck for days in trying to map my backend API's JSON object into the SwitchUI Model (Which I think is the right way to approach this type of problem?). I am getting error while trying to initalize the variable. I am trying to use Alamofire to get the response from my API in JSON and map that to a Published variable so I can print the list of businesses as the result. The following is what I have and the I'm getting the "Missing argument for parameter 'from' in call" error on the line: @Published var result: Result = Result() If I make the "[Businesses] and region" in my model as Optional, then I can't see them in the view. What is wrong here? Thanks very much View class SearchFormModel: ObservableObject { @Published var result: Result = Result() AF.request(backendApiURL, parameters: parameters).responseDecodable(of: Result.self) { response in debugPrint("Response:\(response)") switch response.result { case let .success(value): self.result = value print(value) case let .failure(error): print(error) } Model import Foundation import SwiftyJSON struct Result: Codable { var businesses : [Businesses] var region : Region } struct Businesses: Codable { var id : String = "" var alias : String? var name : String? var image_url : URL? var is_closed : Bool? var url : URL? var review_count : Int? var categories : [Categories]? var rating : Double? var coordinates : Coordinates? var transactions : [String]? var price : String? var location : Location? var phone : String? var display_phone : String? var distance : Double? } struct Categories: Codable { var alias : String = "" var title : String = "" } struct Coordinates: Codable { var latitude : Double = 0.0 var longitude : Double = 0.0 } struct Location: Codable { var address1 : String? var address2 : String? var address3 : String? var city : String? var zip_code : String? var country : String? var state : String? var display_address : [String]? } struct Region: Codable { var center : Center } struct Center : Codable { var longitude : Double = 0.0 var latitude : Double = 0.0 } Sample JSON { "businesses": [ { "id": "aDa5FQZdCghy3XwK_h93Fw", "alias": "worlds-best-pizza-hacienda-heights", "name": "World's Best Pizza", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/ZPKyEBB5As3dVberckNyxg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/worlds-best-pizza-hacienda-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 409, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9801206981514, "longitude": -117.974323744633 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "3142 Colima Rd", "address2": "", "address3": "", "city": "Hacienda Heights", "zip_code": "91745", "country": "US", "state": "CA", "display_address": [ "3142 Colima Rd", "Hacienda Heights, CA 91745" ] }, "phone": "+16269684794", "display_phone": "(626) 968-4794", "distance": 2271.295381028884 }, { "id": "ovq2Sfpw7cQZbSMIqs07vg", "alias": "hacienda-heights-pizza-company-hacienda-heights", "name": "Hacienda Heights Pizza Company", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/codEYU-DR_GdRd7dsNsWyA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/hacienda-heights-pizza-company-hacienda-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 437, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 3.5, "coordinates": { "latitude": 34.015013, "longitude": -117.973866 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "15239 Gale Ave", "address2": "", "address3": "", "city": "Hacienda Heights", "zip_code": "91745", "country": "US", "state": "CA", "display_address": [ "15239 Gale Ave", "Hacienda Heights, CA 91745" ] }, "phone": "+16268552590", "display_phone": "(626) 855-2590", "distance": 1980.1106887021883 }, { "id": "I92UQKaJKq9iaa4HTz2tXg", "alias": "scardinos-pizza-to-go-la-puente", "name": "Scardino's Pizza To Go", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/wE2Jm3DK-4bO_11xsXxGEQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/scardinos-pizza-to-go-la-puente?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 339, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "italian", "title": "Italian" } ], "rating": 4.5, "coordinates": { "latitude": 34.0496506030785, "longitude": -117.946955922661 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "1627 N Hacienda Blvd", "address2": "", "address3": "", "city": "La Puente", "zip_code": "91744", "country": "US", "state": "CA", "display_address": [ "1627 N Hacienda Blvd", "La Puente, CA 91744" ] }, "phone": "+16269181507", "display_phone": "(626) 918-1507", "distance": 6552.790234543938 }, { "id": "XzW26Or2ITIbkoTh2XME4w", "alias": "fuoco-pizzeria-napoletana-fullerton", "name": "Fuoco Pizzeria Napoletana", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/wE95ltg-16GPwYJf4Aof0w/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/fuoco-pizzeria-napoletana-fullerton?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 1783, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "italian", "title": "Italian" }, { "alias": "salad", "title": "Salad" } ], "rating": 4.5, "coordinates": { "latitude": 33.87060085641833, "longitude": -117.92457732489875 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "101 N Harbor Blvd", "address2": "", "address3": "", "city": "Fullerton", "zip_code": "92832", "country": "US", "state": "CA", "display_address": [ "101 N Harbor Blvd", "Fullerton, CA 92832" ] }, "phone": "+17146260727", "display_phone": "(714) 626-0727", "distance": 15285.200290883491 }, { "id": "hTf8c43zQ7TFq6PHQAI2bw", "alias": "love-letter-pizza-and-chicken-rowland-heights", "name": "Love Letter Pizza & Chicken", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/zPQEFl8tgsXomodGvgvPMQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/love-letter-pizza-and-chicken-rowland-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 990, "categories": [ { "alias": "korean", "title": "Korean" }, { "alias": "pizza", "title": "Pizza" }, { "alias": "chicken_wings", "title": "Chicken Wings" } ], "rating": 4, "coordinates": { "latitude": 33.989243, "longitude": -117.904673 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "18333B Colima Rd", "address2": "", "address3": "", "city": "Rowland Heights", "zip_code": "91748", "country": "US", "state": "CA", "display_address": [ "18333B Colima Rd", "Rowland Heights, CA 91748" ] }, "phone": "+16268391235", "display_phone": "(626) 839-1235", "distance": 7344.37662932068 }, { "id": "-5GSm4vuDDdtMaEPjPKwcQ", "alias": "vinnys-italian-restaurant-la-habra-2", "name": "Vinny's Italian Restaurant", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/x7mpbYWdKfoY465wY41wsQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/vinnys-italian-restaurant-la-habra-2?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 1090, "categories": [ { "alias": "italian", "title": "Italian" }, { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.92514, "longitude": -117.92276 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "2101 E Lambert Rd", "address2": "", "address3": "", "city": "La Habra", "zip_code": "90631", "country": "US", "state": "CA", "display_address": [ "2101 E Lambert Rd", "La Habra, CA 90631" ] }, "phone": "+15626943400", "display_phone": "(562) 694-3400", "distance": 9950.263973452404 }, { "id": "_FuGSE3AYx9nOTkODPut1g", "alias": "la-crosta-wood-fired-pizza-whittier", "name": "La Crosta Wood Fired Pizza", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/vdBfsfjDqDnxap0BwSLtdQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/la-crosta-wood-fired-pizza-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 59, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9787781, "longitude": -118.0370427 }, "transactions": [ "pickup", "delivery" ], "location": { "address1": "13002 Philadelphia St", "address2": "", "address3": null, "city": "Whittier", "zip_code": "90601", "country": "US", "state": "CA", "display_address": [ "13002 Philadelphia St", "Whittier, CA 90601" ] }, "phone": "+15623247577", "display_phone": "(562) 324-7577", "distance": 5430.611951758044 }, { "id": "5bjEj57xtVg59fsIjWGCzQ", "alias": "blackjack-pizzeria-la-habra", "name": "Blackjack Pizzeria", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/5uQoPZ5RDa_uFS8tnioUSg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/blackjack-pizzeria-la-habra?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 429, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9398719780954, "longitude": -117.973393835127 }, "transactions": [ "pickup", "delivery" ], "price": "$", "location": { "address1": "2429 W Whittier Blvd", "address2": "", "address3": "", "city": "La Habra", "zip_code": "90631", "country": "US", "state": "CA", "display_address": [ "2429 W Whittier Blvd", "La Habra, CA 90631" ] }, "phone": "+15626944111", "display_phone": "(562) 694-4111", "distance": 6649.561538223691 }, { "id": "lCn-WpZORhjjuVeXiNt5hA", "alias": "pizzamania-whittier", "name": "Pizzamania", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/oikKRCcC4Kncp0BBlruVYg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizzamania-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 1027, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 33.9378271, "longitude": -118.0427549 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "13547 Telegraph Rd", "address2": "", "address3": "", "city": "Whittier", "zip_code": "90605", "country": "US", "state": "CA", "display_address": [ "13547 Telegraph Rd", "Whittier, CA 90605" ] }, "phone": "+15629448803", "display_phone": "(562) 944-8803", "distance": 8691.538482559992 }, { "id": "4qcbUWK6PtT_EhE1CL00OQ", "alias": "ravello-osteria-monterey-park", "name": "Ravello Osteria", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/SL-IEVhRUfuFcz1aZzYEQg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/ravello-osteria-monterey-park?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 578, "categories": [ { "alias": "italian", "title": "Italian" }, { "alias": "pastashops", "title": "Pasta Shops" }, { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 34.036084111352146, "longitude": -118.1307262 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "2315 S Garfield Ave", "address2": "", "address3": "", "city": "Monterey Park", "zip_code": "91754", "country": "US", "state": "CA", "display_address": [ "2315 S Garfield Ave", "Monterey Park, CA 91754" ] }, "phone": "+13237227600", "display_phone": "(323) 722-7600", "distance": 14181.449997149568 }, { "id": "a9Oo2cUQXv4V7sNzlWiMNQ", "alias": "pizza-21-whittier", "name": "Pizza 21", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/r37IuAf-RTO9YlkTTtHKKQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizza-21-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 220, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 5, "coordinates": { "latitude": 33.9718658905689, "longitude": -118.07371439367 }, "transactions": [ "pickup", "delivery" ], "price": "$", "location": { "address1": "8017 Norwalk Blvd", "address2": "", "address3": null, "city": "Whittier", "zip_code": "90606", "country": "US", "state": "CA", "display_address": [ "8017 Norwalk Blvd", "Whittier, CA 90606" ] }, "phone": "+15628013689", "display_phone": "(562) 801-3689", "distance": 8853.647033272864 }, { "id": "LKPl3iThbC2CdbnPb53XRQ", "alias": "the-curry-pizza-company-walnut-walnut-2", "name": "The Curry Pizza Company - Walnut", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/WaC6AFze5NVW9OrL_uGJ7g/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/the-curry-pizza-company-walnut-walnut-2?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 318, "categories": [ { "alias": "indpak", "title": "Indian" }, { "alias": "pizza", "title": "Pizza" }, { "alias": "chicken_wings", "title": "Chicken Wings" } ], "rating": 4.5, "coordinates": { "latitude": 34.0111996, "longitude": -117.859211 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "376 S Lemon Ave", "address2": "", "address3": null, "city": "Walnut", "zip_code": "91789", "country": "US", "state": "CA", "display_address": [ "376 S Lemon Ave", "Walnut, CA 91789" ] }, "phone": "+19099785065", "display_phone": "(909) 978-5065", "distance": 11533.359141110845 }, { "id": "Wcg_6rnWc6tpktt33ous7Q", "alias": "baby-bros-pizza-and-wings-south-el-monte", "name": "Baby Bros Pizza & Wings", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/MZ115Qxa5HTZvCGLWxYw5w/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/baby-bros-pizza-and-wings-south-el-monte?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 292, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "chicken_wings", "title": "Chicken Wings" }, { "alias": "beerbar", "title": "Beer Bar" } ], "rating": 4, "coordinates": { "latitude": 34.05211, "longitude": -118.05398 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "9847 Rush St", "address2": null, "address3": "", "city": "South El Monte", "zip_code": "91733", "country": "US", "state": "CA", "display_address": [ "9847 Rush St", "South El Monte, CA 91733" ] }, "phone": "+16264482316", "display_phone": "(626) 448-2316", "distance": 8772.804450272562 }, { "id": "2UJcwkqvDAKPX8ZeNbQeFQ", "alias": "pizzarev-rowland-heights", "name": "PizzaRev", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/PiDjlQH6Nw7u4q9TLhaGQg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizzarev-rowland-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 397, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9901605, "longitude": -117.9246713 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "17490 Colima Rd", "address2": "Ste D", "address3": null, "city": "Rowland Heights", "zip_code": "91748", "country": "US", "state": "CA", "display_address": [ "17490 Colima Rd", "Ste D", "Rowland Heights, CA 91748" ] }, "phone": "+16268540006", "display_phone": "(626) 854-0006", "distance": 5511.128701794727 }, { "id": "SiyyceCOoIuEqCfZEwN3Hg", "alias": "pie-trap-pizza-covina", "name": "Pie Trap Pizza", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/o8_i3RxRXkFDDRu3p9l08Q/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pie-trap-pizza-covina?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 20, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 34.105086485939346, "longitude": -117.87669418232004 }, "transactions": [ ], "location": { "address1": "720 E Arrow Hwy", "address2": "Ste A", "address3": "", "city": "Covina", "zip_code": "91702", "country": "US", "state": "CA", "display_address": [ "720 E Arrow Hwy", "Ste A", "Covina, CA 91702" ] }, "phone": "+16265410051", "display_phone": "(626) 541-0051", "distance": 15352.567810724982 }, { "id": "efqeidrFoFzqVH1TEmJHIg", "alias": "new-york-pizzeria-walnut", "name": "New York Pizzeria", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/36tqlCLWgOLgIaYasL19Qw/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/new-york-pizzeria-walnut?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 246, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "beer_and_wine", "title": "Beer, Wine & Spirits" }, { "alias": "sandwiches", "title": "Sandwiches" } ], "rating": 4, "coordinates": { "latitude": 34.0190473, "longitude": -117.8650573 }, "transactions": [ "delivery" ], "price": "$", "location": { "address1": "364 N Lemon Ave", "address2": "", "address3": "", "city": "Walnut", "zip_code": "91789", "country": "US", "state": "CA", "display_address": [ "364 N Lemon Ave", "Walnut, CA 91789" ] }, "phone": "+19095945000", "display_phone": "(909) 594-5000", "distance": 11138.41781108791 }, { "id": "nG3lHSvq3m0fzFQTdHjUSw", "alias": "tonys-pizza-whittier", "name": "Tony's Pizza", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/lZ7c-viftcFik1Y06I8xJA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/tonys-pizza-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 518, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 33.9422540037959, "longitude": -117.995184817488 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "15624 Whittwood Ln", "address2": "", "address3": "", "city": "Whittier", "zip_code": "90603", "country": "US", "state": "CA", "display_address": [ "15624 Whittwood Ln", "Whittier, CA 90603" ] }, "phone": "+15629470500", "display_phone": "(562) 947-0500", "distance": 6411.01480512212 }, { "id": "DOB_k_gkyijSLgyt-_zodQ", "alias": "jo-peeps-ny-pizza-whittier-3", "name": "Jo Peeps Ny Pizza", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/vX-ghkTzaweOhKEIvq5wzw/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/jo-peeps-ny-pizza-whittier-3?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 193, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "salad", "title": "Salad" }, { "alias": "sandwiches", "title": "Sandwiches" } ], "rating": 4, "coordinates": { "latitude": 33.9535433, "longitude": -118.0161173 }, "transactions": [ "delivery" ], "price": "$", "location": { "address1": "14450 Whittier Blvd", "address2": "", "address3": "", "city": "Whittier", "zip_code": "90605", "country": "US", "state": "CA", "display_address": [ "14450 Whittier Blvd", "Whittier, CA 90605" ] }, "phone": "+15629459691", "display_phone": "(562) 945-9691", "distance": 5891.520785405544 }, { "id": "2z5o4QXHgDc6vQLqZYoI8w", "alias": "pizza-n-brews-whittier-3", "name": "Pizza-N-Brews", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/eowFStZQxkd0V4bPg5rigA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizza-n-brews-whittier-3?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 43, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "sandwiches", "title": "Sandwiches" }, { "alias": "beerbar", "title": "Beer Bar" } ], "rating": 4.5, "coordinates": { "latitude": 33.94714, "longitude": -118.00047 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "15309 Whittier Blvd", "address2": null, "address3": "", "city": "Whittier", "zip_code": "90603", "country": "US", "state": "CA", "display_address": [ "15309 Whittier Blvd", "Whittier, CA 90603" ] }, "phone": "+15629056048", "display_phone": "(562) 905-6048", "distance": 5980.620672175974 }, { "id": "TK-qu1WwApLzzhRvKn7Mfg", "alias": "tonys-little-italy-pizza-placentia", "name": "Tony's Little Italy Pizza", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/tF4DOUTxrpPSSOvJW3P1ZA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/tonys-little-italy-pizza-placentia?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 2170, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 33.8955049585903, "longitude": -117.872027337872 }, "transactions": [ ], "price": "$$", "location": { "address1": "1808 N Placentia Ave", "address2": "Unit B", "address3": "", "city": "Placentia", "zip_code": "92870", "country": "US", "state": "CA", "display_address": [ "1808 N Placentia Ave", "Unit B", "Placentia, CA 92870" ] }, "phone": "+17145282159", "display_phone": "(714) 528-2159", "distance": 15438.106560936967 } ], "total": 1700, "region": { "center": { "longitude": -117.9834738, "latitude": 33.9990858 } } } A: Change to @Published var result: Result? Result() doesn't work because all the variables need initial values and you haven't provided the values in the struct so you have to provide then upon init.
How to map JSON with array object to Model in SwiftUI? `Missing argument for parameter 'from' in call`
I am new to SwiftUI and have been stuck for days in trying to map my backend API's JSON object into the SwitchUI Model (Which I think is the right way to approach this type of problem?). I am getting error while trying to initalize the variable. I am trying to use Alamofire to get the response from my API in JSON and map that to a Published variable so I can print the list of businesses as the result. The following is what I have and the I'm getting the "Missing argument for parameter 'from' in call" error on the line: @Published var result: Result = Result() If I make the "[Businesses] and region" in my model as Optional, then I can't see them in the view. What is wrong here? Thanks very much View class SearchFormModel: ObservableObject { @Published var result: Result = Result() AF.request(backendApiURL, parameters: parameters).responseDecodable(of: Result.self) { response in debugPrint("Response:\(response)") switch response.result { case let .success(value): self.result = value print(value) case let .failure(error): print(error) } Model import Foundation import SwiftyJSON struct Result: Codable { var businesses : [Businesses] var region : Region } struct Businesses: Codable { var id : String = "" var alias : String? var name : String? var image_url : URL? var is_closed : Bool? var url : URL? var review_count : Int? var categories : [Categories]? var rating : Double? var coordinates : Coordinates? var transactions : [String]? var price : String? var location : Location? var phone : String? var display_phone : String? var distance : Double? } struct Categories: Codable { var alias : String = "" var title : String = "" } struct Coordinates: Codable { var latitude : Double = 0.0 var longitude : Double = 0.0 } struct Location: Codable { var address1 : String? var address2 : String? var address3 : String? var city : String? var zip_code : String? var country : String? var state : String? var display_address : [String]? } struct Region: Codable { var center : Center } struct Center : Codable { var longitude : Double = 0.0 var latitude : Double = 0.0 } Sample JSON { "businesses": [ { "id": "aDa5FQZdCghy3XwK_h93Fw", "alias": "worlds-best-pizza-hacienda-heights", "name": "World's Best Pizza", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/ZPKyEBB5As3dVberckNyxg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/worlds-best-pizza-hacienda-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 409, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9801206981514, "longitude": -117.974323744633 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "3142 Colima Rd", "address2": "", "address3": "", "city": "Hacienda Heights", "zip_code": "91745", "country": "US", "state": "CA", "display_address": [ "3142 Colima Rd", "Hacienda Heights, CA 91745" ] }, "phone": "+16269684794", "display_phone": "(626) 968-4794", "distance": 2271.295381028884 }, { "id": "ovq2Sfpw7cQZbSMIqs07vg", "alias": "hacienda-heights-pizza-company-hacienda-heights", "name": "Hacienda Heights Pizza Company", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/codEYU-DR_GdRd7dsNsWyA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/hacienda-heights-pizza-company-hacienda-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 437, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 3.5, "coordinates": { "latitude": 34.015013, "longitude": -117.973866 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "15239 Gale Ave", "address2": "", "address3": "", "city": "Hacienda Heights", "zip_code": "91745", "country": "US", "state": "CA", "display_address": [ "15239 Gale Ave", "Hacienda Heights, CA 91745" ] }, "phone": "+16268552590", "display_phone": "(626) 855-2590", "distance": 1980.1106887021883 }, { "id": "I92UQKaJKq9iaa4HTz2tXg", "alias": "scardinos-pizza-to-go-la-puente", "name": "Scardino's Pizza To Go", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/wE2Jm3DK-4bO_11xsXxGEQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/scardinos-pizza-to-go-la-puente?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 339, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "italian", "title": "Italian" } ], "rating": 4.5, "coordinates": { "latitude": 34.0496506030785, "longitude": -117.946955922661 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "1627 N Hacienda Blvd", "address2": "", "address3": "", "city": "La Puente", "zip_code": "91744", "country": "US", "state": "CA", "display_address": [ "1627 N Hacienda Blvd", "La Puente, CA 91744" ] }, "phone": "+16269181507", "display_phone": "(626) 918-1507", "distance": 6552.790234543938 }, { "id": "XzW26Or2ITIbkoTh2XME4w", "alias": "fuoco-pizzeria-napoletana-fullerton", "name": "Fuoco Pizzeria Napoletana", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/wE95ltg-16GPwYJf4Aof0w/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/fuoco-pizzeria-napoletana-fullerton?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 1783, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "italian", "title": "Italian" }, { "alias": "salad", "title": "Salad" } ], "rating": 4.5, "coordinates": { "latitude": 33.87060085641833, "longitude": -117.92457732489875 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "101 N Harbor Blvd", "address2": "", "address3": "", "city": "Fullerton", "zip_code": "92832", "country": "US", "state": "CA", "display_address": [ "101 N Harbor Blvd", "Fullerton, CA 92832" ] }, "phone": "+17146260727", "display_phone": "(714) 626-0727", "distance": 15285.200290883491 }, { "id": "hTf8c43zQ7TFq6PHQAI2bw", "alias": "love-letter-pizza-and-chicken-rowland-heights", "name": "Love Letter Pizza & Chicken", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/zPQEFl8tgsXomodGvgvPMQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/love-letter-pizza-and-chicken-rowland-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 990, "categories": [ { "alias": "korean", "title": "Korean" }, { "alias": "pizza", "title": "Pizza" }, { "alias": "chicken_wings", "title": "Chicken Wings" } ], "rating": 4, "coordinates": { "latitude": 33.989243, "longitude": -117.904673 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "18333B Colima Rd", "address2": "", "address3": "", "city": "Rowland Heights", "zip_code": "91748", "country": "US", "state": "CA", "display_address": [ "18333B Colima Rd", "Rowland Heights, CA 91748" ] }, "phone": "+16268391235", "display_phone": "(626) 839-1235", "distance": 7344.37662932068 }, { "id": "-5GSm4vuDDdtMaEPjPKwcQ", "alias": "vinnys-italian-restaurant-la-habra-2", "name": "Vinny's Italian Restaurant", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/x7mpbYWdKfoY465wY41wsQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/vinnys-italian-restaurant-la-habra-2?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 1090, "categories": [ { "alias": "italian", "title": "Italian" }, { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.92514, "longitude": -117.92276 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "2101 E Lambert Rd", "address2": "", "address3": "", "city": "La Habra", "zip_code": "90631", "country": "US", "state": "CA", "display_address": [ "2101 E Lambert Rd", "La Habra, CA 90631" ] }, "phone": "+15626943400", "display_phone": "(562) 694-3400", "distance": 9950.263973452404 }, { "id": "_FuGSE3AYx9nOTkODPut1g", "alias": "la-crosta-wood-fired-pizza-whittier", "name": "La Crosta Wood Fired Pizza", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/vdBfsfjDqDnxap0BwSLtdQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/la-crosta-wood-fired-pizza-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 59, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9787781, "longitude": -118.0370427 }, "transactions": [ "pickup", "delivery" ], "location": { "address1": "13002 Philadelphia St", "address2": "", "address3": null, "city": "Whittier", "zip_code": "90601", "country": "US", "state": "CA", "display_address": [ "13002 Philadelphia St", "Whittier, CA 90601" ] }, "phone": "+15623247577", "display_phone": "(562) 324-7577", "distance": 5430.611951758044 }, { "id": "5bjEj57xtVg59fsIjWGCzQ", "alias": "blackjack-pizzeria-la-habra", "name": "Blackjack Pizzeria", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/5uQoPZ5RDa_uFS8tnioUSg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/blackjack-pizzeria-la-habra?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 429, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9398719780954, "longitude": -117.973393835127 }, "transactions": [ "pickup", "delivery" ], "price": "$", "location": { "address1": "2429 W Whittier Blvd", "address2": "", "address3": "", "city": "La Habra", "zip_code": "90631", "country": "US", "state": "CA", "display_address": [ "2429 W Whittier Blvd", "La Habra, CA 90631" ] }, "phone": "+15626944111", "display_phone": "(562) 694-4111", "distance": 6649.561538223691 }, { "id": "lCn-WpZORhjjuVeXiNt5hA", "alias": "pizzamania-whittier", "name": "Pizzamania", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/oikKRCcC4Kncp0BBlruVYg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizzamania-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 1027, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 33.9378271, "longitude": -118.0427549 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "13547 Telegraph Rd", "address2": "", "address3": "", "city": "Whittier", "zip_code": "90605", "country": "US", "state": "CA", "display_address": [ "13547 Telegraph Rd", "Whittier, CA 90605" ] }, "phone": "+15629448803", "display_phone": "(562) 944-8803", "distance": 8691.538482559992 }, { "id": "4qcbUWK6PtT_EhE1CL00OQ", "alias": "ravello-osteria-monterey-park", "name": "Ravello Osteria", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/SL-IEVhRUfuFcz1aZzYEQg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/ravello-osteria-monterey-park?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 578, "categories": [ { "alias": "italian", "title": "Italian" }, { "alias": "pastashops", "title": "Pasta Shops" }, { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 34.036084111352146, "longitude": -118.1307262 }, "transactions": [ "delivery" ], "price": "$$", "location": { "address1": "2315 S Garfield Ave", "address2": "", "address3": "", "city": "Monterey Park", "zip_code": "91754", "country": "US", "state": "CA", "display_address": [ "2315 S Garfield Ave", "Monterey Park, CA 91754" ] }, "phone": "+13237227600", "display_phone": "(323) 722-7600", "distance": 14181.449997149568 }, { "id": "a9Oo2cUQXv4V7sNzlWiMNQ", "alias": "pizza-21-whittier", "name": "Pizza 21", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/r37IuAf-RTO9YlkTTtHKKQ/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizza-21-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 220, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 5, "coordinates": { "latitude": 33.9718658905689, "longitude": -118.07371439367 }, "transactions": [ "pickup", "delivery" ], "price": "$", "location": { "address1": "8017 Norwalk Blvd", "address2": "", "address3": null, "city": "Whittier", "zip_code": "90606", "country": "US", "state": "CA", "display_address": [ "8017 Norwalk Blvd", "Whittier, CA 90606" ] }, "phone": "+15628013689", "display_phone": "(562) 801-3689", "distance": 8853.647033272864 }, { "id": "LKPl3iThbC2CdbnPb53XRQ", "alias": "the-curry-pizza-company-walnut-walnut-2", "name": "The Curry Pizza Company - Walnut", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/WaC6AFze5NVW9OrL_uGJ7g/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/the-curry-pizza-company-walnut-walnut-2?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 318, "categories": [ { "alias": "indpak", "title": "Indian" }, { "alias": "pizza", "title": "Pizza" }, { "alias": "chicken_wings", "title": "Chicken Wings" } ], "rating": 4.5, "coordinates": { "latitude": 34.0111996, "longitude": -117.859211 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "376 S Lemon Ave", "address2": "", "address3": null, "city": "Walnut", "zip_code": "91789", "country": "US", "state": "CA", "display_address": [ "376 S Lemon Ave", "Walnut, CA 91789" ] }, "phone": "+19099785065", "display_phone": "(909) 978-5065", "distance": 11533.359141110845 }, { "id": "Wcg_6rnWc6tpktt33ous7Q", "alias": "baby-bros-pizza-and-wings-south-el-monte", "name": "Baby Bros Pizza & Wings", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/MZ115Qxa5HTZvCGLWxYw5w/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/baby-bros-pizza-and-wings-south-el-monte?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 292, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "chicken_wings", "title": "Chicken Wings" }, { "alias": "beerbar", "title": "Beer Bar" } ], "rating": 4, "coordinates": { "latitude": 34.05211, "longitude": -118.05398 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "9847 Rush St", "address2": null, "address3": "", "city": "South El Monte", "zip_code": "91733", "country": "US", "state": "CA", "display_address": [ "9847 Rush St", "South El Monte, CA 91733" ] }, "phone": "+16264482316", "display_phone": "(626) 448-2316", "distance": 8772.804450272562 }, { "id": "2UJcwkqvDAKPX8ZeNbQeFQ", "alias": "pizzarev-rowland-heights", "name": "PizzaRev", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/PiDjlQH6Nw7u4q9TLhaGQg/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizzarev-rowland-heights?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 397, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 33.9901605, "longitude": -117.9246713 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "17490 Colima Rd", "address2": "Ste D", "address3": null, "city": "Rowland Heights", "zip_code": "91748", "country": "US", "state": "CA", "display_address": [ "17490 Colima Rd", "Ste D", "Rowland Heights, CA 91748" ] }, "phone": "+16268540006", "display_phone": "(626) 854-0006", "distance": 5511.128701794727 }, { "id": "SiyyceCOoIuEqCfZEwN3Hg", "alias": "pie-trap-pizza-covina", "name": "Pie Trap Pizza", "image_url": "https://s3-media3.fl.yelpcdn.com/bphoto/o8_i3RxRXkFDDRu3p9l08Q/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pie-trap-pizza-covina?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 20, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4.5, "coordinates": { "latitude": 34.105086485939346, "longitude": -117.87669418232004 }, "transactions": [ ], "location": { "address1": "720 E Arrow Hwy", "address2": "Ste A", "address3": "", "city": "Covina", "zip_code": "91702", "country": "US", "state": "CA", "display_address": [ "720 E Arrow Hwy", "Ste A", "Covina, CA 91702" ] }, "phone": "+16265410051", "display_phone": "(626) 541-0051", "distance": 15352.567810724982 }, { "id": "efqeidrFoFzqVH1TEmJHIg", "alias": "new-york-pizzeria-walnut", "name": "New York Pizzeria", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/36tqlCLWgOLgIaYasL19Qw/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/new-york-pizzeria-walnut?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 246, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "beer_and_wine", "title": "Beer, Wine & Spirits" }, { "alias": "sandwiches", "title": "Sandwiches" } ], "rating": 4, "coordinates": { "latitude": 34.0190473, "longitude": -117.8650573 }, "transactions": [ "delivery" ], "price": "$", "location": { "address1": "364 N Lemon Ave", "address2": "", "address3": "", "city": "Walnut", "zip_code": "91789", "country": "US", "state": "CA", "display_address": [ "364 N Lemon Ave", "Walnut, CA 91789" ] }, "phone": "+19095945000", "display_phone": "(909) 594-5000", "distance": 11138.41781108791 }, { "id": "nG3lHSvq3m0fzFQTdHjUSw", "alias": "tonys-pizza-whittier", "name": "Tony's Pizza", "image_url": "https://s3-media1.fl.yelpcdn.com/bphoto/lZ7c-viftcFik1Y06I8xJA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/tonys-pizza-whittier?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 518, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 33.9422540037959, "longitude": -117.995184817488 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "15624 Whittwood Ln", "address2": "", "address3": "", "city": "Whittier", "zip_code": "90603", "country": "US", "state": "CA", "display_address": [ "15624 Whittwood Ln", "Whittier, CA 90603" ] }, "phone": "+15629470500", "display_phone": "(562) 947-0500", "distance": 6411.01480512212 }, { "id": "DOB_k_gkyijSLgyt-_zodQ", "alias": "jo-peeps-ny-pizza-whittier-3", "name": "Jo Peeps Ny Pizza", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/vX-ghkTzaweOhKEIvq5wzw/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/jo-peeps-ny-pizza-whittier-3?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 193, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "salad", "title": "Salad" }, { "alias": "sandwiches", "title": "Sandwiches" } ], "rating": 4, "coordinates": { "latitude": 33.9535433, "longitude": -118.0161173 }, "transactions": [ "delivery" ], "price": "$", "location": { "address1": "14450 Whittier Blvd", "address2": "", "address3": "", "city": "Whittier", "zip_code": "90605", "country": "US", "state": "CA", "display_address": [ "14450 Whittier Blvd", "Whittier, CA 90605" ] }, "phone": "+15629459691", "display_phone": "(562) 945-9691", "distance": 5891.520785405544 }, { "id": "2z5o4QXHgDc6vQLqZYoI8w", "alias": "pizza-n-brews-whittier-3", "name": "Pizza-N-Brews", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/eowFStZQxkd0V4bPg5rigA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/pizza-n-brews-whittier-3?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 43, "categories": [ { "alias": "pizza", "title": "Pizza" }, { "alias": "sandwiches", "title": "Sandwiches" }, { "alias": "beerbar", "title": "Beer Bar" } ], "rating": 4.5, "coordinates": { "latitude": 33.94714, "longitude": -118.00047 }, "transactions": [ "pickup", "delivery" ], "price": "$$", "location": { "address1": "15309 Whittier Blvd", "address2": null, "address3": "", "city": "Whittier", "zip_code": "90603", "country": "US", "state": "CA", "display_address": [ "15309 Whittier Blvd", "Whittier, CA 90603" ] }, "phone": "+15629056048", "display_phone": "(562) 905-6048", "distance": 5980.620672175974 }, { "id": "TK-qu1WwApLzzhRvKn7Mfg", "alias": "tonys-little-italy-pizza-placentia", "name": "Tony's Little Italy Pizza", "image_url": "https://s3-media4.fl.yelpcdn.com/bphoto/tF4DOUTxrpPSSOvJW3P1ZA/o.jpg", "is_closed": false, "url": "https://www.yelp.com/biz/tonys-little-italy-pizza-placentia?adjust_creative=WpoQHLnOMdOyEndsLlwSPg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=WpoQHLnOMdOyEndsLlwSPg", "review_count": 2170, "categories": [ { "alias": "pizza", "title": "Pizza" } ], "rating": 4, "coordinates": { "latitude": 33.8955049585903, "longitude": -117.872027337872 }, "transactions": [ ], "price": "$$", "location": { "address1": "1808 N Placentia Ave", "address2": "Unit B", "address3": "", "city": "Placentia", "zip_code": "92870", "country": "US", "state": "CA", "display_address": [ "1808 N Placentia Ave", "Unit B", "Placentia, CA 92870" ] }, "phone": "+17145282159", "display_phone": "(714) 528-2159", "distance": 15438.106560936967 } ], "total": 1700, "region": { "center": { "longitude": -117.9834738, "latitude": 33.9990858 } } }
[ "Change to\n@Published var result: Result?\n\nResult() doesn't work because all the variables need initial values and you haven't provided the values in the struct so you have to provide then upon init.\n" ]
[ 0 ]
[]
[]
[ "alamofire", "json", "swift", "swiftui" ]
stackoverflow_0074680802_alamofire_json_swift_swiftui.txt
Q: Unable to use session cookie in server-side request (getServerSideProps) in Next.js I'm trying to perform a request to a backend service using Axios inside getServerSideProps, but it is failing because the session cookie that is needed for authentication is not included in context.req headers. The application has its client on a subdomain (e.g. app.domain.com) and the backend service, which is based on Node/Express.js, is on another subdomain (e.g. api.domain.com). The cookie is being sent during authentication and seems to be correctly stored in the browser, but interestingly, it is not stored within the client subdomain, but as part of the backend subdomain (api.domain.com). I'm using cookie-session for handling the response from Express with the following config flags: app.use( cookieSession({ signed: false, secure: true, httpOnly: true, sameSite: "strict" }) ); I've played with the cookie-session middleware config flags, setting sameSite to "none" and httpOnly to false, with no success. I've also checked the contents of the "context" object in getServerSideProps, just to confirm that the cookie is not being sent to the server. A: Assuming you have correctly configured a middleware in your backend to send/accept credentials and accept CORS requests (e.g. https://expressjs.com/en/resources/middleware/cors.html), you can try to add the "domain" flag to cookieSession options. app.use( cookieSession({ signed: false, domain: "your-domain.com", secure: true, httpOnly: true, sameSite: "strict" }) ); This way, the cookie will be stored in the "domain scope" and not restricted to your backend subdomain.
Unable to use session cookie in server-side request (getServerSideProps) in Next.js
I'm trying to perform a request to a backend service using Axios inside getServerSideProps, but it is failing because the session cookie that is needed for authentication is not included in context.req headers. The application has its client on a subdomain (e.g. app.domain.com) and the backend service, which is based on Node/Express.js, is on another subdomain (e.g. api.domain.com). The cookie is being sent during authentication and seems to be correctly stored in the browser, but interestingly, it is not stored within the client subdomain, but as part of the backend subdomain (api.domain.com). I'm using cookie-session for handling the response from Express with the following config flags: app.use( cookieSession({ signed: false, secure: true, httpOnly: true, sameSite: "strict" }) ); I've played with the cookie-session middleware config flags, setting sameSite to "none" and httpOnly to false, with no success. I've also checked the contents of the "context" object in getServerSideProps, just to confirm that the cookie is not being sent to the server.
[ "Assuming you have correctly configured a middleware in your backend to send/accept credentials and accept CORS requests (e.g. https://expressjs.com/en/resources/middleware/cors.html), you can try to add the \"domain\" flag to cookieSession options.\napp.use(\n cookieSession({\n signed: false,\n domain: \"your-domain.com\",\n secure: true,\n httpOnly: true,\n sameSite: \"strict\"\n })\n);\n\nThis way, the cookie will be stored in the \"domain scope\" and not restricted to your backend subdomain.\n" ]
[ 0 ]
[]
[]
[ "cookie_session", "express", "next.js", "session_cookies" ]
stackoverflow_0074680798_cookie_session_express_next.js_session_cookies.txt