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:
doubling object in Python
how do I double the object side by side?
print(" *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****" *2)
this code puts the objects one below another, how do i do that it prints it besides?
A:
You could try something like that:
obj = " *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****"
lines = obj.split('\n')
space = len(max(lines, key=len)) + 3
for line in lines:
print(line + " "* (space - len(line)) + line)
A:
Use a multiline string for your image, iterate through the lines and print each one doubled:
# using dots to indicate spaces clearly
s = '''\
....*.....
...*.*....
..*...*...
.*.....*..
***...***.
..*...*...
..*...*...
..*****...
'''.replace('.',' ')
# double each line
for line in s.splitlines():
print(line * 2)
Output:
* *
* * * *
* * * *
* * * *
*** *** *** ***
* * * *
* * * *
***** *****
A:
This works:
arrow = " *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****"
arrow_lines = arrow.split("\n")
double_arrow_lines = [line +" "*(15-len(line)) +line for line in arrow_lines]
double_arrow = "\n".join(double_arrow_lines)
print(double_arrow)
| doubling object in Python | how do I double the object side by side?
print(" *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****" *2)
this code puts the objects one below another, how do i do that it prints it besides?
| [
"You could try something like that:\nobj = \" *\\n * *\\n * *\\n * *\\n*** ***\\n * *\\n * *\\n *****\"\n\nlines = obj.split('\\n')\nspace = len(max(lines, key=len)) + 3\n\nfor line in lines:\n print(line + \" \"* (space - len(line)) + line)\n\n",
"Use a multiline string for your image, iterate through the lines and print each one doubled:\n# using dots to indicate spaces clearly\ns = '''\\\n....*.....\n...*.*....\n..*...*...\n.*.....*..\n***...***.\n..*...*...\n..*...*...\n..*****...\n'''.replace('.',' ')\n\n# double each line\nfor line in s.splitlines():\n print(line * 2)\n\nOutput:\n * * \n * * * * \n * * * * \n * * * * \n*** *** *** *** \n * * * * \n * * * * \n ***** ***** \n\n",
"This works:\narrow = \" *\\n * *\\n * *\\n * *\\n*** ***\\n * *\\n * *\\n *****\"\n \narrow_lines = arrow.split(\"\\n\")\ndouble_arrow_lines = [line +\" \"*(15-len(line)) +line for line in arrow_lines]\ndouble_arrow = \"\\n\".join(double_arrow_lines)\n \nprint(double_arrow)\n\n"
] | [
2,
1,
0
] | [
"To print the object side by side, you can use the join() method. The join() method takes a list of strings and concatenates them together, using the string on which the method is called as a separator.\nFor example, you can use the following code to print the object side by side:\nobj = \" *\\n * \\n * \\n * \\n ***\\n * *\\n * *\\n *****\"\n\nprint(\"\\n\".join([obj, obj]))\n\nThis will print the object twice, with a newline between each instance.\nAlternatively, you could use string multiplication to repeat the string, and then use the print() function to print the result on a single line, like this:\nobj = \" *\\n * \\n * \\n * \\n ***\\n * *\\n * *\\n *****\"\n\nprint(obj * 2, sep=\"\")\n\nIn this case, we use the sep parameter of the print() function to specify that no separator should be used between the items being printed. This will print the objects side by side on a single line.\n"
] | [
-4
] | [
"python"
] | stackoverflow_0074671391_python.txt |
Q:
My javascript function does not loop using setInterval
I have to create a JS program that changes the title of a page either every 30 seconds or when the user leaves the page. It depends on the word passed in parameter. I call "linear" the function that allows to change the title every 30 seconds and leaving the one that allows it when the user leaves the page.
The leaving function works well but the linear function executes only the first cell of the message array to display. I tried several alternatives but nothing works, could someone explain my error?
Here is the code
var titles = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];
var timeLaps = 1000; // time in miliseconds
var i = 0;
var ogTitle = document.title;
function mainTitle() {
document.title = ogTitle;
}
function newTitle() {
document.title = 'Come Back!';
}
function leaving() {
window.onblur = newTitle;
window.onfocus = mainTitle;
}
function linear(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
function main(animType) {
if(animType === "leaving") {
leaving();
} else if (animType === "linear") {
setInterval(() => {
changeTitle('linear')
}, timeLaps);
}
}
main('linear');
Have a good day!
A:
The solution is pretty simple. With the given code, you should switch array titles to titleArray, or switch titleArray to titles. This is because you defined it as following:
var titles = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];
and later you used:
document.title = titleArray[i];
With this simple fix, it worked for me in my browser. What I did was the following:
var titleArray = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];
A:
Details are commented in example
let initInterval = null; // Define interval method
/* Set a flag to prevent constant "focus" event triggering
(see lines marked with: β)
*/
let on = false;
let delay = 3000; // 3 seconds for setTimeout method
/* Change to 30000 for 30 second intervals as per OP. 3 seconds
is just for the sake of brevity
*/
let interval = 3000;
let count = 0; // Define count with initial value
// Define array of titles
const titles = ["TITLE I", "TITLE II", "TITLE III", "TITLE IV"];
/*
|| Uncomment line A and comment line B as per OP
*/
// const changeTitle = str => document.title = str; // A
const changeTitle = str => document.querySelector("h1").textContent = str; // B
/*
|| Event handler passes (e)vent object by default
|| Redefine initInterval() method
==========================================================
|| wrap source of setInterval() in an anonymous function so that changeTitle()
|| can pass the parameter >titles[count++]<
|| Note: >count< is incremented on line C.
==========================================================
|| If >count< exceeds the last index of >titles< array, reset >count<
|| Invoke changeTitle(), passing the string at the current index
|| of >titles< array
|| Repeat above every >interval< ms
*/
const go = e => {
initInterval = setInterval(() => {
if (count > titles.length - 1) {
count = 0;
}
changeTitle(titles[count++]); // C
}, interval);
}
/*
|| Anonymous event handler triggers when window loads
|β Set >on< to true which indicates the user is still on the page.
|| Change title to it's welcome message
|| Start go(e) in >delay< ms
*/
window.onload = e => {
on = true; // β
changeTitle("Loaded");
setTimeout(go, delay);
}
/*
|| Anonymous event handler triggers when user focuses on window.
|β If the >on< flag is false...
|| change the title to the focused message
|| start go(e) in >delay< ms
|β set >on< to true. This ensures that the only "focus" event that
|| the event handler gets triggered by is when the user focuses after
|| a "blur" event
*/
window.onfocus = e => {
if (!on) { // β
changeTitle("Focused");
setTimeout(go, delay);
on = true; // β
}
}
/*
|| Anonymous event handler triggers when the user leaves the window.
|β Set the >on< flag to false indicating that the user has left the page
|| Change to title to a leaving message
|| Remove the interval method
*/
window.onblur = e => {
on = false; // β
changeTitle("Unfocused");
clearInterval(initInterval);
}
<h1></h1>
A:
You call your method changeTitle without arguments, yet you didn't handle the case within method when there is no arguments.
Try calling it like this:
setInterval(() => {
changeTitle('linear')
}, timeLaps);
| My javascript function does not loop using setInterval | I have to create a JS program that changes the title of a page either every 30 seconds or when the user leaves the page. It depends on the word passed in parameter. I call "linear" the function that allows to change the title every 30 seconds and leaving the one that allows it when the user leaves the page.
The leaving function works well but the linear function executes only the first cell of the message array to display. I tried several alternatives but nothing works, could someone explain my error?
Here is the code
var titles = ["MyTitle","AlsoMyTitle","MyThirdTitle","TheFourth"];
var timeLaps = 1000; // time in miliseconds
var i = 0;
var ogTitle = document.title;
function mainTitle() {
document.title = ogTitle;
}
function newTitle() {
document.title = 'Come Back!';
}
function leaving() {
window.onblur = newTitle;
window.onfocus = mainTitle;
}
function linear(){
if (i == 4) {
i = 0;
}
document.title = titleArray[i];
i++;
}
function main(animType) {
if(animType === "leaving") {
leaving();
} else if (animType === "linear") {
setInterval(() => {
changeTitle('linear')
}, timeLaps);
}
}
main('linear');
Have a good day!
| [
"The solution is pretty simple. With the given code, you should switch array titles to titleArray, or switch titleArray to titles. This is because you defined it as following:\nvar titles = [\"MyTitle\",\"AlsoMyTitle\",\"MyThirdTitle\",\"TheFourth\"];\n\nand later you used:\ndocument.title = titleArray[i];\n\nWith this simple fix, it worked for me in my browser. What I did was the following:\nvar titleArray = [\"MyTitle\",\"AlsoMyTitle\",\"MyThirdTitle\",\"TheFourth\"];\n\n",
"Details are commented in example\n\n\nlet initInterval = null; // Define interval method\n/* Set a flag to prevent constant \"focus\" event triggering\n (see lines marked with: β) \n*/\nlet on = false;\nlet delay = 3000; // 3 seconds for setTimeout method\n/* Change to 30000 for 30 second intervals as per OP. 3 seconds\nis just for the sake of brevity \n*/\nlet interval = 3000;\nlet count = 0; // Define count with initial value \n// Define array of titles\nconst titles = [\"TITLE I\", \"TITLE II\", \"TITLE III\", \"TITLE IV\"];\n\n/*\n|| Uncomment line A and comment line B as per OP\n*/\n// const changeTitle = str => document.title = str; // A\nconst changeTitle = str => document.querySelector(\"h1\").textContent = str; // B\n\n/*\n|| Event handler passes (e)vent object by default\n|| Redefine initInterval() method\n==========================================================\n|| wrap source of setInterval() in an anonymous function so that changeTitle() \n|| can pass the parameter >titles[count++]< \n|| Note: >count< is incremented on line C.\n==========================================================\n|| If >count< exceeds the last index of >titles< array, reset >count<\n|| Invoke changeTitle(), passing the string at the current index\n|| of >titles< array\n|| Repeat above every >interval< ms\n*/\nconst go = e => {\n initInterval = setInterval(() => {\n if (count > titles.length - 1) {\n count = 0;\n }\n changeTitle(titles[count++]); // C\n }, interval);\n}\n\n/*\n|| Anonymous event handler triggers when window loads\n|β Set >on< to true which indicates the user is still on the page.\n|| Change title to it's welcome message\n|| Start go(e) in >delay< ms\n*/\nwindow.onload = e => {\n on = true; // β\n changeTitle(\"Loaded\");\n setTimeout(go, delay);\n}\n\n/*\n|| Anonymous event handler triggers when user focuses on window.\n|β If the >on< flag is false...\n|| change the title to the focused message\n|| start go(e) in >delay< ms\n|β set >on< to true. This ensures that the only \"focus\" event that\n|| the event handler gets triggered by is when the user focuses after \n|| a \"blur\" event\n*/\nwindow.onfocus = e => {\n if (!on) { // β\n changeTitle(\"Focused\");\n setTimeout(go, delay);\n on = true; // β\n }\n}\n/*\n|| Anonymous event handler triggers when the user leaves the window.\n|β Set the >on< flag to false indicating that the user has left the page\n|| Change to title to a leaving message\n|| Remove the interval method\n*/\nwindow.onblur = e => {\n on = false; // β\n changeTitle(\"Unfocused\");\n clearInterval(initInterval);\n}\n<h1></h1>\n\n\n\n",
"You call your method changeTitle without arguments, yet you didn't handle the case within method when there is no arguments.\nTry calling it like this:\nsetInterval(() => {\n changeTitle('linear')\n}, timeLaps);\n\n"
] | [
1,
1,
0
] | [] | [] | [
"html",
"javascript",
"title"
] | stackoverflow_0074670428_html_javascript_title.txt |
Q:
Unity framework for SwiftUI InitializeMemory() error in iOS 16.1
I am using Unity as a library for SwiftUI quite a while now. However when updating to the newest iOS version (16.1) it stopped working. Compiling runs without a problem but during runtime I get an error when Unity is starting:
in:
I even started a completely new project with Unity included to SwiftUI and get the same error. As this is some kind of assembler code and I certainly do not know how to read it I don't really know where I have to start searching.
A:
A similar thing happened to me. I'm not entirely sure if it's the same problem but in the console, I got a message saying UnityFramework is running optimized and may behave oddly. Unfortunately, I've tried a couple of ways to disable optimization but I've yet to find a solution.
For now, I'm able to bypass this error by disabling the debugger entirely. In order to do this, you have to go to Product -> Scheme -> Edit Scheme and uncheck debug executable.
I'm not sure if this will work for you but I figured it'd be worth a shot!
| Unity framework for SwiftUI InitializeMemory() error in iOS 16.1 | I am using Unity as a library for SwiftUI quite a while now. However when updating to the newest iOS version (16.1) it stopped working. Compiling runs without a problem but during runtime I get an error when Unity is starting:
in:
I even started a completely new project with Unity included to SwiftUI and get the same error. As this is some kind of assembler code and I certainly do not know how to read it I don't really know where I have to start searching.
| [
"A similar thing happened to me. I'm not entirely sure if it's the same problem but in the console, I got a message saying UnityFramework is running optimized and may behave oddly. Unfortunately, I've tried a couple of ways to disable optimization but I've yet to find a solution.\nFor now, I'm able to bypass this error by disabling the debugger entirely. In order to do this, you have to go to Product -> Scheme -> Edit Scheme and uncheck debug executable.\nI'm not sure if this will work for you but I figured it'd be worth a shot!\n"
] | [
0
] | [] | [] | [
"swiftui",
"unity3d"
] | stackoverflow_0074623906_swiftui_unity3d.txt |
Q:
Visual Studio: Errors only showing in terminal after running code
No errors are shown in the "problems" tab nor in the code itself. How do I get these errors to show up in the "problems" tab and in my code for easier debugging?
Right now it says "No problems have been detected in the workspace." When my code runs with errors in the terminal.
I tried reinstalling and resetting my settings, no luck.
error example (only shown in terminal):
Traceback (most recent call last):
File "redacted", line 29, in <module>
main()
File "redacted", line 6, in main
deal_cards(deck, numcards)
File "redacted", line 17, in deal_cards
if number > len(deck):
TypeError: object of type 'NoneType' has no len()
A:
It sounds like you are using an Integrated Development Environment (IDE) to write and run your code, but the IDE is not showing any errors or warnings when your code contains mistakes.
There are a few possible reasons for this. First, it is possible that your IDE is not properly configured to display errors and warnings. In this case, you can try looking for settings or preferences related to error and warning display, and make sure that these are enabled.
Second, it is possible that your code contains mistakes that the IDE is not able to detect. This can happen if your code contains syntax errors or other problems that the IDE is not designed to recognize. In this case, you can try running your code through a compiler or interpreter, which will typically provide more detailed error messages that can help you identify and fix problems in your code.
Finally, it is also possible that your code is actually correct and does not contain any errors or warnings. In this case, the IDE will not show any errors or warnings because there are none to display.
Overall, the best way to troubleshoot problems with error and warning display in your IDE will depend on the specific tools and settings you are using. You may need to consult the documentation for your IDE, compiler, or interpreter to learn how to configure error and warning display and how to interpret the error messages that are generated.
A:
The error you show is a runtime error (an error that happens when a program is run, not before) and the Errors window doesn't show runtime errors.
| Visual Studio: Errors only showing in terminal after running code | No errors are shown in the "problems" tab nor in the code itself. How do I get these errors to show up in the "problems" tab and in my code for easier debugging?
Right now it says "No problems have been detected in the workspace." When my code runs with errors in the terminal.
I tried reinstalling and resetting my settings, no luck.
error example (only shown in terminal):
Traceback (most recent call last):
File "redacted", line 29, in <module>
main()
File "redacted", line 6, in main
deal_cards(deck, numcards)
File "redacted", line 17, in deal_cards
if number > len(deck):
TypeError: object of type 'NoneType' has no len()
| [
"It sounds like you are using an Integrated Development Environment (IDE) to write and run your code, but the IDE is not showing any errors or warnings when your code contains mistakes.\nThere are a few possible reasons for this. First, it is possible that your IDE is not properly configured to display errors and warnings. In this case, you can try looking for settings or preferences related to error and warning display, and make sure that these are enabled.\nSecond, it is possible that your code contains mistakes that the IDE is not able to detect. This can happen if your code contains syntax errors or other problems that the IDE is not designed to recognize. In this case, you can try running your code through a compiler or interpreter, which will typically provide more detailed error messages that can help you identify and fix problems in your code.\nFinally, it is also possible that your code is actually correct and does not contain any errors or warnings. In this case, the IDE will not show any errors or warnings because there are none to display.\nOverall, the best way to troubleshoot problems with error and warning display in your IDE will depend on the specific tools and settings you are using. You may need to consult the documentation for your IDE, compiler, or interpreter to learn how to configure error and warning display and how to interpret the error messages that are generated.\n",
"The error you show is a runtime error (an error that happens when a program is run, not before) and the Errors window doesn't show runtime errors.\n"
] | [
0,
0
] | [] | [] | [
"debugging",
"terminal",
"visual_studio"
] | stackoverflow_0074671338_debugging_terminal_visual_studio.txt |
Q:
How to stop an ongoing phone authentication request with Firebase
I have added to my phone authentication to my sign up process, in a send code activity - which sends the sms code to confirm the phone authentication process. Then, I have also added a "go-back"/"return" button which moves the user back to the main activity.
If I make the following request which sends the user a sms code to his phone:
PhoneAuthProvider.verifyPhoneNumber(options);
I won't be able to make another request before the defined timeout duration ends. Therefore, I thought about the easy and not messy approach, that would be to cancel the ongoing request, but unfortunately couldn't find how to do so, if even possible nowadays. I have also saw the unanswered post here: Android Firebase OTP auth: Is there a way to cancel OTP code request programatically before the actual timeout?
Couldn't work with this, even though it's what I am looking for, but it has no related answers.
Note: I am programming my project with Java and not Kotlin.
I have also thought about the second approach, which is to save current activity's phone number and then extract it with onRestoreInstanceState and onSaveInstanceState, then resend a code sms again. But of course, it's much more complicated and messier.
A:
It is possible to cancel an ongoing verification request by calling the verifyPhoneNumber method again with the same phone number, but with the forceResendingToken parameter set to null. This will cancel the previous request and allow to start a new one.
It is also possible to use the PhoneAuthProvider.getInstance() method to get a reference to the PhoneAuthProvider instance, and then call the verifyPhoneNumber method on that instance instead of calling it directly. This allows to call the verifyPhoneNumber method multiple times without canceling the previous request.
Timeout duration for verification requests is typically around 5 minutes, so if you want to allow the user to request a new code before the timeout expires, provide a way for them to do so, such as by adding a "Resend code" button to the app.
Overall, it's best to design apps in a way that minimizes the need for canceling ongoing verification requests, as this can lead to a confusing user experience. Instead, focus on providing clear instructions and options for the user, and consider using the getInstance method to avoid having to cancel requests altogether.
A:
To cancel an ongoing phone verification request in Firebase, you can use the PhoneAuthProvider.ForceResendingToken class. This class represents a token that can be used to force the resending of a verification code.
To cancel an ongoing phone verification request, you can use the PhoneAuthProvider.verifyPhoneNumber method to initiate the request, and then call the PhoneAuthProvider.verifyPhoneNumber method again with the same phoneNumber and ForceResendingToken arguments. This will cancel the previous request and start a new one, allowing you to resend the verification code.
Here is an example of how you can cancel an ongoing phone verification request in Firebase:
// Initiate the phone verification request
PhoneAuthProvider.verifyPhoneNumber(
phoneNumber,
timeoutDuration,
activity,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
// Handle the verification state change events
@Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
// Save the verification ID and token
this.verificationId = verificationId;
this.token = token;
}
// ...
}
);
// Cancel the ongoing phone verification request
PhoneAuthProvider.verifyPhoneNumber(
phoneNumber,
timeoutDuration,
activity,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
// Handle the verification state change events
@Override
public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
// Save the verification ID and token
this.verificationId = verificationId;
this.token = token;
}
// ...
},
token //
| How to stop an ongoing phone authentication request with Firebase | I have added to my phone authentication to my sign up process, in a send code activity - which sends the sms code to confirm the phone authentication process. Then, I have also added a "go-back"/"return" button which moves the user back to the main activity.
If I make the following request which sends the user a sms code to his phone:
PhoneAuthProvider.verifyPhoneNumber(options);
I won't be able to make another request before the defined timeout duration ends. Therefore, I thought about the easy and not messy approach, that would be to cancel the ongoing request, but unfortunately couldn't find how to do so, if even possible nowadays. I have also saw the unanswered post here: Android Firebase OTP auth: Is there a way to cancel OTP code request programatically before the actual timeout?
Couldn't work with this, even though it's what I am looking for, but it has no related answers.
Note: I am programming my project with Java and not Kotlin.
I have also thought about the second approach, which is to save current activity's phone number and then extract it with onRestoreInstanceState and onSaveInstanceState, then resend a code sms again. But of course, it's much more complicated and messier.
| [
"It is possible to cancel an ongoing verification request by calling the verifyPhoneNumber method again with the same phone number, but with the forceResendingToken parameter set to null. This will cancel the previous request and allow to start a new one.\nIt is also possible to use the PhoneAuthProvider.getInstance() method to get a reference to the PhoneAuthProvider instance, and then call the verifyPhoneNumber method on that instance instead of calling it directly. This allows to call the verifyPhoneNumber method multiple times without canceling the previous request.\nTimeout duration for verification requests is typically around 5 minutes, so if you want to allow the user to request a new code before the timeout expires, provide a way for them to do so, such as by adding a \"Resend code\" button to the app.\nOverall, it's best to design apps in a way that minimizes the need for canceling ongoing verification requests, as this can lead to a confusing user experience. Instead, focus on providing clear instructions and options for the user, and consider using the getInstance method to avoid having to cancel requests altogether.\n",
"To cancel an ongoing phone verification request in Firebase, you can use the PhoneAuthProvider.ForceResendingToken class. This class represents a token that can be used to force the resending of a verification code.\nTo cancel an ongoing phone verification request, you can use the PhoneAuthProvider.verifyPhoneNumber method to initiate the request, and then call the PhoneAuthProvider.verifyPhoneNumber method again with the same phoneNumber and ForceResendingToken arguments. This will cancel the previous request and start a new one, allowing you to resend the verification code.\nHere is an example of how you can cancel an ongoing phone verification request in Firebase:\n// Initiate the phone verification request\nPhoneAuthProvider.verifyPhoneNumber(\n phoneNumber,\n timeoutDuration,\n activity,\n new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {\n // Handle the verification state change events\n @Override\n public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {\n // Save the verification ID and token\n this.verificationId = verificationId;\n this.token = token;\n }\n // ...\n }\n);\n\n// Cancel the ongoing phone verification request\nPhoneAuthProvider.verifyPhoneNumber(\n phoneNumber,\n timeoutDuration,\n activity,\n new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {\n // Handle the verification state change events\n @Override\n public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {\n // Save the verification ID and token\n this.verificationId = verificationId;\n this.token = token;\n }\n // ...\n },\n token //\n\n"
] | [
1,
0
] | [] | [] | [
"android",
"firebase",
"java"
] | stackoverflow_0074645305_android_firebase_java.txt |
Q:
Python can't access global variable modified in a loop in another loop because of threading
I'm currently working on a small project with the OpenWeatherMap API and used threading for the first time. I don't know if this is the best "solution" to my code, but the rest of my project is working fine and I'm having only this one last issue.
It seems like it's coming from the way the threading is handled, that the 2nd thread is calling a variable that didn't get "processed" in the 1st thread so far.
import requests
import time
import json
from threading import Thread
def weather():
global desc
while True:
# [code for the API is working fine]
with open('weather.json') as f:
data = json.load(f)
desc = data["weather"][0]["description"]
temp = data["main"]["temp"]
print(desc, temp)
time.sleep(120) # this would print something like "extra sunny 293" (temp in Β°K) every 2 mins
def other():
while True:
print(desc)
time.sleep(10) # this causes the error "NameError: name 'desc' is not defined"
thread1 = Thread(target=weather)
thread2 = Thread(target=other)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
My current "fix" is to simply add a small delay to the 2nd loop with:
def other():
while True:
time.sleep(1)
print(desc)
time.sleep(9) # no error anymore
But this solution feels rather janky and I can imagine that it will get only worse with more complicated code. Is there a more optimal way to fix this?
A:
It sounds like the variable desc is not defined in the other function. You can fix this by making desc a global variable that can be accessed by both functions. You can do this by adding the global keyword before the variable name in both functions, like this:
def weather():
global desc
# [code for the API is working fine]
with open('weather.json') as f:
data = json.load(f)
desc = data["weather"][0]["description"]
temp = data["main"]["temp"]
print(desc, temp)
time.sleep(120) # this would print something like "extra sunny 293" (temp in Β°K) every 2 mins
def other():
global desc
while True:
print(desc)
Alternatively, you can pass the value of desc as an argument to the other function when you create the thread2 object, like this:
thread2 = Thread(target=other, args=(desc,))
Then, you can access the desc argument in the other function using the index of the args tuple, like this:
def other(desc):
while True:
print(desc)
time.sleep(10) # this should no longer cause the "NameError: name 'desc' is not defined" error
| Python can't access global variable modified in a loop in another loop because of threading | I'm currently working on a small project with the OpenWeatherMap API and used threading for the first time. I don't know if this is the best "solution" to my code, but the rest of my project is working fine and I'm having only this one last issue.
It seems like it's coming from the way the threading is handled, that the 2nd thread is calling a variable that didn't get "processed" in the 1st thread so far.
import requests
import time
import json
from threading import Thread
def weather():
global desc
while True:
# [code for the API is working fine]
with open('weather.json') as f:
data = json.load(f)
desc = data["weather"][0]["description"]
temp = data["main"]["temp"]
print(desc, temp)
time.sleep(120) # this would print something like "extra sunny 293" (temp in Β°K) every 2 mins
def other():
while True:
print(desc)
time.sleep(10) # this causes the error "NameError: name 'desc' is not defined"
thread1 = Thread(target=weather)
thread2 = Thread(target=other)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
My current "fix" is to simply add a small delay to the 2nd loop with:
def other():
while True:
time.sleep(1)
print(desc)
time.sleep(9) # no error anymore
But this solution feels rather janky and I can imagine that it will get only worse with more complicated code. Is there a more optimal way to fix this?
| [
"It sounds like the variable desc is not defined in the other function. You can fix this by making desc a global variable that can be accessed by both functions. You can do this by adding the global keyword before the variable name in both functions, like this:\ndef weather():\n global desc\n # [code for the API is working fine]\n with open('weather.json') as f:\n data = json.load(f)\n desc = data[\"weather\"][0][\"description\"]\n temp = data[\"main\"][\"temp\"]\n print(desc, temp)\n time.sleep(120) # this would print something like \"extra sunny 293\" (temp in Β°K) every 2 mins \n\ndef other():\n global desc\n while True:\n print(desc)\n\n\nAlternatively, you can pass the value of desc as an argument to the other function when you create the thread2 object, like this:\nthread2 = Thread(target=other, args=(desc,))\n\nThen, you can access the desc argument in the other function using the index of the args tuple, like this:\ndef other(desc):\n while True:\n print(desc)\n time.sleep(10) # this should no longer cause the \"NameError: name 'desc' is not defined\" error\n\n\n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0074671542_multithreading_python_python_multithreading.txt |
Q:
iOS Safari + Vimeo iframe, detect "Done" button press in native player
I have a Vimeo iframe embed on a mobile site, and am trying to figure out how to detect when the user presses the "Done" button in the native iOS Safari video player.
I know this is possible with the "webkitendfullscreen" event if you are embedding with a video tag directly (as described here):
$('video').bind('webkitendfullscreen', function()
{
console.log('on webkit close');
});
However, the video object is not accessible in the case of a foreign iframe embed.
A:
I have not, so far, been able to find a good way to get this to happen, after quite a lot of keyboard-head-banging. I really hope Vimeo adds a way to do this in the future. The only thing I have found is in their new JS API, there is an event fired when the video has ended, and you can latch on to that and do something if they watch the video all the way to the end. You can also detect when the user pauses the video and do something after a "reasonable" time-frame, depending on what you are trying to do.
My hope was that I would be able to close the corresponding modal window whenever someone closes out of a video, but that was really not a possibility.
A:
you can use the leavepictureinpicture event
myPlayer.on("leavepictureinpicture", () => console.log("leave pip triggered"));
https://github.com/vimeo/player.js/blob/master/README.md#leavepictureinpicture
| iOS Safari + Vimeo iframe, detect "Done" button press in native player | I have a Vimeo iframe embed on a mobile site, and am trying to figure out how to detect when the user presses the "Done" button in the native iOS Safari video player.
I know this is possible with the "webkitendfullscreen" event if you are embedding with a video tag directly (as described here):
$('video').bind('webkitendfullscreen', function()
{
console.log('on webkit close');
});
However, the video object is not accessible in the case of a foreign iframe embed.
| [
"I have not, so far, been able to find a good way to get this to happen, after quite a lot of keyboard-head-banging. I really hope Vimeo adds a way to do this in the future. The only thing I have found is in their new JS API, there is an event fired when the video has ended, and you can latch on to that and do something if they watch the video all the way to the end. You can also detect when the user pauses the video and do something after a \"reasonable\" time-frame, depending on what you are trying to do.\nMy hope was that I would be able to close the corresponding modal window whenever someone closes out of a video, but that was really not a possibility.\n",
"you can use the leavepictureinpicture event\nmyPlayer.on(\"leavepictureinpicture\", () => console.log(\"leave pip triggered\"));\n\nhttps://github.com/vimeo/player.js/blob/master/README.md#leavepictureinpicture\n"
] | [
0,
0
] | [] | [] | [
"embed",
"iframe",
"ios",
"safari",
"vimeo"
] | stackoverflow_0043935724_embed_iframe_ios_safari_vimeo.txt |
Q:
How to configure the docker image for the Jenkin to create the Android build?
How can we use the Docker image for the Android and Java SDK instead of setting the manual path of Android and Java inside the Manage Jenkin option?
I have done in the Gitlab to create the multiple apk on each Git push with the help of .gitlab-ci.yml. Is same type of file will be use in case of Jenkin? Please check the below links
1). First link
2). Second link
Just like Gitlab apk/build creation I need to perform same operation in Jenkin.
How to use this below docker image of Android SDK 30 which are as below please check it once
I am using this Docker image from this reference, please check it once Click here
A:
Pull the Jenkins Docker image from the Docker Hub.
docker pull jenkins/jenkins:lts
Run the Docker image and expose the port 8080.
docker run -d -v jenkins_home:/var/jenkins_home -p 8080:8080 --name
jenkins jenkins/jenkins:lts
Create the directory for Android SDK and set the environment variables.
mkDIR /var/jenkins_home/android-sdk && export
ANDROID_HOME=/var/jenkins_home/android-sdk
Download and install the Android SDK in the created directory.
wget
https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
&& unzip sdk-tools-linux-4333796.zip -d /var/jenkins_home/android-sdk
Download and install the Android SDK Platform tools.
wget
https://dl.google.com/android/repository/platform-tools_r28.0.1-linux.zip
&& unzip platform-tools_r28.0.1-linux.zip -d
/var/jenkins_home/android-sdk
Install the Android SDK build tools.
/var/jenkins_home/android-sdk/tools/bin/sdkmanager --list
/var/jenkins_home/android-sdk/tools/bin/sdkmanager
"build-tools;29.0.2"
Add the environment variables to Jenkins configurations.
Go to http://localhost:8080/configure
Add the environment variables:
ANDROID_HOME = /var/jenkins_home/android-sdk
JAVA_HOME = /usr/lib/jvm/java-8-openjdk-amd64
Install the necessary Jenkins plugins.
Go to http://localhost:8080/pluginManager/
Install the following plugins:
Android Emulator Plugin
Android Lint Plugin
Android Signing Plugin
Apache Ant Plugin
Maven Integration Plugin
Configure the Jenkins job
| How to configure the docker image for the Jenkin to create the Android build? | How can we use the Docker image for the Android and Java SDK instead of setting the manual path of Android and Java inside the Manage Jenkin option?
I have done in the Gitlab to create the multiple apk on each Git push with the help of .gitlab-ci.yml. Is same type of file will be use in case of Jenkin? Please check the below links
1). First link
2). Second link
Just like Gitlab apk/build creation I need to perform same operation in Jenkin.
How to use this below docker image of Android SDK 30 which are as below please check it once
I am using this Docker image from this reference, please check it once Click here
| [
"\nPull the Jenkins Docker image from the Docker Hub.\n\n\ndocker pull jenkins/jenkins:lts\n\n\nRun the Docker image and expose the port 8080.\n\n\ndocker run -d -v jenkins_home:/var/jenkins_home -p 8080:8080 --name\njenkins jenkins/jenkins:lts\n\n\nCreate the directory for Android SDK and set the environment variables.\n\n\nmkDIR /var/jenkins_home/android-sdk && export\nANDROID_HOME=/var/jenkins_home/android-sdk\n\n\nDownload and install the Android SDK in the created directory.\n\n\nwget\nhttps://dl.google.com/android/repository/sdk-tools-linux-4333796.zip\n&& unzip sdk-tools-linux-4333796.zip -d /var/jenkins_home/android-sdk\n\n\nDownload and install the Android SDK Platform tools.\n\n\nwget\nhttps://dl.google.com/android/repository/platform-tools_r28.0.1-linux.zip\n&& unzip platform-tools_r28.0.1-linux.zip -d\n/var/jenkins_home/android-sdk\n\n\nInstall the Android SDK build tools.\n\n\n/var/jenkins_home/android-sdk/tools/bin/sdkmanager --list\n/var/jenkins_home/android-sdk/tools/bin/sdkmanager\n\"build-tools;29.0.2\"\n\n\nAdd the environment variables to Jenkins configurations.\n\n\nGo to http://localhost:8080/configure\nAdd the environment variables:\nANDROID_HOME = /var/jenkins_home/android-sdk\nJAVA_HOME = /usr/lib/jvm/java-8-openjdk-amd64\n\n\nInstall the necessary Jenkins plugins.\n\n\nGo to http://localhost:8080/pluginManager/\nInstall the following plugins:\nAndroid Emulator Plugin\nAndroid Lint Plugin\nAndroid Signing Plugin\nApache Ant Plugin\nMaven Integration Plugin\n\n\nConfigure the Jenkins job\n\n"
] | [
0
] | [] | [] | [
"android",
"docker_image",
"jenkins",
"jenkins_pipeline",
"jenkins_plugins"
] | stackoverflow_0068363485_android_docker_image_jenkins_jenkins_pipeline_jenkins_plugins.txt |
Q:
How to change Node Version in Provision Step in Amplify Console
I'm facing the problem that I cant build my Angular app through the AWS Amplify Console:
"You are running version v8.12.0 of Node.js, which is not supported by Angular CLI 8.0+.
The official Node.js version that is supported is 10.9 or greater.
Please visit https://nodejs.org/en/ to find instructions on how to update Node.js."
Now I want to set the default node version of the docker container in the provision step to VERSION_NODE_10 which is already defined in the container.
# Framework Versions
ENV VERSION_NODE_8=8.12.0
ENV VERSION_NODE_6=6
ENV VERSION_NODE_10=10
ENV VERSION_NODE_DEFAULT=$VERSION_NODE_8 <-- Change this to $VERSION_NODE_10
ENV VERSION_RUBY_2_3=2.3.6
ENV VERSION_RUBY_2_4=2.4.3
ENV VERSION_RUBY_DEFAULT=$VERSION_RUBY_2_3
ENV VERSION_HUGO=0.51
ENV VERSION_YARN=1.13.0
amplify.yml:
version: 0.1
backend:
phases:
build:
commands:
- '# Execute Amplify CLI with the helper script'
- amplifyPush --simple
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- node -v
- npm run-script build
artifacts:
baseDirectory: dist/cr-client
files:
- '**/*'
cache:
paths:
- node_modules/**/*
Does anyone know how to change the default?
A:
The correct answer actually isn't the right one.
You should use a custom build image of NodeJS to run your application properly without changing the node version by nvm.
To do that:
Open the "Amplify Console"
Open "All Apps"
Choose the app you're going to change the NodeJS version
Open "Build Settings"
Scroll down to "Build image settings" box and hit "edit" button
At "Build Image" dropdown, choose the option "Build image"
A new input field will appear just below this dropdown, now write the Docker Image Name (same used in Dockefile) you are looking for. For example node:12.16.1
Save
Redeploy any build.
A:
AWS Amplify use nvm to handle node version. Try this:
version: 0.1
backend:
phases:
build:
commands:
- '# Execute Amplify CLI with the helper script'
- amplifyPush --simple
frontend:
phases:
preBuild:
commands:
- nvm use $VERSION_NODE_10
- npm ci
build:
commands:
- nvm use $VERSION_NODE_10
- node -v
- npm run-script build
artifacts:
baseDirectory: dist/cr-client
files:
- '**/*'
cache:
paths:
- node_modules/**/*
A:
Custom build image of NodeJS is a lot of pain.
I usually do this:
App settings > Build Settings > Build Image Settings click Edit.
Live package updates : Node.js version > version.
A:
The accepted answer did not work for me.
The only way to change the node version in the provision step is to have your own build setting.
However, there is an easier way to accomplish this.
In my case, I wanted the latest node 10 version. And adding nvm install in the prebuild step worked.
frontend:
phases:
preBuild:
commands:
- nvm install 10
You can install and use any node version in the amplify by installing it in prebuild steps. Use nvm to switch the node version.
preBuild:
commands:
- nvm install <node version>
Amplify Console output:
# Executing command: nvm install 10
2020-09-09T13:36:19.465Z [INFO]: Downloading and installing node v10.22.0...
2020-09-09T13:36:19.544Z [WARNING]: Downloading https://nodejs.org/dist/v10.22.0/node-v10.22.0-linux-x64.tar.gz...
2020-09-09T13:36:19.664Z [WARNING]: ########
2020-09-09T13:36:19.665Z [WARNING]: 11.9%
2020-09-09T13:36:19.765Z [WARNING]: #######
2020-09-09T13:36:19.765Z [WARNING]: ######################## 43.5%
2020-09-09T13:36:19.832Z [WARNING]: ################################
2020-09-09T13:36:19.832Z [WARNING]: ######################################## 100.0%
2020-09-09T13:36:19.844Z [WARNING]: Computing checksum with sha256sum
2020-09-09T13:36:19.934Z [WARNING]: Checksums matched!
2020-09-09T13:36:20.842Z [INFO]: Now using node v10.22.0 (npm v6.14.6)
A:
Following on @richard's solution, you can put a .nvmrc ($ node --version > .nvmrc) file in the root of your repo with the specific Node version you used to build your project, and use nvm install instead of nvm use $VERSION_NODE_10
A:
Update as of 4th Dec 2022:
What worked out for me was to use a custom build of the NodeJS Docker image on Docker Hub.
Here's what you would need to do:
Go to AWS Amplify
Go to "Build settings"
Scroll down to "Build image settings"
Click on "Edit" button
Under "Build image" click on the dropdown button
Select "Build Image" (by default Linux:2 is selected, at least for me)
In the text field type, for example, "node:18.12.1"
Go back to the latest deploy and click on the "Redeploy this version" app
Roll a J and smoke it, everything should be green now
In that way, you may use whatever build of NodeJS you would need. At least, NodeJS 18 worked for me, I didn't need another.
During build time you can see in the Provision tab they actually use the custom build from Docker Hub:
I tried two of the answers above and they did not work for me.
I didn't think of that. That approach was shared by "dncrews" user on Github.
Check this out.
| How to change Node Version in Provision Step in Amplify Console | I'm facing the problem that I cant build my Angular app through the AWS Amplify Console:
"You are running version v8.12.0 of Node.js, which is not supported by Angular CLI 8.0+.
The official Node.js version that is supported is 10.9 or greater.
Please visit https://nodejs.org/en/ to find instructions on how to update Node.js."
Now I want to set the default node version of the docker container in the provision step to VERSION_NODE_10 which is already defined in the container.
# Framework Versions
ENV VERSION_NODE_8=8.12.0
ENV VERSION_NODE_6=6
ENV VERSION_NODE_10=10
ENV VERSION_NODE_DEFAULT=$VERSION_NODE_8 <-- Change this to $VERSION_NODE_10
ENV VERSION_RUBY_2_3=2.3.6
ENV VERSION_RUBY_2_4=2.4.3
ENV VERSION_RUBY_DEFAULT=$VERSION_RUBY_2_3
ENV VERSION_HUGO=0.51
ENV VERSION_YARN=1.13.0
amplify.yml:
version: 0.1
backend:
phases:
build:
commands:
- '# Execute Amplify CLI with the helper script'
- amplifyPush --simple
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- node -v
- npm run-script build
artifacts:
baseDirectory: dist/cr-client
files:
- '**/*'
cache:
paths:
- node_modules/**/*
Does anyone know how to change the default?
| [
"The correct answer actually isn't the right one.\nYou should use a custom build image of NodeJS to run your application properly without changing the node version by nvm.\nTo do that:\n\nOpen the \"Amplify Console\"\nOpen \"All Apps\"\nChoose the app you're going to change the NodeJS version\nOpen \"Build Settings\"\nScroll down to \"Build image settings\" box and hit \"edit\" button\nAt \"Build Image\" dropdown, choose the option \"Build image\"\nA new input field will appear just below this dropdown, now write the Docker Image Name (same used in Dockefile) you are looking for. For example node:12.16.1\nSave\nRedeploy any build.\n\n",
"AWS Amplify use nvm to handle node version. Try this:\nversion: 0.1\nbackend:\n phases:\n build:\n commands:\n - '# Execute Amplify CLI with the helper script'\n - amplifyPush --simple\nfrontend:\n phases:\n preBuild:\n commands:\n - nvm use $VERSION_NODE_10\n - npm ci\n build:\n commands:\n - nvm use $VERSION_NODE_10\n - node -v\n - npm run-script build\n artifacts:\n baseDirectory: dist/cr-client\n files:\n - '**/*'\n cache:\n paths:\n - node_modules/**/*\n\n",
"Custom build image of NodeJS is a lot of pain.\nI usually do this:\nApp settings > Build Settings > Build Image Settings click Edit.\nLive package updates : Node.js version > version.\n\n",
"The accepted answer did not work for me.\nThe only way to change the node version in the provision step is to have your own build setting.\nHowever, there is an easier way to accomplish this.\nIn my case, I wanted the latest node 10 version. And adding nvm install in the prebuild step worked.\nfrontend:\n phases:\n preBuild:\n commands:\n - nvm install 10\n\nYou can install and use any node version in the amplify by installing it in prebuild steps. Use nvm to switch the node version.\npreBuild:\n commands:\n - nvm install <node version>\n\nAmplify Console output:\n# Executing command: nvm install 10\n\n2020-09-09T13:36:19.465Z [INFO]: Downloading and installing node v10.22.0...\n2020-09-09T13:36:19.544Z [WARNING]: Downloading https://nodejs.org/dist/v10.22.0/node-v10.22.0-linux-x64.tar.gz...\n2020-09-09T13:36:19.664Z [WARNING]: ########\n2020-09-09T13:36:19.665Z [WARNING]: 11.9%\n2020-09-09T13:36:19.765Z [WARNING]: #######\n2020-09-09T13:36:19.765Z [WARNING]: ######################## 43.5%\n2020-09-09T13:36:19.832Z [WARNING]: ################################\n2020-09-09T13:36:19.832Z [WARNING]: ######################################## 100.0%\n2020-09-09T13:36:19.844Z [WARNING]: Computing checksum with sha256sum\n2020-09-09T13:36:19.934Z [WARNING]: Checksums matched!\n\n2020-09-09T13:36:20.842Z [INFO]: Now using node v10.22.0 (npm v6.14.6)\n\n",
"Following on @richard's solution, you can put a .nvmrc ($ node --version > .nvmrc) file in the root of your repo with the specific Node version you used to build your project, and use nvm install instead of nvm use $VERSION_NODE_10\n",
"Update as of 4th Dec 2022:\nWhat worked out for me was to use a custom build of the NodeJS Docker image on Docker Hub.\nHere's what you would need to do:\n\nGo to AWS Amplify\nGo to \"Build settings\"\nScroll down to \"Build image settings\"\nClick on \"Edit\" button\nUnder \"Build image\" click on the dropdown button\nSelect \"Build Image\" (by default Linux:2 is selected, at least for me)\nIn the text field type, for example, \"node:18.12.1\"\nGo back to the latest deploy and click on the \"Redeploy this version\" app\nRoll a J and smoke it, everything should be green now\n\nIn that way, you may use whatever build of NodeJS you would need. At least, NodeJS 18 worked for me, I didn't need another.\nDuring build time you can see in the Provision tab they actually use the custom build from Docker Hub:\n\n\nI tried two of the answers above and they did not work for me.\n\nI didn't think of that. That approach was shared by \"dncrews\" user on Github.\nCheck this out.\n"
] | [
37,
30,
11,
5,
1,
0
] | [] | [] | [
"amazon_web_services",
"aws_amplify",
"node.js"
] | stackoverflow_0056444337_amazon_web_services_aws_amplify_node.js.txt |
Q:
How to stop VSCode from adding 'package' to java files
Background
I installed all the VSCode 'Extension Pack for Java' when I started working with Java, this included:
Debugger for Java
Project Manager for Java
Maven for Java
IntelliCode
Test Runner for Java
Language Support for Java(TM) by RedHat
Problem
The Extension "Language Support for Java(TM) by Red Hat" will attempt to add a package to each file you are working in automatically. However for the class I am in the grading tool asks you remove 'package' from the files before submitting. I can't seem to find a way to disable this and I am not as familiar with editing VSCode settings.
What I have tried
I tried just disabling the extensions but now I don't have access to the required .jars since disabling this extension also disables the ability to add .jars to your class path via IDE.
A:
This may not be the best solution but for some reason if I disable then enable "Language Support for Java(TM) by Red Hat" it stops prompting to add package...
Not sure if this is the recommended solution so curious if anyone else knows a better way.
| How to stop VSCode from adding 'package' to java files | Background
I installed all the VSCode 'Extension Pack for Java' when I started working with Java, this included:
Debugger for Java
Project Manager for Java
Maven for Java
IntelliCode
Test Runner for Java
Language Support for Java(TM) by RedHat
Problem
The Extension "Language Support for Java(TM) by Red Hat" will attempt to add a package to each file you are working in automatically. However for the class I am in the grading tool asks you remove 'package' from the files before submitting. I can't seem to find a way to disable this and I am not as familiar with editing VSCode settings.
What I have tried
I tried just disabling the extensions but now I don't have access to the required .jars since disabling this extension also disables the ability to add .jars to your class path via IDE.
| [
"This may not be the best solution but for some reason if I disable then enable \"Language Support for Java(TM) by Red Hat\" it stops prompting to add package...\nNot sure if this is the recommended solution so curious if anyone else knows a better way.\n"
] | [
0
] | [] | [] | [
"java",
"redhat",
"visual_studio_code",
"vscode_extensions"
] | stackoverflow_0074671558_java_redhat_visual_studio_code_vscode_extensions.txt |
Q:
Issues using run-ios with React Native
It seems that once every other week I have the same issue where my React Native project stops building and won't open in Xcode, and I wanted to know what some fixes could be for this. When I try and build in Visual Studio Code the app gets stuck at the β Building the app message. And when I try opening the workspace in Xcode, Xcode stops responding and it gets stuck on the spinning rainbow wheel. For some reason, npx react-native start works just fine, the issue occurs when using npx react-native run-ios.
When this happens it takes me hours to troubleshoot and I can't find a consistent fix for this issue. Does anyone have experience with this and know a solution?
A:
Here are some potential fixes for issues with running the run-ios command in React Native:
Try clearing the React Native packager cache by running the npx react-native start --reset-cache command and then re-running npx react-native run-ios.
Check for any outdated or conflicting dependencies in your project by running npm outdated and npm ls to see if any packages need to be updated or removed.
If you are using Xcode, try cleaning the build folder by selecting "Product" > "Clean Build Folder" in the Xcode menu and then re-running npx react-native run-ios.
Restart your computer and try running the run-ios command again.
If the issue persists, try uninstalling and re-installing React Native and its dependencies by running npm uninstall -g react-native-cli and then npm install -g react-native-cli.
A:
It appears that the issue results from Xcode's way of handling iCloud files. I was able to resolve the issue by moving my project to a folder that is not in my iCloud Drive.
| Issues using run-ios with React Native | It seems that once every other week I have the same issue where my React Native project stops building and won't open in Xcode, and I wanted to know what some fixes could be for this. When I try and build in Visual Studio Code the app gets stuck at the β Building the app message. And when I try opening the workspace in Xcode, Xcode stops responding and it gets stuck on the spinning rainbow wheel. For some reason, npx react-native start works just fine, the issue occurs when using npx react-native run-ios.
When this happens it takes me hours to troubleshoot and I can't find a consistent fix for this issue. Does anyone have experience with this and know a solution?
| [
"Here are some potential fixes for issues with running the run-ios command in React Native:\n\nTry clearing the React Native packager cache by running the npx react-native start --reset-cache command and then re-running npx react-native run-ios.\nCheck for any outdated or conflicting dependencies in your project by running npm outdated and npm ls to see if any packages need to be updated or removed.\nIf you are using Xcode, try cleaning the build folder by selecting \"Product\" > \"Clean Build Folder\" in the Xcode menu and then re-running npx react-native run-ios.\nRestart your computer and try running the run-ios command again.\nIf the issue persists, try uninstalling and re-installing React Native and its dependencies by running npm uninstall -g react-native-cli and then npm install -g react-native-cli.\n\n",
"It appears that the issue results from Xcode's way of handling iCloud files. I was able to resolve the issue by moving my project to a folder that is not in my iCloud Drive.\n"
] | [
0,
0
] | [] | [] | [
"ios",
"mobile",
"react_native",
"reactjs",
"xcode"
] | stackoverflow_0074671484_ios_mobile_react_native_reactjs_xcode.txt |
Q:
Cannot run query: project does not have the reservation in the data region - for a few minutes after removing the reservation
I am using flexible reservations for bigquery and turn them on/off for larger jobs. However after turning them off and (somewhere else) a query is started, it will fail with the "Cannot run query: project does not have the reservation in the data region" error. This happens for about 20 seconds, and then everything works fine.
What I do for turning flex reservations on is:
create a commitment
create a reservation
create an assignment
wait 60 seconds
(this works fine)
What I do for turning flex reservations off is:
remove the assignment
remove the reservation
remove the commitment
Now we are entering a short "twilight" zone where the error can happen. After some time, everything starts working normally
Is this normal behaviour? Is there anything in the removement procedure that can be done to avoid this?
A:
You can do the following to prevent that issue.
Delete the assignment
Wait for 2-3 minutes
Remove Reservation
Remove Commitment
I tested this and it worked for me.
| Cannot run query: project does not have the reservation in the data region - for a few minutes after removing the reservation | I am using flexible reservations for bigquery and turn them on/off for larger jobs. However after turning them off and (somewhere else) a query is started, it will fail with the "Cannot run query: project does not have the reservation in the data region" error. This happens for about 20 seconds, and then everything works fine.
What I do for turning flex reservations on is:
create a commitment
create a reservation
create an assignment
wait 60 seconds
(this works fine)
What I do for turning flex reservations off is:
remove the assignment
remove the reservation
remove the commitment
Now we are entering a short "twilight" zone where the error can happen. After some time, everything starts working normally
Is this normal behaviour? Is there anything in the removement procedure that can be done to avoid this?
| [
"You can do the following to prevent that issue.\n\nDelete the assignment\nWait for 2-3 minutes\nRemove Reservation\nRemove Commitment\n\nI tested this and it worked for me.\n"
] | [
0
] | [] | [] | [
"google_bigquery"
] | stackoverflow_0072457987_google_bigquery.txt |
Q:
Value in checkpoint could not be found in the restored object: (root).optimizer.iter
So i was using the pre-trained weight from this link: http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz
then i copied the pipeline.config from the download link to my folder because i want to change the optimizer to adam to train on my own dataset (the pipeline in the link is using momentum_optimizer)
Here is my code for my pipeline.config to train:
optimizer {
adam_optimizer {
learning_rate {
cosine_decay_learning_rate {
learning_rate_base: 0.01
total_steps: 50000
warmup_learning_rate: 0.026666
warmup_steps: 1000
}
}
epsilon: 1e-8
}
use_moving_average: false
}
but then the cmd promt hit me with this:
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.iter
W0419 23:47:07.776149 17436 util.py:194] Value in checkpoint could not be found in the restored object: (root).optimizer.iter
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.decay
W0419 23:47:07.777309 17436 util.py:194] Value in checkpoint could not be found in the restored object: (root).optimizer.decay
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.momentum
W0419 23:47:07.779311 17436 util.py:194] Value in checkpoint could not be found in the restored object: (root).optimizer.momentum
Can anyone explain please thank you
[1]: https://i.stack.imgur.com/BBmVA.png
A:
I had the same mistake while executing the following lines:
python Tensorflow\models\research\object_detection\model_main_tf2.py --model_dir=Tensorflow\workspace\models\my_ssd_mobnet --pipeline_config_path=Tensorflow\workspace\models\my_ssd_mobnet\pipeline.config --num_train_steps=2000
Changing the number of steps worked for me!
A:
what worked for me was to go into the model checkpoints folder and deleting all the previous checkpoints, leaving only the pipeline config file there.
A:
what worked for me was to go into the model checkpoints folder and deleting all the previous checkpoints, leaving only the pipeline config file there.
Para mi si funciono esta manera, lo que haces es de que te vas a la carpeta de my_ssd_mobnet y eliminas los checkpoint y solo dejas el archivo pipline.config y corres el comando: python Tensorflow\models\research\object_detection\model_main_tf2.py --model_dir=Tensorflow\workspace\models\my_ssd_mobnet --pipeline_config_path=Tensorflow\workspace\models\my_ssd_mobnet\pipeline.config --num_train_steps=2000
A:
model.load_weights(MY_CHECKPOINT_FILE).expect_partial() has been working for me
| Value in checkpoint could not be found in the restored object: (root).optimizer.iter | So i was using the pre-trained weight from this link: http://download.tensorflow.org/models/object_detection/tf2/20200711/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8.tar.gz
then i copied the pipeline.config from the download link to my folder because i want to change the optimizer to adam to train on my own dataset (the pipeline in the link is using momentum_optimizer)
Here is my code for my pipeline.config to train:
optimizer {
adam_optimizer {
learning_rate {
cosine_decay_learning_rate {
learning_rate_base: 0.01
total_steps: 50000
warmup_learning_rate: 0.026666
warmup_steps: 1000
}
}
epsilon: 1e-8
}
use_moving_average: false
}
but then the cmd promt hit me with this:
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.iter
W0419 23:47:07.776149 17436 util.py:194] Value in checkpoint could not be found in the restored object: (root).optimizer.iter
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.decay
W0419 23:47:07.777309 17436 util.py:194] Value in checkpoint could not be found in the restored object: (root).optimizer.decay
WARNING:tensorflow:Value in checkpoint could not be found in the restored object: (root).optimizer.momentum
W0419 23:47:07.779311 17436 util.py:194] Value in checkpoint could not be found in the restored object: (root).optimizer.momentum
Can anyone explain please thank you
[1]: https://i.stack.imgur.com/BBmVA.png
| [
"I had the same mistake while executing the following lines:\npython Tensorflow\\models\\research\\object_detection\\model_main_tf2.py --model_dir=Tensorflow\\workspace\\models\\my_ssd_mobnet --pipeline_config_path=Tensorflow\\workspace\\models\\my_ssd_mobnet\\pipeline.config --num_train_steps=2000\n\nChanging the number of steps worked for me!\n",
"what worked for me was to go into the model checkpoints folder and deleting all the previous checkpoints, leaving only the pipeline config file there.\n",
"what worked for me was to go into the model checkpoints folder and deleting all the previous checkpoints, leaving only the pipeline config file there.\nPara mi si funciono esta manera, lo que haces es de que te vas a la carpeta de my_ssd_mobnet y eliminas los checkpoint y solo dejas el archivo pipline.config y corres el comando: python Tensorflow\\models\\research\\object_detection\\model_main_tf2.py --model_dir=Tensorflow\\workspace\\models\\my_ssd_mobnet --pipeline_config_path=Tensorflow\\workspace\\models\\my_ssd_mobnet\\pipeline.config --num_train_steps=2000\n",
"model.load_weights(MY_CHECKPOINT_FILE).expect_partial() has been working for me\n"
] | [
0,
0,
0,
0
] | [] | [] | [
"computer_vision",
"machine_learning",
"object_detection",
"tensorflow"
] | stackoverflow_0071929036_computer_vision_machine_learning_object_detection_tensorflow.txt |
Q:
PostgreSQL: Cant match function in DLL
I created a custom DLL containing following function:
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
PG_MODULE_MAGIC;
/* by value */
PG_FUNCTION_INFO_V1(add_one);
Datum
add_one(PG_FUNCTION_ARGS)
{
int32 arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(arg + 1);
}
But when i try to create it in PgAdmin4 using next command:
CREATE FUNCTION add_one(INTEGER) RETURNS INTEGER
AS '$libdir/new_func', 'add_one'
LANGUAGE C STRICT ;
It says:
ERROR:cannot match function "add_one" in file "C:/Program Files/PostgreSQL/14/lib/new_func.dll"
SQL-state: 42883
DLL was compiled according to this guide.
Is there any way to check the list of functions in a .dll using PGAdmin? Or how can i try to solve this?
A:
After some time i found out the reason why my DLL could not been read.
I used wrong compiler.
First i used compiler from this site. Then i followed the guide in Question.
Few days ago I found another MinGW compiler. And finally everything works.
Compiler i used for the last time here.
| PostgreSQL: Cant match function in DLL | I created a custom DLL containing following function:
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
PG_MODULE_MAGIC;
/* by value */
PG_FUNCTION_INFO_V1(add_one);
Datum
add_one(PG_FUNCTION_ARGS)
{
int32 arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(arg + 1);
}
But when i try to create it in PgAdmin4 using next command:
CREATE FUNCTION add_one(INTEGER) RETURNS INTEGER
AS '$libdir/new_func', 'add_one'
LANGUAGE C STRICT ;
It says:
ERROR:cannot match function "add_one" in file "C:/Program Files/PostgreSQL/14/lib/new_func.dll"
SQL-state: 42883
DLL was compiled according to this guide.
Is there any way to check the list of functions in a .dll using PGAdmin? Or how can i try to solve this?
| [
"After some time i found out the reason why my DLL could not been read.\nI used wrong compiler.\nFirst i used compiler from this site. Then i followed the guide in Question.\nFew days ago I found another MinGW compiler. And finally everything works.\nCompiler i used for the last time here.\n"
] | [
1
] | [] | [] | [
"pgadmin_4",
"postgresql"
] | stackoverflow_0074417420_pgadmin_4_postgresql.txt |
Q:
Django AWS S3 media files
Working with Django, I am trying to use AWS S3 storage only for uploading and reading files which is working well at MEDIA_URL but the problem when using AWS S3 is that somehow I am losing reference to STATIC_URL where CSS and javascript files are
I only want MEDIA_URL pointing to S3 and keep my STATIC_URL away from AWS S3... Is that possible?
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
if DEBUG:
MEDIA_ROOT = os.environ['MEDIA_ROOT']
MEDIA_URL = os.environ['MEDIA_URL']
else:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
MEDIA_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
A:
Change STATIC_URL to "STATIC_ROOT = os.path.join(BASE_DIR,'static')". Could use decouple to hide those variables too.
| Django AWS S3 media files | Working with Django, I am trying to use AWS S3 storage only for uploading and reading files which is working well at MEDIA_URL but the problem when using AWS S3 is that somehow I am losing reference to STATIC_URL where CSS and javascript files are
I only want MEDIA_URL pointing to S3 and keep my STATIC_URL away from AWS S3... Is that possible?
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
if DEBUG:
MEDIA_ROOT = os.environ['MEDIA_ROOT']
MEDIA_URL = os.environ['MEDIA_URL']
else:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')
MEDIA_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
| [
"Change STATIC_URL to \"STATIC_ROOT = os.path.join(BASE_DIR,'static')\". Could use decouple to hide those variables too.\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"amazon_web_services",
"django",
"python"
] | stackoverflow_0024734733_amazon_s3_amazon_web_services_django_python.txt |
Q:
Minibash in C, problem making pipes between execvp and parent proccess
I have to do this as a university project so I cant share the whole code, im sorry for that.
I have to create a function called "read" that enables the user to create new env variables, thats the easy part. The problem comes when I call that function as the last one of the commands array e.g "ls | grep aux.txt | read a" this should give the env var A the value aux.txt, the problem is that it get stuck in the
fgets(value, sizeof(value),stdin);
and I cant even recover the terminal.
Thanks in advance for the help if you need more info about the problem I will happily give it.
I can't reproduce exactly the main function as there are parts that are not mine but I hope this helps:
char **argvv;
int fd[2][2];
int pid;
int main(int argc, char ***argvv) {
argvv[0][0] = "echo";
argvv[0][1] = "elpmaxe";
argvv[1][0] = "rev";
argvv[2][0] = "read";
argvv[2][1] = "a";
for (int i = 0; i < 2; i++) {
pipe(fd[i]);
}
for(int i = 0; i< 3; i++){
pid = fork();
if(pid == 0){
if(i ==0){
dup2(fd[0][1], 1);
fun_close(fd);
execvp(argvv[0][0], argvv[0]);
}
if(i == 1){
dup2(fd[0][0], 0);
dup2(fd[1][1], 1);
fun_close(fd);
execvp(argvv[1][0], argvv[0]);
}
}else{
if(i == 2){
close(fd[0][1]);
close(fd[0][0]);
fun_read("read a", 3, fd[1]);
}
}
}
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child %d exited with status 0x%.4X\n", corpse, status);
return 0;
void fun_close(int **fd){
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
}
And here is the fun_read:
int fun_read(char **command, int argc, int fd[]){
char **env_varv;
char value[1024];
char last_var[1024];
long size = 0;
char *token;
int status;
char *delim = " \t\n";
env_varv = malloc((argc-1) * sizeof(char *));
for(int i = 1; i < argc; i++){
env_varv[i-1] = strdup(command[i]);
wait(status);
}
if (fd[0] !=0){
printf("%d\n", fd[0]);
dup2(fd[0],0);
close(fd[0]);
close(fd[1]);
}
fgets(value, sizeof(value),stdin);
int i = 0;
token = strtok(value, delim);
last_var[0] = '\0';
while(token != NULL){
if(i == argc-2){
while (token != NULL){
strcat(last_var,token);
setenv(env_varv[i],last_var,1);
token = strtok(NULL,delim);
strcat(last_var," ");
}
}
else if (env_varv[i] != NULL){
setenv(env_varv[i],token,1);
token = strtok(NULL,delim);
i++;
}
else{
break;
}
}
return 0;
The program should put an envariomental variable called a with the value of example.
postscript: it seems like there is no problem if the previous command is a builtin "echo hi | echo hi2 | read a" $a=hi2
Sincerely I have tried all, changing the pipes doesnt work, changing fgets for read doesn't help either. Is the only part of the code I haven't been able to fix
A:
This fragment of code shows some problems:
char ***argvv;
int fd[2][2];
int pid;
int main(int argc, char ***argvv) {
argvv[0][0] = "echo";
argvv[0][1] = "elpmaxe";
argvv[1][0] = "rev";
argvv[2][0] = "read";
argvv[2][1] = "a";
for (int i = 0; i < 2; i++) {
pipe(fd[i]);
}
for(int i = 0; i< 3; i++){
pid = fork();
if(pid == 0){
if(i ==0){
close(fd[0][0]);
close(fd[1][1]);
close(fd[1][0]);
dup2(fd[0][1], 1);
execvp(argvv[0][0], argvv[0]);
}
if(i = 1){
close(fd[0][1]);
close(fd[1][0]);
dup2(fd[0][0], 0);
dup2(fd[1][1], 1);
execvp(argvv[1][0], argvv[0]);
}
if(i = 2){
close(fd[0][1]);
close(fd[0][0]);
close(fd[1][1]);
dup2(fd[1][0], 0);
fun_read("read a", 3, fd[1]);
}
}
}
Rule of Thumb
You aren't closing enough pipe file descriptors in any of the processes.
If you dup2()
one end of a pipe to standard input or standard output, close both of the
original file descriptors returned by
pipe()
as soon as possible.
In particular, you should close them before using any of the
exec*()
family of functions.
The rule also applies if you duplicate the descriptors with either
dup()
or
fcntl()
with F_DUPFD or F_DUPFD_CLOEXEC.
Other comments on the use of pipes
If the parent process will not communicate with any of its children via
the pipe, it must ensure that it closes both ends of the pipe early
enough (before waiting, for example) so that its children can receive
EOF indications on read (or get SIGPIPE signals or write errors on
write), rather than blocking indefinitely.
Even if the parent uses the pipe without using dup2(), it should
normally close at least one end of the pipe β it is extremely rare for
a program to read and write on both ends of a single pipe.
Note that the O_CLOEXEC option to
open(),
and the FD_CLOEXEC and F_DUPFD_CLOEXEC options to fcntl() can also factor
into this discussion.
If you use
posix_spawn()
and its extensive family of support functions (21 functions in total),
you will need to review how to close file descriptors in the spawned process
(posix_spawn_file_actions_addclose(),
etc.).
Note that using dup2(a, b) is safer than using close(b); dup(a);
for a variety of reasons.
One is that if you want to force the file descriptor to a larger than
usual number, dup2() is the only sensible way to do that.
Another is that if a is the same as b (e.g. both 0), then dup2()
handles it correctly (it doesn't close b before duplicating a)
whereas the separate close() and dup() fails horribly.
This is an unlikely, but not impossible, circumstance.
Analyzing your code
The parent process has the pipes open; if the commands are reading from the pipes, they won't get EOF until the parent process closes them. Although you close most of the pipes in the child processes, you don't close those that you duplicate to the standard I/O channels β and yet that is required too.
Note that if (i = 1) should be if (i == 1), and if (i = 2) should be if (i == 2). The first of those bugs prevents your fun_read() from being invoked β which is why it isn't responding. Using diagnostic printing to standard error would confirm that fun_read() is never called.
So, at bare minimum, you need to have code like this:
char ***argvv;
int fd[2][2];
int pid;
int main(int argc, char ***argvv)
{
argvv[0][0] = "echo";
argvv[0][1] = "elpmaxe";
argvv[1][0] = "rev";
argvv[2][0] = "read";
argvv[2][1] = "a";
for (int i = 0; i < 2; i++)
{
pipe(fd[i]);
}
for (int i = 0; i < 3; i++)
{
pid = fork();
if (pid == 0)
{
if (i == 0)
{
dup2(fd[0][1], 1);
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
execvp(argvv[0][0], argvv[0]);
fprintf(stderr, "failed to execute %s\n", argvv[0][0]);
exit(EXIT_FAILURE);
}
if (i == 1)
{
dup2(fd[0][0], 0);
dup2(fd[1][1], 1);
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
execvp(argvv[1][0], argvv[0]);
fprintf(stderr, "failed to execute %s\n", argvv[1][0]);
exit(EXIT_FAILURE);
}
if (i == 2)
{
dup2(fd[1][0], 0);
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
fun_read("read a", 3, fd[1]);
exit(EXIT_SUCCESS);
}
}
}
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
/* wait loop here - and not before */
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child %d exited with status 0x%.4X\n", corpse, status);
return 0;
}
Note that it is important to handle failure to execute. And error messages should be reported to standard error, not to standard output.
Given that the same sequence of 4 calls to close() is made 4 times, a function to do the job seems appropriate. You could make it:
static inline void close_pipes(int fd[2][2])
{
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
}
There is a decent chance the compiler will inline the function, but it is easier to see that the same 4 descriptors are closed if one function always does the closing. For bigger arrays of pipes (more processes), you'd have a loop inside the close_pipes() function with a counter as well as the array.
There are still some issues to be resolved, notably with the fun_read() function. The fd[1] file descriptors were both closed, so passing those to fun_read() doesn't seem likely to be useful. Since fun_read() is executed in a separate process, any changes made by fun_read() won't be reflected in the parent process. There are probably other problems too.
AFAICT, on looking at fun_read() more closely, the fd argument should not be needed at all. The paragraph of code:
if (fd[0] != 0) {
printf("%d\n", fd[0]);
dup2(fd[0], 0);
}
is not useful. You've already redirected standard input so it comes from the pipe and then closed the pipe file descriptor. This paragraph then changes standard input to come from the closed descriptor, which isn't going to help anything. But none of this helps you with the fact that anything done by fun_read() is done in a child process of your shell, so the environment in the main shell is not going to be affected.
| Minibash in C, problem making pipes between execvp and parent proccess | I have to do this as a university project so I cant share the whole code, im sorry for that.
I have to create a function called "read" that enables the user to create new env variables, thats the easy part. The problem comes when I call that function as the last one of the commands array e.g "ls | grep aux.txt | read a" this should give the env var A the value aux.txt, the problem is that it get stuck in the
fgets(value, sizeof(value),stdin);
and I cant even recover the terminal.
Thanks in advance for the help if you need more info about the problem I will happily give it.
I can't reproduce exactly the main function as there are parts that are not mine but I hope this helps:
char **argvv;
int fd[2][2];
int pid;
int main(int argc, char ***argvv) {
argvv[0][0] = "echo";
argvv[0][1] = "elpmaxe";
argvv[1][0] = "rev";
argvv[2][0] = "read";
argvv[2][1] = "a";
for (int i = 0; i < 2; i++) {
pipe(fd[i]);
}
for(int i = 0; i< 3; i++){
pid = fork();
if(pid == 0){
if(i ==0){
dup2(fd[0][1], 1);
fun_close(fd);
execvp(argvv[0][0], argvv[0]);
}
if(i == 1){
dup2(fd[0][0], 0);
dup2(fd[1][1], 1);
fun_close(fd);
execvp(argvv[1][0], argvv[0]);
}
}else{
if(i == 2){
close(fd[0][1]);
close(fd[0][0]);
fun_read("read a", 3, fd[1]);
}
}
}
int corpse;
int status;
while ((corpse = wait(&status)) > 0)
printf("Child %d exited with status 0x%.4X\n", corpse, status);
return 0;
void fun_close(int **fd){
close(fd[0][0]);
close(fd[0][1]);
close(fd[1][0]);
close(fd[1][1]);
}
And here is the fun_read:
int fun_read(char **command, int argc, int fd[]){
char **env_varv;
char value[1024];
char last_var[1024];
long size = 0;
char *token;
int status;
char *delim = " \t\n";
env_varv = malloc((argc-1) * sizeof(char *));
for(int i = 1; i < argc; i++){
env_varv[i-1] = strdup(command[i]);
wait(status);
}
if (fd[0] !=0){
printf("%d\n", fd[0]);
dup2(fd[0],0);
close(fd[0]);
close(fd[1]);
}
fgets(value, sizeof(value),stdin);
int i = 0;
token = strtok(value, delim);
last_var[0] = '\0';
while(token != NULL){
if(i == argc-2){
while (token != NULL){
strcat(last_var,token);
setenv(env_varv[i],last_var,1);
token = strtok(NULL,delim);
strcat(last_var," ");
}
}
else if (env_varv[i] != NULL){
setenv(env_varv[i],token,1);
token = strtok(NULL,delim);
i++;
}
else{
break;
}
}
return 0;
The program should put an envariomental variable called a with the value of example.
postscript: it seems like there is no problem if the previous command is a builtin "echo hi | echo hi2 | read a" $a=hi2
Sincerely I have tried all, changing the pipes doesnt work, changing fgets for read doesn't help either. Is the only part of the code I haven't been able to fix
| [
"This fragment of code shows some problems:\nchar ***argvv;\nint fd[2][2];\nint pid;\nint main(int argc, char ***argvv) {\nargvv[0][0] = \"echo\";\nargvv[0][1] = \"elpmaxe\";\nargvv[1][0] = \"rev\";\nargvv[2][0] = \"read\";\nargvv[2][1] = \"a\";\nfor (int i = 0; i < 2; i++) {\n pipe(fd[i]);\n}\nfor(int i = 0; i< 3; i++){\n pid = fork();\n if(pid == 0){\n if(i ==0){\n close(fd[0][0]);\n close(fd[1][1]);\n close(fd[1][0]);\n dup2(fd[0][1], 1);\n execvp(argvv[0][0], argvv[0]);\n }\n if(i = 1){\n close(fd[0][1]);\n close(fd[1][0]);\n dup2(fd[0][0], 0);\n dup2(fd[1][1], 1);\n execvp(argvv[1][0], argvv[0]);\n }\n if(i = 2){\n close(fd[0][1]);\n close(fd[0][0]);\n close(fd[1][1]);\n dup2(fd[1][0], 0);\n fun_read(\"read a\", 3, fd[1]);\n }\n }\n}\n\n\nRule of Thumb\nYou aren't closing enough pipe file descriptors in any of the processes.\nIf you dup2()\none end of a pipe to standard input or standard output, close both of the\noriginal file descriptors returned by\npipe()\nas soon as possible.\nIn particular, you should close them before using any of the\nexec*()\nfamily of functions.\nThe rule also applies if you duplicate the descriptors with either\ndup()\nor\nfcntl()\nwith F_DUPFD or F_DUPFD_CLOEXEC.\n\nOther comments on the use of pipes\nIf the parent process will not communicate with any of its children via\nthe pipe, it must ensure that it closes both ends of the pipe early\nenough (before waiting, for example) so that its children can receive\nEOF indications on read (or get SIGPIPE signals or write errors on\nwrite), rather than blocking indefinitely.\nEven if the parent uses the pipe without using dup2(), it should\nnormally close at least one end of the pipe β it is extremely rare for\na program to read and write on both ends of a single pipe.\nNote that the O_CLOEXEC option to\nopen(),\nand the FD_CLOEXEC and F_DUPFD_CLOEXEC options to fcntl() can also factor\ninto this discussion.\nIf you use\nposix_spawn()\nand its extensive family of support functions (21 functions in total),\nyou will need to review how to close file descriptors in the spawned process\n(posix_spawn_file_actions_addclose(),\netc.).\nNote that using dup2(a, b) is safer than using close(b); dup(a);\nfor a variety of reasons.\nOne is that if you want to force the file descriptor to a larger than\nusual number, dup2() is the only sensible way to do that.\nAnother is that if a is the same as b (e.g. both 0), then dup2()\nhandles it correctly (it doesn't close b before duplicating a)\nwhereas the separate close() and dup() fails horribly.\nThis is an unlikely, but not impossible, circumstance.\n\nAnalyzing your code\nThe parent process has the pipes open; if the commands are reading from the pipes, they won't get EOF until the parent process closes them. Although you close most of the pipes in the child processes, you don't close those that you duplicate to the standard I/O channels β and yet that is required too.\nNote that if (i = 1) should be if (i == 1), and if (i = 2) should be if (i == 2). The first of those bugs prevents your fun_read() from being invoked β which is why it isn't responding. Using diagnostic printing to standard error would confirm that fun_read() is never called.\nSo, at bare minimum, you need to have code like this:\nchar ***argvv;\nint fd[2][2];\nint pid;\n\nint main(int argc, char ***argvv)\n{\n argvv[0][0] = \"echo\";\n argvv[0][1] = \"elpmaxe\";\n argvv[1][0] = \"rev\";\n argvv[2][0] = \"read\";\n argvv[2][1] = \"a\";\n for (int i = 0; i < 2; i++)\n {\n pipe(fd[i]);\n }\n for (int i = 0; i < 3; i++)\n {\n pid = fork();\n if (pid == 0)\n {\n if (i == 0)\n {\n dup2(fd[0][1], 1);\n close(fd[0][0]);\n close(fd[0][1]);\n close(fd[1][0]);\n close(fd[1][1]);\n execvp(argvv[0][0], argvv[0]);\n fprintf(stderr, \"failed to execute %s\\n\", argvv[0][0]);\n exit(EXIT_FAILURE);\n }\n if (i == 1)\n {\n dup2(fd[0][0], 0);\n dup2(fd[1][1], 1);\n close(fd[0][0]);\n close(fd[0][1]);\n close(fd[1][0]);\n close(fd[1][1]);\n execvp(argvv[1][0], argvv[0]);\n fprintf(stderr, \"failed to execute %s\\n\", argvv[1][0]);\n exit(EXIT_FAILURE);\n }\n if (i == 2)\n {\n dup2(fd[1][0], 0);\n close(fd[0][0]);\n close(fd[0][1]);\n close(fd[1][0]);\n close(fd[1][1]);\n fun_read(\"read a\", 3, fd[1]);\n exit(EXIT_SUCCESS);\n }\n }\n }\n close(fd[0][0]);\n close(fd[0][1]);\n close(fd[1][0]);\n close(fd[1][1]);\n\n /* wait loop here - and not before */\n int corpse;\n int status;\n while ((corpse = wait(&status)) > 0)\n printf(\"Child %d exited with status 0x%.4X\\n\", corpse, status);\n\n return 0;\n}\n\nNote that it is important to handle failure to execute. And error messages should be reported to standard error, not to standard output.\nGiven that the same sequence of 4 calls to close() is made 4 times, a function to do the job seems appropriate. You could make it:\nstatic inline void close_pipes(int fd[2][2])\n{\n close(fd[0][0]);\n close(fd[0][1]);\n close(fd[1][0]);\n close(fd[1][1]);\n}\n\nThere is a decent chance the compiler will inline the function, but it is easier to see that the same 4 descriptors are closed if one function always does the closing. For bigger arrays of pipes (more processes), you'd have a loop inside the close_pipes() function with a counter as well as the array.\nThere are still some issues to be resolved, notably with the fun_read() function. The fd[1] file descriptors were both closed, so passing those to fun_read() doesn't seem likely to be useful. Since fun_read() is executed in a separate process, any changes made by fun_read() won't be reflected in the parent process. There are probably other problems too.\nAFAICT, on looking at fun_read() more closely, the fd argument should not be needed at all. The paragraph of code:\nif (fd[0] != 0) {\n printf(\"%d\\n\", fd[0]);\n dup2(fd[0], 0);\n}\n\nis not useful. You've already redirected standard input so it comes from the pipe and then closed the pipe file descriptor. This paragraph then changes standard input to come from the closed descriptor, which isn't going to help anything. But none of this helps you with the fact that anything done by fun_read() is done in a child process of your shell, so the environment in the main shell is not going to be affected.\n"
] | [
2
] | [] | [] | [
"c",
"environment_variables",
"pipe",
"shell"
] | stackoverflow_0074670178_c_environment_variables_pipe_shell.txt |
Q:
Convert a node module to ESM
My project uses ES6 modules in a browser, but I need to use a library that is made using Node module then webpacked: cytoscape-dagre or cytoscape-klay. Those are extensions for Cytoscape which itself has an ESM port that works just fine. I am finding a lot of resources to go from ES6 to anything else, but not the other way around. Does anyone know where I should look?
A:
There are online services for this, such as esm.sh:
import cytoscapeDagre from 'https://esm.sh/cytoscape-dagre';
import cytoscapeKlay from 'https://esm.sh/cytoscape-klay';
If youβd like to build it and host it yourself, you could do what esm.sh does and use esbuild: https://github.com/evanw/esbuild.
| Convert a node module to ESM | My project uses ES6 modules in a browser, but I need to use a library that is made using Node module then webpacked: cytoscape-dagre or cytoscape-klay. Those are extensions for Cytoscape which itself has an ESM port that works just fine. I am finding a lot of resources to go from ES6 to anything else, but not the other way around. Does anyone know where I should look?
| [
"There are online services for this, such as esm.sh:\nimport cytoscapeDagre from 'https://esm.sh/cytoscape-dagre';\nimport cytoscapeKlay from 'https://esm.sh/cytoscape-klay';\n\nIf youβd like to build it and host it yourself, you could do what esm.sh does and use esbuild: https://github.com/evanw/esbuild.\n"
] | [
0
] | [] | [] | [
"es6_modules",
"node.js",
"web"
] | stackoverflow_0068801153_es6_modules_node.js_web.txt |
Q:
Can't get randomized vertical line to work in p5js
I've tried to create the simplest vertical line with a random x value between 0-5 at each vertex, and an increase in 10px in the y value at a time. Why is my line not showing?
function setup() {
createCanvas(400, 400);
noLoop();
}
function draw() {
background(220);
var y = 10;
var r = 0;
beginShape();
vertex(0, 0);
for (var i = 0; i < height; i += 10) {
r = random(0, 5);
console.log(r + " " + y);
vertex(r, y);
translate(r, y);
y += 10;
}
endShape();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
A:
I think you forgot beginShape(LINES) also you should put translate outside of the beginShape endShape otherwise it will translate everything once. (So they will be at the same place and not all over the place).
I made this code after many trial and error, I don't know if it's the result you expected:
function draw() {
background(220);
var y = 10;
var r = 0;
var random_old = 0;
for (var i = 0; i < height; i += 10) {
beginShape(LINES);
r = random(0, 5);
console.log(r + " " + y);
vertex(r, y);
y += 10;
r = random(0, 5);
vertex(r, y);
endShape();
translate((r - random_old) * 10, 0);
random_old = r;
y += 10;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
A:
I think you've misunderstood the way translate() works in the context of a shape.
You may be under the impression that each translate moves the canvas a little bit, then you draw a vertex, then the next translate moves the canvas a bit, then you draw another vertex and so on.
Actually, all of the translate() calls that happen inside of the beginShape()/endShape() stack on top of each other, translating the whole, completed shape as defined by the offsets passed to each vertex() call way off canvas. The coordinates you log misleadingly don't take into account the translations.
The solution is basically to remove translate(), optionally just doing one translation up front to reposition the shape.
function setup() {
createCanvas(400, 400);
noLoop();
}
function draw() {
background(220);
var y = 10;
var r = 0;
beginShape();
vertex(0, 0);
for (var i = 0; i < height; i += 10) {
r = random(0, 5);
vertex(r, y);
//translate(r, y); // <-- only change
y += 10;
}
endShape(CLOSE);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
That said, I don't think shapes are appropriate here anyway since I believe they'll require you to draw an ugly-looking straight line from bottom to top to close out the shape. Using a series of lines seems to look better:
function setup() {
createCanvas(400, 400);
noLoop();
}
function draw() {
background(220);
push();
translate(width / 2, 0);
let lastX = 0;
let lastY = 0;
for (let y = 0; y <= height; y += 10) {
const x = random(0, 5)
line(lastX, lastY, x, y);
lastX = x;
lastY = y;
}
pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
Looping the above gives:
function setup() {
createCanvas(400, 400);
noLoop();
}
function draw() {
background(220);
for (let i = 0; i < width; i += 5) {
push();
translate(i, 0);
let lastX = 0;
let lastY = 0;
for (let y = 0; y <= height; y += 10) {
const x = random(0, 5)
line(lastX, lastY, x, y);
lastX = x;
lastY = y;
}
pop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
| Can't get randomized vertical line to work in p5js | I've tried to create the simplest vertical line with a random x value between 0-5 at each vertex, and an increase in 10px in the y value at a time. Why is my line not showing?
function setup() {
createCanvas(400, 400);
noLoop();
}
function draw() {
background(220);
var y = 10;
var r = 0;
beginShape();
vertex(0, 0);
for (var i = 0; i < height; i += 10) {
r = random(0, 5);
console.log(r + " " + y);
vertex(r, y);
translate(r, y);
y += 10;
}
endShape();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js"></script>
| [
"I think you forgot beginShape(LINES) also you should put translate outside of the beginShape endShape otherwise it will translate everything once. (So they will be at the same place and not all over the place).\nI made this code after many trial and error, I don't know if it's the result you expected:\n\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n var random_old = 0;\n for (var i = 0; i < height; i += 10) {\n beginShape(LINES);\n r = random(0, 5);\n console.log(r + \" \" + y);\n vertex(r, y);\n y += 10;\n r = random(0, 5);\n vertex(r, y);\n endShape();\n translate((r - random_old) * 10, 0);\n random_old = r;\n y += 10;\n }\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script>\n\n\n\n",
"I think you've misunderstood the way translate() works in the context of a shape.\nYou may be under the impression that each translate moves the canvas a little bit, then you draw a vertex, then the next translate moves the canvas a bit, then you draw another vertex and so on.\nActually, all of the translate() calls that happen inside of the beginShape()/endShape() stack on top of each other, translating the whole, completed shape as defined by the offsets passed to each vertex() call way off canvas. The coordinates you log misleadingly don't take into account the translations.\nThe solution is basically to remove translate(), optionally just doing one translation up front to reposition the shape.\n\n\nfunction setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n beginShape();\n vertex(0, 0);\n for (var i = 0; i < height; i += 10) {\n r = random(0, 5);\n vertex(r, y);\n //translate(r, y); // <-- only change\n y += 10;\n }\n endShape(CLOSE);\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script>\n\n\n\nThat said, I don't think shapes are appropriate here anyway since I believe they'll require you to draw an ugly-looking straight line from bottom to top to close out the shape. Using a series of lines seems to look better:\n\n\nfunction setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n push();\n translate(width / 2, 0);\n let lastX = 0;\n let lastY = 0;\n\n for (let y = 0; y <= height; y += 10) {\n const x = random(0, 5)\n line(lastX, lastY, x, y);\n lastX = x;\n lastY = y;\n }\n \n pop();\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script>\n\n\n\nLooping the above gives:\n\n\nfunction setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n \n for (let i = 0; i < width; i += 5) {\n push();\n translate(i, 0);\n let lastX = 0;\n let lastY = 0;\n\n for (let y = 0; y <= height; y += 10) {\n const x = random(0, 5)\n line(lastX, lastY, x, y);\n lastX = x;\n lastY = y;\n }\n\n pop();\n }\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.js\"></script>\n\n\n\n"
] | [
2,
2
] | [
"It looks like you forgot to call the draw() function, so the shape is not being rendered. You can fix this by adding draw() to the end of your code:\nfunction setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n beginShape();\n vertex(0, 0);\n for (var i = 0; i < height; i += 10) {\n r = random(0, 5);\n console.log(r + \" \" + y);\n vertex(r, y);\n translate(r, y);\n y += 10;\n }\n endShape();\n}\n\ndraw();\n\nAdditionally, the translate() function will not have any effect in your code because you are calling it after calling vertex() to set the position of the next vertex. You can remove the translate() call and the line should be rendered correctly.\nHere is the updated code:\nfunction setup() {\n createCanvas(400, 400);\n noLoop();\n}\n\nfunction draw() {\n background(220);\n var y = 10;\n var r = 0;\n beginShape();\n vertex(0, 0);\n for (var i = 0; i < height; i += 10) {\n r = random(0, 5);\n console.log\n\n"
] | [
-1
] | [
"javascript",
"p5.js"
] | stackoverflow_0074669901_javascript_p5.js.txt |
Q:
Specified Class is not a Driver. Can't add MySQL Connector/J 8.0 to Netbeans 8.0
I can't get MySQL 8.0 jdbc driver set up in Netbeans. Can anyone help?
My Netbeans 8.0 IDE was set up using an older version of the MySQL JDBC Driver, 5.1.23. I upgraded MySQL to 8.0 and am trying to setup a new JDBC Driver in Netbeans because the old driver isn't able to connect to the new DB (*see note at end).
These are the steps I followed.
Step 1: I removed the old mysql driver jar file from D:\Program Files\NetBeans 8.0\ide\modules\ext and copied the new mysql-connector-java-8.0.12.jar file and restarted the IDE.
Step 2: In the Services tab under Databases I right clicked on Drivers and New Driver...
Step 3: In the dialog box that shows up I click the Add... button and I select the new driver jar D:\Program Files\NetBeans 8.0\ide\modules\ext\mysql-connector-java-8.0.12.jar
At this point the Driver Class automatically gets populated with com.mysql.jdbc.Driver and I can't hit the OK button because there's a message Specified class is not a driver (java.sql.Driver)
I tried changing it to com.mysql.cj.jdbc.Driver but it still gave the same message.
I decompiled com.mysql.jdbc.Driver from the jar file and got this:
package com.mysql.jdbc;
import java.io.PrintStream;
import java.sql.SQLException;
public class Driver
extends com.mysql.cj.jdbc.Driver
{
public Driver()
throws SQLException
{}
static
{
System.err.println("Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.");
}
}
and for com.mysql.cj.jdbc.Driver I got this
package com.mysql.cj.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Driver
extends NonRegisteringDriver
implements java.sql.Driver
{
public Driver()
throws SQLException
{}
static
{
try
{
DriverManager.registerDriver(new Driver());
}
catch (SQLException E)
{
throw new RuntimeException("Can't register driver!");
}
}
}
So com.mysql.jdbc.Driver extends com.mysql.cj.jdbc.Driver which implements java.sql.Driver so I don't know what the error is all about.
Anyone have any idea how to resolve this? I tried a 6.0 driver and got the same error. The 5 driver works but can't connect to DB.
Side note. with the old 5 driver I was getting ClassCastException when trying to connect to database. BigInt can't be Cast to Long. When I changed the driver in the application to the new driver that problem went away.
A:
First, I am successfully using mysql-connector-java-8.0.12.jar as the driver for MySQL 8.0 on NetBeans 8.2, so it definitely works:
I don't see any obvious reason for your problem but there are some things you can try to resolve this:
In your New JDBC Driver screenshot NetBeans is naming the driver MySQL (Connector/J driver) (1). Presumably that is because you already have a driver named MySQL (Connector/J driver), and your first screen shot confirms that. Why are you trying to add a second driver for MySQL? If there is no good reason, can you delete the old one, and then try adding the driver again?
Check for multiple instances of the 8.0.12 driver, and delete any old MySQL 5.x and MySQL 8.x drivers in your filestore, unless you have good reason to keep any of them.
The download page for Connector/J states "We suggest that you use the MD5 checksums and GnuPG signatures to verify the integrity of the packages you download". Did you do that? It's unlikely but possible that you have a corrupt file. Also, note that you must select "Platform Independent" when downloading the driver for Windows.
NetBeans might be caching something that's causing this problem. That's just a wild and desperate guess on my part, with no evidence at all to back it up, but you can easily and safely delete the cache to eliminate it as a possibility:
Help > About
Scroll down and locate the path of the Cache directory.
Shutdown NetBeans and delete that directory.
Start NetBeans and try again.
Check the NetBeans Log for possible insight into the problem:
Repeat the attempt to create the driver.
View > IDE Log and review the most recent entries in the log.
There might be an issue with NetBeans 8.0 since it is fairly old. Is it possible to upgrade to version 8.2 or 9.0?
Update based on feedback in the comments from the OP:
The OP reports that the cause of the problem was given by this message in the NetBeans log:
INFO [org.netbeans.modules.db.explorer.dlg.AddDriverDialog]: Got an
exception trying to load class com.mysql.jdbc.Driver during search for
JDBC drivers in driver jar(s): java.lang.UnsupportedClassVersionError:
com/mysql/jdbc/Driver : Unsupported major.minor version 52.0. Skipping
this class...
The Connector/J 8.0 driver requires Java 8:
It is a MySQL driver for the Java 8 platform. For Java 7 or earlier,
use Connector/J 5.1 instead.
So updating the default platform for NetBeans from JDK 7 to JDK 8 in netBeans.conf resolved the issue.
A:
Found that updating my Java version fixed it for me (from JDK 11 -> 18) since it seems the Java version the binary was compiled for was too new
A:
Use Connection Properties button and add a property with field name serverTimezone and value UTC.
This should work if error was caused by timezone issue.
A:
I got the problem of driver class, but when I checked the zip file mysql-connector-java-8.0.30, there is a second zip file within, then I used that second zip and solve the problem for Driver class.
| Specified Class is not a Driver. Can't add MySQL Connector/J 8.0 to Netbeans 8.0 | I can't get MySQL 8.0 jdbc driver set up in Netbeans. Can anyone help?
My Netbeans 8.0 IDE was set up using an older version of the MySQL JDBC Driver, 5.1.23. I upgraded MySQL to 8.0 and am trying to setup a new JDBC Driver in Netbeans because the old driver isn't able to connect to the new DB (*see note at end).
These are the steps I followed.
Step 1: I removed the old mysql driver jar file from D:\Program Files\NetBeans 8.0\ide\modules\ext and copied the new mysql-connector-java-8.0.12.jar file and restarted the IDE.
Step 2: In the Services tab under Databases I right clicked on Drivers and New Driver...
Step 3: In the dialog box that shows up I click the Add... button and I select the new driver jar D:\Program Files\NetBeans 8.0\ide\modules\ext\mysql-connector-java-8.0.12.jar
At this point the Driver Class automatically gets populated with com.mysql.jdbc.Driver and I can't hit the OK button because there's a message Specified class is not a driver (java.sql.Driver)
I tried changing it to com.mysql.cj.jdbc.Driver but it still gave the same message.
I decompiled com.mysql.jdbc.Driver from the jar file and got this:
package com.mysql.jdbc;
import java.io.PrintStream;
import java.sql.SQLException;
public class Driver
extends com.mysql.cj.jdbc.Driver
{
public Driver()
throws SQLException
{}
static
{
System.err.println("Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.");
}
}
and for com.mysql.cj.jdbc.Driver I got this
package com.mysql.cj.jdbc;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Driver
extends NonRegisteringDriver
implements java.sql.Driver
{
public Driver()
throws SQLException
{}
static
{
try
{
DriverManager.registerDriver(new Driver());
}
catch (SQLException E)
{
throw new RuntimeException("Can't register driver!");
}
}
}
So com.mysql.jdbc.Driver extends com.mysql.cj.jdbc.Driver which implements java.sql.Driver so I don't know what the error is all about.
Anyone have any idea how to resolve this? I tried a 6.0 driver and got the same error. The 5 driver works but can't connect to DB.
Side note. with the old 5 driver I was getting ClassCastException when trying to connect to database. BigInt can't be Cast to Long. When I changed the driver in the application to the new driver that problem went away.
| [
"First, I am successfully using mysql-connector-java-8.0.12.jar as the driver for MySQL 8.0 on NetBeans 8.2, so it definitely works:\n\nI don't see any obvious reason for your problem but there are some things you can try to resolve this:\n\nIn your New JDBC Driver screenshot NetBeans is naming the driver MySQL (Connector/J driver) (1). Presumably that is because you already have a driver named MySQL (Connector/J driver), and your first screen shot confirms that. Why are you trying to add a second driver for MySQL? If there is no good reason, can you delete the old one, and then try adding the driver again?\nCheck for multiple instances of the 8.0.12 driver, and delete any old MySQL 5.x and MySQL 8.x drivers in your filestore, unless you have good reason to keep any of them.\nThe download page for Connector/J states \"We suggest that you use the MD5 checksums and GnuPG signatures to verify the integrity of the packages you download\". Did you do that? It's unlikely but possible that you have a corrupt file. Also, note that you must select \"Platform Independent\" when downloading the driver for Windows.\nNetBeans might be caching something that's causing this problem. That's just a wild and desperate guess on my part, with no evidence at all to back it up, but you can easily and safely delete the cache to eliminate it as a possibility:\n\nHelp > About\nScroll down and locate the path of the Cache directory.\nShutdown NetBeans and delete that directory.\nStart NetBeans and try again.\n\nCheck the NetBeans Log for possible insight into the problem:\n\nRepeat the attempt to create the driver.\nView > IDE Log and review the most recent entries in the log.\n\nThere might be an issue with NetBeans 8.0 since it is fairly old. Is it possible to upgrade to version 8.2 or 9.0?\n\n\nUpdate based on feedback in the comments from the OP:\nThe OP reports that the cause of the problem was given by this message in the NetBeans log:\nINFO [org.netbeans.modules.db.explorer.dlg.AddDriverDialog]: Got an\nexception trying to load class com.mysql.jdbc.Driver during search for\nJDBC drivers in driver jar(s): java.lang.UnsupportedClassVersionError:\ncom/mysql/jdbc/Driver : Unsupported major.minor version 52.0. Skipping\nthis class...\n\nThe Connector/J 8.0 driver requires Java 8:\n\nIt is a MySQL driver for the Java 8 platform. For Java 7 or earlier,\n use Connector/J 5.1 instead.\n\nSo updating the default platform for NetBeans from JDK 7 to JDK 8 in netBeans.conf resolved the issue.\n",
"Found that updating my Java version fixed it for me (from JDK 11 -> 18) since it seems the Java version the binary was compiled for was too new\n",
"Use Connection Properties button and add a property with field name serverTimezone and value UTC. \nThis should work if error was caused by timezone issue. \n",
"I got the problem of driver class, but when I checked the zip file mysql-connector-java-8.0.30, there is a second zip file within, then I used that second zip and solve the problem for Driver class.\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"jdbc",
"mysql",
"mysql_connector",
"netbeans",
"netbeans_8"
] | stackoverflow_0052433053_jdbc_mysql_mysql_connector_netbeans_netbeans_8.txt |
Q:
Handle Google authentication in FastAPI
I am trying to implement a Google authentication on a FastAPI application.
I have a local register and login system with JWT that works perfectly, but the 'get_current_user' method depends on the oauth scheme for the local authentication:
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM])
email: EmailStr = payload.get("sub")
if email is None:
raise credentials_exception
token_data = TokenData(email=email)
except JWTError:
raise credentials_exception
user = await User.find_one(User.email == EmailStr(token_data.email))
if user is None:
raise credentials_exception
return user
oauth2_scheme using fastapi.security:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/jwt/login")
Now, the problem is that I don't know how to handle when a user is authenticated via Google, because I've defined a different Oauth client for Google:
google_oauth = OAuth(starlette_config)
google_oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'}
)
And my protected routes depend on the 'get_current_user' method, which is linked to the local oauth2_scheme.
How should I go about allowing users who have logged in via Google to access my protected endpoints?
A:
from fastapi import Request, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
class JWTBearer(HTTPBearer):
def __init__(self, auto_error: bool = True):
super(JWTBearer, self).__init__(auto_error=auto_error)
async def __call__(self, request: Request):
credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)
if credentials:
if not credentials.scheme == "Bearer":
raise HTTPException(status_code=403, detail="Invalid authentication scheme.")
#if not self.verify_jwt(credentials.credentials):
# raise HTTPException(status_code=403, detail="Invalid token or expired token.")
return credentials.credentials
else:
raise HTTPException(status_code=403, detail="Invalid authorization code.")```
now change your schema to
oauth2_schema = JWTBearer().
This will give a new type of authorization that only accept jwt token instead of the normal password and username.
Process flow on swagger docs:
1) go to any of the endpoints that give you token
2) copy the token and click on the padlock icon,
3) paste the token then you are login.
| Handle Google authentication in FastAPI | I am trying to implement a Google authentication on a FastAPI application.
I have a local register and login system with JWT that works perfectly, but the 'get_current_user' method depends on the oauth scheme for the local authentication:
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM])
email: EmailStr = payload.get("sub")
if email is None:
raise credentials_exception
token_data = TokenData(email=email)
except JWTError:
raise credentials_exception
user = await User.find_one(User.email == EmailStr(token_data.email))
if user is None:
raise credentials_exception
return user
oauth2_scheme using fastapi.security:
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/jwt/login")
Now, the problem is that I don't know how to handle when a user is authenticated via Google, because I've defined a different Oauth client for Google:
google_oauth = OAuth(starlette_config)
google_oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'}
)
And my protected routes depend on the 'get_current_user' method, which is linked to the local oauth2_scheme.
How should I go about allowing users who have logged in via Google to access my protected endpoints?
| [
"from fastapi import Request, HTTPException\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\n\n\n\nclass JWTBearer(HTTPBearer):\n def __init__(self, auto_error: bool = True):\n super(JWTBearer, self).__init__(auto_error=auto_error)\n\n async def __call__(self, request: Request):\n credentials: HTTPAuthorizationCredentials = await super(JWTBearer, self).__call__(request)\n if credentials:\n if not credentials.scheme == \"Bearer\":\n raise HTTPException(status_code=403, detail=\"Invalid authentication scheme.\")\n #if not self.verify_jwt(credentials.credentials):\n # raise HTTPException(status_code=403, detail=\"Invalid token or expired token.\")\n return credentials.credentials\n else:\n raise HTTPException(status_code=403, detail=\"Invalid authorization code.\")```\n\nnow change your schema to \n\noauth2_schema = JWTBearer().\n\nThis will give a new type of authorization that only accept jwt token instead of the normal password and username.\n\nProcess flow on swagger docs:\n\n1) go to any of the endpoints that give you token\n\n2) copy the token and click on the padlock icon, \n\n3) paste the token then you are login.\n\n"
] | [
0
] | [] | [] | [
"authentication",
"fastapi",
"oauth_2.0",
"python"
] | stackoverflow_0073945475_authentication_fastapi_oauth_2.0_python.txt |
Q:
Turbopack giving undefined for `React.Component`
I'm trying to create a component class with a Turbopack TSX project:
import React from 'react';
import baseResolution from '@/lib/baseResolution';
export default class GameContainer
extends React.Component<{}, {resizeListener: Function | null}>
{
// ...
}
So far, I've not modified anything in package.json. When I run npm run dev and access the web page, I get:
TypeError: Class extends value undefined is not a constructor or null
at (/app/GameContainer.tsx:5:18)
at Module.[project-with-next]/app/GameContainer.tsx (ecmascript, rsc) (.next\server\app\chunks\rsc\app_layout.tsx.js:165:3)
at (.next\server\app\chunks\ssr_6c0b57.js:67894:21)
...
What am I missing? Here's the package.json:
{
"private": true,
"scripts": {
"dev": "next dev --turbo",
"dev:tailwind": "concurrently \"next dev --turbo\" \"npm run tailwind -- --watch\"",
"build": "next build",
"start": "next start",
"lint": "next lint",
"tailwind": "tailwindcss -i styles/globals.css -o styles/dist.css",
"format": "prettier --write \"**/*.{js,ts,tsx,md}\"",
"postinstall": "npm run tailwind"
},
"prettier": {
"arrowParens": "always",
"semi": true,
"trailingComma": "all",
"singleQuote": true
},
"dependencies": {
"clsx": "1.2.1",
"concurrently": "7.5.0",
"next": "latest",
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "6.0.0-beta.2",
"styled-jsx": "5.1.0",
"use-count-up": "3.0.1"
},
"devDependencies": {
"@types/node": "18.0.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"autoprefixer": "^10.4.7",
"eslint": "8.19.0",
"eslint-config-next": "latest",
"postcss": "^8.4.14",
"prettier": "^2.7.1",
"prettier-plugin-tailwindcss": "^0.1.12",
"tailwindcss": "^3.1.6",
"typescript": "4.7.4"
}
}
A:
It looks like you are using the import keyword to import the React module, but you are not specifying the file where it is defined. This is causing the error you are seeing because the JavaScript runtime is unable to find the React module.
To fix this error, you need to specify the file where the React module is defined. In your code, this is the react package that you have installed, so you can use the following import statement to import the React module:
import * as React from 'react';
This import statement uses the import * as syntax to import the React module from the react package and assigns it to a variable named React. This should fix the error you are seeing.
Alternatively, if you are using a recent version of TypeScript, you can use the import type syntax to import the React module as a type instead of a value. This can be useful if you only want to use the types defined in the React module, without actually using the React value itself. Here is an example of how you can do that:
import type {React} from 'react';
In this code, the import type syntax is used to import the React type from the react package. This will allow you to use the types defined in the React module, but you will not be able to use the React value itself.
| Turbopack giving undefined for `React.Component` | I'm trying to create a component class with a Turbopack TSX project:
import React from 'react';
import baseResolution from '@/lib/baseResolution';
export default class GameContainer
extends React.Component<{}, {resizeListener: Function | null}>
{
// ...
}
So far, I've not modified anything in package.json. When I run npm run dev and access the web page, I get:
TypeError: Class extends value undefined is not a constructor or null
at (/app/GameContainer.tsx:5:18)
at Module.[project-with-next]/app/GameContainer.tsx (ecmascript, rsc) (.next\server\app\chunks\rsc\app_layout.tsx.js:165:3)
at (.next\server\app\chunks\ssr_6c0b57.js:67894:21)
...
What am I missing? Here's the package.json:
{
"private": true,
"scripts": {
"dev": "next dev --turbo",
"dev:tailwind": "concurrently \"next dev --turbo\" \"npm run tailwind -- --watch\"",
"build": "next build",
"start": "next start",
"lint": "next lint",
"tailwind": "tailwindcss -i styles/globals.css -o styles/dist.css",
"format": "prettier --write \"**/*.{js,ts,tsx,md}\"",
"postinstall": "npm run tailwind"
},
"prettier": {
"arrowParens": "always",
"semi": true,
"trailingComma": "all",
"singleQuote": true
},
"dependencies": {
"clsx": "1.2.1",
"concurrently": "7.5.0",
"next": "latest",
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "6.0.0-beta.2",
"styled-jsx": "5.1.0",
"use-count-up": "3.0.1"
},
"devDependencies": {
"@types/node": "18.0.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"autoprefixer": "^10.4.7",
"eslint": "8.19.0",
"eslint-config-next": "latest",
"postcss": "^8.4.14",
"prettier": "^2.7.1",
"prettier-plugin-tailwindcss": "^0.1.12",
"tailwindcss": "^3.1.6",
"typescript": "4.7.4"
}
}
| [
"It looks like you are using the import keyword to import the React module, but you are not specifying the file where it is defined. This is causing the error you are seeing because the JavaScript runtime is unable to find the React module.\nTo fix this error, you need to specify the file where the React module is defined. In your code, this is the react package that you have installed, so you can use the following import statement to import the React module:\nimport * as React from 'react';\n\nThis import statement uses the import * as syntax to import the React module from the react package and assigns it to a variable named React. This should fix the error you are seeing.\nAlternatively, if you are using a recent version of TypeScript, you can use the import type syntax to import the React module as a type instead of a value. This can be useful if you only want to use the types defined in the React module, without actually using the React value itself. Here is an example of how you can do that:\nimport type {React} from 'react';\n\nIn this code, the import type syntax is used to import the React type from the react package. This will allow you to use the types defined in the React module, but you will not be able to use the React value itself.\n"
] | [
1
] | [] | [] | [
"reactjs",
"tsx",
"turbopack"
] | stackoverflow_0074671587_reactjs_tsx_turbopack.txt |
Q:
Laravel Voyager not showing images
I have created a Laravel app using installatron on godaddy.com (shared hosting). After installing Voyager the default admin avatar is not showing. The storage link is automatically created by Voyager. But when I open the admin panel voyager tries to get admin avatar from [app_url]/storage/users/default.png and receives a 404. The avatar is at [app_url]/public/storage/users/default.png
Screenshot
Versions:
Laravel: 5.8
Voyager: 1.3
A:
Put port number in .env file if use localhost
APP_URL=http://localhost:port_number
A:
I've faced the exact same issue before, after checking the APP_URL, go ahead and execute
php artisan config:clear
After that try again.
If it doesn't work, delete the symlink storage in public/ and execute
php artisan storage:link
A:
Please check if the APP_URL in your .env file is correct.
That it equals the domain-name you bought at godaddy and also the protocol (HTTP or HTTPS).
A:
in my case 3 steps:
1- correct App_URL in .env file (do`nt forget port number )
example:
APP_URL=http://127.0.0.1:8000
2- delete storage file from [project path]\public
3- run: php artisan storage:link
enjoy:)
A:
Simply change the 'APP_URL' variable into the .env file to your localhost route.
For example:
APP_URL=http://127.0.0.1:8000
I was facing this issue today
A:
I solved my problem in local try with adding port to APP_URL.
But in the server problem was the "Storage" folder which is in public directory.
UPDATE Feb 2022
please notice the symbolic link must be existed in your root
A:
In your .env file, replace the app URL.
APP_URL=http://localhost:port
A:
I had to change the setting in filesystems.php.
'url' => env('APP_URL').'/nameOfMyRootFolder/storage/app/public',
Then it was able to resolve the image link correctly.
A:
Change the setting in filesystems.php,
disks -> public -> "url => env('APP_URL').'/public/storage'"
A:
Please check APP_URL=<> in your .env file it should be basically like
APP_URL=http://localhost:8000
A:
Check APP_URL in .env file, make sure that APP_URL in .env file is to the public folder of your project
APP_URL=http://localhost/your-project-name/public/
A:
APP_URL setting worked for me. I'm running the app in a container so I have to put the port used from my host not 8000. I have port 8000 mapped to 8186, so I have to put APP_URL=http://localhost:8186
A:
if you were using sail, try run :
sail artisan storage:link
A:
work for me:
image see in url http://localhost:8000/storage/users/default.png but dont in /admin panel (http://localhost/storage/users/default.png 404) its a port problem with storage
change in config/app to
'url' => env('APP_URL', 'http://localhost:8000')
A:
If you're still wonder why, check this answer in voyager issues
Since FILESYSTEM_DRIVER was not defined by default in Laravel the public storage was used, but in Laravel 8.5.19 the default value was added.
| Laravel Voyager not showing images | I have created a Laravel app using installatron on godaddy.com (shared hosting). After installing Voyager the default admin avatar is not showing. The storage link is automatically created by Voyager. But when I open the admin panel voyager tries to get admin avatar from [app_url]/storage/users/default.png and receives a 404. The avatar is at [app_url]/public/storage/users/default.png
Screenshot
Versions:
Laravel: 5.8
Voyager: 1.3
| [
"Put port number in .env file if use localhost\nAPP_URL=http://localhost:port_number\n\n",
"I've faced the exact same issue before, after checking the APP_URL, go ahead and execute\nphp artisan config:clear\n\nAfter that try again.\nIf it doesn't work, delete the symlink storage in public/ and execute\nphp artisan storage:link\n\n",
"Please check if the APP_URL in your .env file is correct. \nThat it equals the domain-name you bought at godaddy and also the protocol (HTTP or HTTPS).\n",
"in my case 3 steps:\n1- correct App_URL in .env file (do`nt forget port number )\nexample:\nAPP_URL=http://127.0.0.1:8000\n\n2- delete storage file from [project path]\\public\n3- run: php artisan storage:link\nenjoy:)\n",
"Simply change the 'APP_URL' variable into the .env file to your localhost route.\nFor example:\nAPP_URL=http://127.0.0.1:8000\n\nI was facing this issue today\n",
"I solved my problem in local try with adding port to APP_URL.\nBut in the server problem was the \"Storage\" folder which is in public directory.\nUPDATE Feb 2022\nplease notice the symbolic link must be existed in your root\n",
"In your .env file, replace the app URL.\nAPP_URL=http://localhost:port \n\n",
"I had to change the setting in filesystems.php.\n'url' => env('APP_URL').'/nameOfMyRootFolder/storage/app/public',\n\nThen it was able to resolve the image link correctly.\n",
"Change the setting in filesystems.php,\ndisks -> public -> \"url => env('APP_URL').'/public/storage'\"\n",
"Please check APP_URL=<> in your .env file it should be basically like\nAPP_URL=http://localhost:8000\n\n",
"Check APP_URL in .env file, make sure that APP_URL in .env file is to the public folder of your project\nAPP_URL=http://localhost/your-project-name/public/\n",
"APP_URL setting worked for me. I'm running the app in a container so I have to put the port used from my host not 8000. I have port 8000 mapped to 8186, so I have to put APP_URL=http://localhost:8186\n",
"if you were using sail, try run :\n sail artisan storage:link\n\n",
"work for me:\nimage see in url http://localhost:8000/storage/users/default.png but dont in /admin panel (http://localhost/storage/users/default.png 404) its a port problem with storage\nchange in config/app to\n'url' => env('APP_URL', 'http://localhost:8000')\n\n",
"If you're still wonder why, check this answer in voyager issues\nSince FILESYSTEM_DRIVER was not defined by default in Laravel the public storage was used, but in Laravel 8.5.19 the default value was added.\n"
] | [
6,
3,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"laravel",
"voyager"
] | stackoverflow_0059697588_laravel_voyager.txt |
Q:
Switch to a branch without bringing changed code from another branch
I was working on a branch named "improvement/02-improve-cart-page" but after doing some commits and changes to my code, I want to scrap this branch. As in delete the branch and go back to my develop branch which is my main branch.
I have the unchanged code in my "develop" branch and then the changed code in the "improvement/02-improve-cart-page" branch. When I do git checkout develop, the branch switches to develop but the code that was changed while I was in the "improvement/02-improve-cart-page" branch has remained.
What do I do so that I can go back to the "develop" branch code without any of the changes I made/committed? The "improvement/01-improve-cart-page" as well as the commits have not been pushed to Github
Upon doing git reset --hard while being in the develop branch, I get the following output and the code has remained the same:
HEAD is now at eae5c34 Merge pull request #6 from hudds-awp-cht2520/improvement/01-improve-products/page
A:
Upon doing git reset --hard while being in the develop branch,
You've achieved your goal. You discarded the unwanted changes and you are at the tip of the develop branch. You can confirm this with git status.*
(* - if you created new files while on improvement/02-improve-cart-page and not commited them then after git reset --hard you'll still have to remove them some other way (e.g. just deleting them in a file explorer))
| Switch to a branch without bringing changed code from another branch | I was working on a branch named "improvement/02-improve-cart-page" but after doing some commits and changes to my code, I want to scrap this branch. As in delete the branch and go back to my develop branch which is my main branch.
I have the unchanged code in my "develop" branch and then the changed code in the "improvement/02-improve-cart-page" branch. When I do git checkout develop, the branch switches to develop but the code that was changed while I was in the "improvement/02-improve-cart-page" branch has remained.
What do I do so that I can go back to the "develop" branch code without any of the changes I made/committed? The "improvement/01-improve-cart-page" as well as the commits have not been pushed to Github
Upon doing git reset --hard while being in the develop branch, I get the following output and the code has remained the same:
HEAD is now at eae5c34 Merge pull request #6 from hudds-awp-cht2520/improvement/01-improve-products/page
| [
"\nUpon doing git reset --hard while being in the develop branch,\n\nYou've achieved your goal. You discarded the unwanted changes and you are at the tip of the develop branch. You can confirm this with git status.*\n(* - if you created new files while on improvement/02-improve-cart-page and not commited them then after git reset --hard you'll still have to remove them some other way (e.g. just deleting them in a file explorer))\n"
] | [
0
] | [] | [] | [
"git",
"github"
] | stackoverflow_0074660040_git_github.txt |
Q:
What is right method to pass activationData from app to Apple Wallet?
I am trying to integrate Apple Pay In-App provisioning into bank application. My question is about the activationData parameter that returns from our host and must be passed to Wallet. Should an activationData be passed through addPaymentPassViewController delegate method only, or it is necessary to call activate(_:activationData:completion:) method as well? If it is necessary, what is the right place where I should call this method?
A:
https://medium.com/@daviddvd19/inapp-provisioning-enrolling-cards-en-5c368591d320
Maybe this link could be useful for you. I followed these steps for integration. The only question is how to create this activations data in BE side, I was not able to find step by step documentation in Apple website.
| What is right method to pass activationData from app to Apple Wallet? | I am trying to integrate Apple Pay In-App provisioning into bank application. My question is about the activationData parameter that returns from our host and must be passed to Wallet. Should an activationData be passed through addPaymentPassViewController delegate method only, or it is necessary to call activate(_:activationData:completion:) method as well? If it is necessary, what is the right place where I should call this method?
| [
"https://medium.com/@daviddvd19/inapp-provisioning-enrolling-cards-en-5c368591d320\nMaybe this link could be useful for you. I followed these steps for integration. The only question is how to create this activations data in BE side, I was not able to find step by step documentation in Apple website.\n"
] | [
0
] | [] | [] | [
"apple_wallet",
"applepay",
"ios",
"ios_provisioning",
"swift"
] | stackoverflow_0073497738_apple_wallet_applepay_ios_ios_provisioning_swift.txt |
Q:
How to change an attribute in a listview with ProgramAdapter class android studio JAVA
I need to change the clicked text in listview using a ProgramAdapter.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
String[] programName = {"ex1", "ex2", "ex3"}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProgram = findViewById(R.id.listView);
ProgramAdapter programAdapter = new ProgramAdapter(this, programName);
lvProgram.setAdapter(programAdapter);
}}
ProgramAdapter.java:
public class ProgramAdapter extends ArrayAdapter<String> {
Context context;
String[] programName;
public ProgramAdapter(Context context, String[] programName) {
super(context, R.layout.single_item2, R.id.titulo, programName);
this.context = context;
this.programName = programName;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View singleItem = convertView;
ProgramViewHolder holder = null;
if(singleItem == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
singleItem = layoutInflater.inflate(R.layout.single_item2, parent, false);
holder = new ProgramViewHolder(singleItem);
singleItem.setTag(holder);
}
else{
holder = (ProgramViewHolder) singleItem.getTag();
}
holder.programTitle.setText(programName[position]);
}
}
My attempt was that:
ProgramViewHolder finalHolder = holder;
singleItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
}
}
});
This changes the text for a moment, but every time you go down the list and up again, the text goes back to the default text.
A:
To fix this issue, you can try to update the programName array in the adapter after setting the text of the programTitle.
Here's how you can do that:
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
programName[position] = "expected text"; // update the programName array
}
}
This will update the programName array with the new text, and when you scroll up and down the list, the new text will be displayed. You can also try using the notifyDataSetChanged() method after updating the programName array to refresh the listview with the updated text.
Here's how your onClick() method can look like after implementing these changes:
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
programName[position] = "expected text"; // update the programName array
notifyDataSetChanged(); // refresh the listview
}
}
| How to change an attribute in a listview with ProgramAdapter class android studio JAVA | I need to change the clicked text in listview using a ProgramAdapter.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
String[] programName = {"ex1", "ex2", "ex3"}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProgram = findViewById(R.id.listView);
ProgramAdapter programAdapter = new ProgramAdapter(this, programName);
lvProgram.setAdapter(programAdapter);
}}
ProgramAdapter.java:
public class ProgramAdapter extends ArrayAdapter<String> {
Context context;
String[] programName;
public ProgramAdapter(Context context, String[] programName) {
super(context, R.layout.single_item2, R.id.titulo, programName);
this.context = context;
this.programName = programName;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View singleItem = convertView;
ProgramViewHolder holder = null;
if(singleItem == null){
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
singleItem = layoutInflater.inflate(R.layout.single_item2, parent, false);
holder = new ProgramViewHolder(singleItem);
singleItem.setTag(holder);
}
else{
holder = (ProgramViewHolder) singleItem.getTag();
}
holder.programTitle.setText(programName[position]);
}
}
My attempt was that:
ProgramViewHolder finalHolder = holder;
singleItem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(programName[position] == "ex1") {
finalHolder.programTitle.setText("expected text");
}
}
});
This changes the text for a moment, but every time you go down the list and up again, the text goes back to the default text.
| [
"To fix this issue, you can try to update the programName array in the adapter after setting the text of the programTitle.\nHere's how you can do that:\n@Override\npublic void onClick(View view) {\nif(programName[position] == \"ex1\") {\nfinalHolder.programTitle.setText(\"expected text\");\nprogramName[position] = \"expected text\"; // update the programName array\n}\n}\n\nThis will update the programName array with the new text, and when you scroll up and down the list, the new text will be displayed. You can also try using the notifyDataSetChanged() method after updating the programName array to refresh the listview with the updated text.\nHere's how your onClick() method can look like after implementing these changes:\n@Override\npublic void onClick(View view) {\nif(programName[position] == \"ex1\") {\nfinalHolder.programTitle.setText(\"expected text\");\nprogramName[position] = \"expected text\"; // update the programName array\nnotifyDataSetChanged(); // refresh the listview\n}\n}\n\n"
] | [
0
] | [] | [] | [
"android_studio",
"class",
"java"
] | stackoverflow_0074671378_android_studio_class_java.txt |
Q:
Grade computing program
I am learning python. The question is "Write a grade program using a function called computegrade that takes a score as its parameter and returns a grade as a string."
# Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
# < 0.6 F
How do I get the grades when I run this program? As I am not assigning the grades to any variable. Hence, unable to get the output.
def computegrade():
if score >=0.9:
print('Grade A')
elif score >=0.8 and score<0.9:
print('Grade B')
elif score >=0.7 and score<0.8:
print('Grade C')
elif score >=0.6 and score<0.7:
print('Grade D')
else:
print('Grade F')
score = input('Enter the score: ')
try:
score = float(score)
except:
print('Enter numbers only')
No Error messages, but I unable to see the grades when entering a value
A:
You're not seeing the grades because you're not telling python to run computegrade. If you do
try:
score = float(score)
computegrade()
It'll be done with.
Some observations about the computegrade method. I advise you to make it accept score as an argument
def computegrade(score):
# grade calculations...
Although it works without this - as long as there is a score variable in the same scope, Python takes it - it feels counterintuitive to call a function that requires as score, not passing a score to it.
Also, currently your program accepts grades bigger than 1.0 and smaller than 0.0, which is something you may want to raise an AssertionError in the future. I don't know if that is in the scope of your learning program, but having an
def computegrade():
if score > 1.0 or score < 0.0:
raise AssertionError('Scores must be within the 1.0 and 0.0 range!')
Is a good practice.
A:
def compute_grade(marks):
try:
if float(marks)>1.0 or float(marks)<0.0:
print("Invalid enteries")
else:
if float(marks) >= 0.9:
print("Grade A")
elif float(marks) >= 0.8:
print("Grade B")
elif float(marks) >= 0.7:
print("Grade C")
elif float(marks) >= 0.6:
print("Grade D")
elif float(marks) < 0.6:
print("Grade F")
except:
print("Please enter numeric value")
compute_grade(input("Please enter your marks\n"))
A:
sco = float(input('Enter your score: '))
def compute_grade(score):
if score > 1.0:
s = 'Out of Range!'
return s
elif score >= 0.9:
s = "A"
return s
elif score >= 0.8:
s = 'B'
return s
elif score >= 0.7:
s = 'C'
return s
elif score >= 0.6:
s = 'D'
return s
elif score >= 0.5:
s = 'E'
return s
else:
s = 'Bad score'
return s
sc = compute_grade(sco)
print(sc)
| Grade computing program | I am learning python. The question is "Write a grade program using a function called computegrade that takes a score as its parameter and returns a grade as a string."
# Score Grade
#>= 0.9 A
#>= 0.8 B
#>= 0.7 C
#>= 0.6 D
# < 0.6 F
How do I get the grades when I run this program? As I am not assigning the grades to any variable. Hence, unable to get the output.
def computegrade():
if score >=0.9:
print('Grade A')
elif score >=0.8 and score<0.9:
print('Grade B')
elif score >=0.7 and score<0.8:
print('Grade C')
elif score >=0.6 and score<0.7:
print('Grade D')
else:
print('Grade F')
score = input('Enter the score: ')
try:
score = float(score)
except:
print('Enter numbers only')
No Error messages, but I unable to see the grades when entering a value
| [
"You're not seeing the grades because you're not telling python to run computegrade. If you do\ntry:\n score = float(score)\n computegrade()\n\nIt'll be done with.\nSome observations about the computegrade method. I advise you to make it accept score as an argument\ndef computegrade(score):\n # grade calculations...\n\nAlthough it works without this - as long as there is a score variable in the same scope, Python takes it - it feels counterintuitive to call a function that requires as score, not passing a score to it.\nAlso, currently your program accepts grades bigger than 1.0 and smaller than 0.0, which is something you may want to raise an AssertionError in the future. I don't know if that is in the scope of your learning program, but having an\ndef computegrade():\n if score > 1.0 or score < 0.0:\n raise AssertionError('Scores must be within the 1.0 and 0.0 range!')\n\nIs a good practice.\n",
"def compute_grade(marks):\n try:\n if float(marks)>1.0 or float(marks)<0.0:\n print(\"Invalid enteries\")\n else:\n if float(marks) >= 0.9:\n print(\"Grade A\")\n elif float(marks) >= 0.8:\n print(\"Grade B\")\n elif float(marks) >= 0.7:\n print(\"Grade C\")\n elif float(marks) >= 0.6:\n print(\"Grade D\")\n elif float(marks) < 0.6:\n print(\"Grade F\")\n except:\n print(\"Please enter numeric value\")\ncompute_grade(input(\"Please enter your marks\\n\"))\n\n",
"sco = float(input('Enter your score: '))\ndef compute_grade(score):\nif score > 1.0:\n s = 'Out of Range!'\n return s\nelif score >= 0.9:\n s = \"A\"\n return s\nelif score >= 0.8:\n s = 'B'\n return s\nelif score >= 0.7:\n s = 'C'\n return s\nelif score >= 0.6:\n s = 'D'\n return s\nelif score >= 0.5:\n s = 'E'\n return s\nelse:\n s = 'Bad score'\n return s\n\nsc = compute_grade(sco)\nprint(sc)\n"
] | [
0,
0,
0
] | [
"You arenβt calling the function; you have told Python what the function is, but not called it. \nWhat you need to do is \nscore = float(score) \ngrade = computegrade()\nprint(βScore :β, score,β Grade :β, grade)\n\nIt is better practice to define your function so that it takes a parameter ;\ndef computegrade( score):\n\nInstead of your current βdefβ line, and then when you call the function:\ngrade = computegrade( score) \n\nIt is far better practice to write functions with parameters rather than rely on external variables. \n",
"You forgot to call the function.\nThe following is only a definition of the wanted function.\ndef computegrade():\n if score >=0.9:\n print('Grade A')\n elif score >=0.8 and score<0.9:\n print('Grade B')\n elif score >=0.7 and score<0.8:\n print('Grade C')\n elif score >=0.6 and score<0.7:\n print('Grade D')\n else:\n print('Grade F')\n\nYou need to call the function for it to be \"activated\".\nYou do so by writing:\ncomputegrade()\n\nSo i would guess that the resulting code should look like this:\nscore = input('Enter the score: ')\ntry:\n computegrade()\nexcept:\n print('Enter numbers only')\n\n(no need to convert to float, the command input() does it for you...)\n"
] | [
-1,
-1
] | [
"python"
] | stackoverflow_0057454202_python.txt |
Q:
Create plot with only x axis
I want to create a bubble plot without the y axis, meaning the x axis represents a range between certain values and the size of the bubbles corresponds to a "number" variable.
Since geom_point() requires a y variable, I created a new column with only zero values and assigned it to the y axis.
ggplot(df, aes(x=range, y=new, size = numberPoints)) +
geom_point(alpha=0.5, shape=19) +
scale_size(range = c(.1, 24)) +
scale_y_continuous(breaks = NULL)
However, it gave the following result (the y axis is too large):
I only wanted the bubbles above the x axis (without too much space), but I can't find a way to do it.
A:
You can use coord_fixed to "reduce" your axis
library(dplyr)
library(ggplot2)
data.frame(x = c(1,2,3,4), size = c(1,1,4,8)) %>%
ggplot(aes(x=x, y=1, size = size)) +
geom_point(alpha=0.5, shape=19) +
scale_size(range = c(.1, 24)) +
scale_y_continuous(breaks = NULL)+
coord_fixed(6)
| Create plot with only x axis | I want to create a bubble plot without the y axis, meaning the x axis represents a range between certain values and the size of the bubbles corresponds to a "number" variable.
Since geom_point() requires a y variable, I created a new column with only zero values and assigned it to the y axis.
ggplot(df, aes(x=range, y=new, size = numberPoints)) +
geom_point(alpha=0.5, shape=19) +
scale_size(range = c(.1, 24)) +
scale_y_continuous(breaks = NULL)
However, it gave the following result (the y axis is too large):
I only wanted the bubbles above the x axis (without too much space), but I can't find a way to do it.
| [
"You can use coord_fixed to \"reduce\" your axis\nlibrary(dplyr)\nlibrary(ggplot2)\n\ndata.frame(x = c(1,2,3,4), size = c(1,1,4,8)) %>% \n ggplot(aes(x=x, y=1, size = size)) +\n geom_point(alpha=0.5, shape=19) +\n scale_size(range = c(.1, 24)) +\n scale_y_continuous(breaks = NULL)+\n coord_fixed(6)\n\n\n"
] | [
0
] | [] | [] | [
"bubble_chart",
"ggplot2",
"r"
] | stackoverflow_0074671551_bubble_chart_ggplot2_r.txt |
Q:
Center Align Panel Header - Vuetify
My panel header is not center align
I can reproduce it here.
https://jsfiddle.net/bheng/7zd83tr9/
How do I center align it?
<v-expansion-panels>
<v-expansion-panel
v-for="(item,i) in 5"
:key="i"
>
<v-expansion-panel-header>
<v-row no-gutters>
<v-col> AAA </v-col>
<v-col>
<v-icon color="teal"> mdi-check </v-icon>
</v-col>
<v-col align="right">
<v-btn text color="red" @click.stop="remove(index, type)">
DELETE
</v-btn>
</v-col>
</v-row>
</v-expansion-panel-header>
<v-expansion-panel-content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
A:
You can use the align-center helper class on the v-row element.
class="align-center"
Snippet:
<v-expansion-panels>
<v-expansion-panel
v-for="(item,i) in 5"
:key="i"
>
<v-expansion-panel-header>
<v-row no-gutters class="align-center">
<v-col> AAA </v-col>
<v-col>
<v-icon color="teal"> mdi-check </v-icon>
</v-col>
<v-col align="right">
<v-btn text color="red" @click.stop="remove(index, type)">
DELETE
</v-btn>
</v-col>
</v-row>
</v-expansion-panel-header>
<v-expansion-panel-content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
Example: https://codepen.io/alexpetergill/pen/poLeWXb/dcb97f5a9ea97d1c2476b6437b91714f
Vuetify Docs: https://vuetifyjs.com/en/styles/flex/#flex-align
| Center Align Panel Header - Vuetify | My panel header is not center align
I can reproduce it here.
https://jsfiddle.net/bheng/7zd83tr9/
How do I center align it?
<v-expansion-panels>
<v-expansion-panel
v-for="(item,i) in 5"
:key="i"
>
<v-expansion-panel-header>
<v-row no-gutters>
<v-col> AAA </v-col>
<v-col>
<v-icon color="teal"> mdi-check </v-icon>
</v-col>
<v-col align="right">
<v-btn text color="red" @click.stop="remove(index, type)">
DELETE
</v-btn>
</v-col>
</v-row>
</v-expansion-panel-header>
<v-expansion-panel-content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</v-expansion-panel-content>
</v-expansion-panel>
</v-expansion-panels>
| [
"You can use the align-center helper class on the v-row element.\nclass=\"align-center\"\n\nSnippet:\n<v-expansion-panels>\n <v-expansion-panel\n v-for=\"(item,i) in 5\"\n :key=\"i\"\n >\n <v-expansion-panel-header>\n <v-row no-gutters class=\"align-center\">\n <v-col> AAA </v-col>\n <v-col>\n <v-icon color=\"teal\"> mdi-check </v-icon>\n </v-col>\n <v-col align=\"right\">\n <v-btn text color=\"red\" @click.stop=\"remove(index, type)\">\n DELETE\n </v-btn>\n </v-col>\n </v-row>\n </v-expansion-panel-header>\n <v-expansion-panel-content>\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n </v-expansion-panel-content>\n </v-expansion-panel>\n</v-expansion-panels>\n\nExample: https://codepen.io/alexpetergill/pen/poLeWXb/dcb97f5a9ea97d1c2476b6437b91714f\nVuetify Docs: https://vuetifyjs.com/en/styles/flex/#flex-align\n"
] | [
1
] | [] | [] | [
"vue.js",
"vuejs2",
"vuetify.js"
] | stackoverflow_0074669838_vue.js_vuejs2_vuetify.js.txt |
Q:
How to Update integer column with Thousand Seperator as "." in Postgresql
Hi I have a table that with integer data type and have values like "1000" ,"10000" "1000000" and I want to convert them as "1.000" , "10.000" and "1.000.000". Also I want to keep them in integer format. Is that possible ?
A:
No you cannot store an integer that way:
show lc_numeric;
en_US.UTF-8
select 10,000::integer;
?column? | int4
----------+------
10 | 0
select 10.000::integer;
int4
------
10
select to_char(10000, '99G999');
to_char
---------
10,000
select to_number('10,000', '99G999');
to_number
-----------
1000
set lc_numeric='de_DE.UTF-8';
SET
show lc_numeric ;
lc_numeric
-------------
de_DE.UTF-8
select 10,000::integer;
?column? | int4
----------+------
10 | 0
(1 row)
select 10.000::integer;
int4
------
10
(1 row)
select to_char(10000, '99G999');
to_char
---------
10.000
select to_number('10.000', '99G999');
to_number
-----------
10000
lc_numeric:
lc_numeric (string)
Sets the locale to use for formatting numbers, for example with the to_char family of functions. Acceptable values are system-dependent; see SectionΒ 24.1 for more information. If this variable is set to the empty string (which is the default) then the value is inherited from the execution environment of the server in a system-dependent way.
So the only way locale specific information is going to be relevant is when you format the number to a string or vice versa.
| How to Update integer column with Thousand Seperator as "." in Postgresql | Hi I have a table that with integer data type and have values like "1000" ,"10000" "1000000" and I want to convert them as "1.000" , "10.000" and "1.000.000". Also I want to keep them in integer format. Is that possible ?
| [
"No you cannot store an integer that way:\nshow lc_numeric; \nen_US.UTF-8 \n\nselect 10,000::integer; \n ?column? | int4 \n----------+------\n 10 | 0\n\nselect 10.000::integer;\n int4 \n------\n 10\n\nselect to_char(10000, '99G999');\n to_char \n---------\n 10,000\n\nselect to_number('10,000', '99G999');\n to_number \n-----------\n 1000\n\n\n\n\n\nset lc_numeric='de_DE.UTF-8';\nSET\n\nshow lc_numeric ;\n lc_numeric \n-------------\n de_DE.UTF-8\n\nselect 10,000::integer;\n ?column? | int4 \n----------+------\n 10 | 0\n(1 row)\n\nselect 10.000::integer;\n int4 \n------\n 10\n(1 row)\n\nselect to_char(10000, '99G999');\n to_char \n---------\n 10.000\n\nselect to_number('10.000', '99G999');\n to_number \n-----------\n 10000\n\n\n\nlc_numeric:\n\nlc_numeric (string)\n\n\nSets the locale to use for formatting numbers, for example with the to_char family of functions. Acceptable values are system-dependent; see SectionΒ 24.1 for more information. If this variable is set to the empty string (which is the default) then the value is inherited from the execution environment of the server in a system-dependent way.\n\nSo the only way locale specific information is going to be relevant is when you format the number to a string or vice versa.\n"
] | [
1
] | [] | [] | [
"format",
"postgresql"
] | stackoverflow_0074665762_format_postgresql.txt |
Q:
pulp constraint: exactly N in a category, up to X of a second choice, same category
I have a problem I'm trying to solve for where I want N players from one team, and up to X players from a second team, but I don't particularly care which team fills those constraints. For example, if N=5 and X=2, I could have 5 from one team and up to 2 from a second, different, team. How would I write such a constraint?
example dataframe:
team
pos
name
ceil
salary
0
NYY
OF
Aaron Judge
21.6631
6500
1
HOU
OF
Yordan Alvarez
21.6404
6100
2
ATL
OF
Ronald Acuna Jr.
21.5363
5400
3
HOU
OF
Kyle Tucker
20.0992
4700
4
TOR
1B
Vladimir Guerrero Jr.
20.0722
6000
5
LAD
SS
Trea Turner
20.0256
5700
6
LAD
OF
Mookie Betts
19.5231
6300
7
SEA
OF
Julio Rodriguez
19.3694
5200
8
MIN
OF
Byron Buxton
19.3412
5600
9
LAD
1B
Freddie Freeman
19.3393
5600
10
TOR
OF
George Springer
19.1429
5100
11
NYM
OF
Starling Marte
19.0791
5200
12
ATL
1B
Matt Olson
19.009
4800
13
ATL
3B
Austin Riley
18.9091
5200
14
SF
OF
Austin Slater
18.9052
3700
15
NYM
1B
Pete Alonso
18.8921
5700
16
TEX
OF
Adolis Garcia
18.7115
4200
17
TEX
SS
Corey Seager
18.6957
5100
18
TOR
OF
Teoscar Hernandez
18.6834
5200
19
CWS
1B
Jose Abreu
18.497
4600
20
ATL
SS
Dansby Swanson
18.4679
4900
21
TEX
2B/SS
Marcus Semien
18.4389
4100
22
NYY
1B
Anthony Rizzo
18.4383
5300
23
NYY
2B
Gleyber Torres
18.39
4500
24
CHC
C
Willson Contreras
18.3452
5800
existing code snippet:
#problem definition
prob = LpProblem(name="DFS", sense=LpMaximize)
prob += lpSum(player_vars[i] * slate['ceil'].iloc[i] for i in player_ids), "FPTS"
#salary and total player constraints
prob += lpSum(player_vars[i] * slate['salary'].iloc[i] for i in player_ids) <= 50000, "Salary"
prob += lpSum(player_vars[i] for i in player_ids) == 10, "Total Players"
#position constraints
prob += lpSum(player_vars[i] for i in player_ids if slate['pos'].iloc[i] == 'P') == 2, "Pitcher"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('C')].to_list()]) == 1, "Catcher"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('1B')].to_list()]) == 1, "1B"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('2B')].to_list()]) == 1, "2B"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('3B')].to_list()]) == 1, "3B"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('SS')].to_list()]) == 1, "SS"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('OF')].to_list()]) == 3, "OF"
#no opposing pitcher constraint
for pid in player_ids:
if slate['pos'].iloc[pid] == 'P':
prob += lpSum([player_vars[i] for i in player_ids if
slate['team'].iloc[i] == slate['opp'].iloc[pid]] + [9 * player_vars[pid]]) <= 9, "P{pid}".format(pid=pid)
#three team max constraint
unique_teams = slate['team'].unique()
player_in_team = slate['team'].str.get_dummies()
team_vars = LpVariable.dicts('team', unique_teams, cat = 'Binary')
for team in unique_teams:
prob += lpSum([player_in_team[team][i] * player_vars[i] for i in player_ids if slate['pos'].iloc[i] != 'P']) >= team_vars[team], "Team{team}Min".format(team=team)
prob += lpSum(team_vars[team] for team in unique_teams) == 3, "3 Teams"
A:
Here's how I would attack this... In pseudocode....
make a set of teams that you can use to index a couple of new variables.
Make subsets of your players grouped by team, or use pandas data frame filters to limit summations of players to the team of interest.
Make 2 new variables, that are binary "indicator" variables, one call it use5from[team] and one called use[team] to indicate that the team has been used at all.
Make appropriate constraints to link those to the selection variables. Something like:
for team in teams:
5 * use5from[team] <= pulp.lpSum(x[i] for i in team[i])
And for the other, a constraint to indicate any use...
for team in teams:
use[team] <= pulp.lpSum(x[i] for i in team[I])
And then make constraints that those two variables sum to over 1 and 3 respectively.
| pulp constraint: exactly N in a category, up to X of a second choice, same category | I have a problem I'm trying to solve for where I want N players from one team, and up to X players from a second team, but I don't particularly care which team fills those constraints. For example, if N=5 and X=2, I could have 5 from one team and up to 2 from a second, different, team. How would I write such a constraint?
example dataframe:
team
pos
name
ceil
salary
0
NYY
OF
Aaron Judge
21.6631
6500
1
HOU
OF
Yordan Alvarez
21.6404
6100
2
ATL
OF
Ronald Acuna Jr.
21.5363
5400
3
HOU
OF
Kyle Tucker
20.0992
4700
4
TOR
1B
Vladimir Guerrero Jr.
20.0722
6000
5
LAD
SS
Trea Turner
20.0256
5700
6
LAD
OF
Mookie Betts
19.5231
6300
7
SEA
OF
Julio Rodriguez
19.3694
5200
8
MIN
OF
Byron Buxton
19.3412
5600
9
LAD
1B
Freddie Freeman
19.3393
5600
10
TOR
OF
George Springer
19.1429
5100
11
NYM
OF
Starling Marte
19.0791
5200
12
ATL
1B
Matt Olson
19.009
4800
13
ATL
3B
Austin Riley
18.9091
5200
14
SF
OF
Austin Slater
18.9052
3700
15
NYM
1B
Pete Alonso
18.8921
5700
16
TEX
OF
Adolis Garcia
18.7115
4200
17
TEX
SS
Corey Seager
18.6957
5100
18
TOR
OF
Teoscar Hernandez
18.6834
5200
19
CWS
1B
Jose Abreu
18.497
4600
20
ATL
SS
Dansby Swanson
18.4679
4900
21
TEX
2B/SS
Marcus Semien
18.4389
4100
22
NYY
1B
Anthony Rizzo
18.4383
5300
23
NYY
2B
Gleyber Torres
18.39
4500
24
CHC
C
Willson Contreras
18.3452
5800
existing code snippet:
#problem definition
prob = LpProblem(name="DFS", sense=LpMaximize)
prob += lpSum(player_vars[i] * slate['ceil'].iloc[i] for i in player_ids), "FPTS"
#salary and total player constraints
prob += lpSum(player_vars[i] * slate['salary'].iloc[i] for i in player_ids) <= 50000, "Salary"
prob += lpSum(player_vars[i] for i in player_ids) == 10, "Total Players"
#position constraints
prob += lpSum(player_vars[i] for i in player_ids if slate['pos'].iloc[i] == 'P') == 2, "Pitcher"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('C')].to_list()]) == 1, "Catcher"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('1B')].to_list()]) == 1, "1B"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('2B')].to_list()]) == 1, "2B"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('3B')].to_list()]) == 1, "3B"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('SS')].to_list()]) == 1, "SS"
prob += lpSum([player_vars[i] for i in player_ids if slate['name'].iloc[i] in slate['name'][slate['pos'].str.contains('OF')].to_list()]) == 3, "OF"
#no opposing pitcher constraint
for pid in player_ids:
if slate['pos'].iloc[pid] == 'P':
prob += lpSum([player_vars[i] for i in player_ids if
slate['team'].iloc[i] == slate['opp'].iloc[pid]] + [9 * player_vars[pid]]) <= 9, "P{pid}".format(pid=pid)
#three team max constraint
unique_teams = slate['team'].unique()
player_in_team = slate['team'].str.get_dummies()
team_vars = LpVariable.dicts('team', unique_teams, cat = 'Binary')
for team in unique_teams:
prob += lpSum([player_in_team[team][i] * player_vars[i] for i in player_ids if slate['pos'].iloc[i] != 'P']) >= team_vars[team], "Team{team}Min".format(team=team)
prob += lpSum(team_vars[team] for team in unique_teams) == 3, "3 Teams"
| [
"Here's how I would attack this... In pseudocode....\n\nmake a set of teams that you can use to index a couple of new variables.\n\nMake subsets of your players grouped by team, or use pandas data frame filters to limit summations of players to the team of interest.\n\nMake 2 new variables, that are binary \"indicator\" variables, one call it use5from[team] and one called use[team] to indicate that the team has been used at all.\n\nMake appropriate constraints to link those to the selection variables. Something like:\n\n\n\nfor team in teams:\n 5 * use5from[team] <= pulp.lpSum(x[i] for i in team[i])\n\n\nAnd for the other, a constraint to indicate any use...\n\n\nfor team in teams:\n use[team] <= pulp.lpSum(x[i] for i in team[I]) \n\n\nAnd then make constraints that those two variables sum to over 1 and 3 respectively.\n\n"
] | [
1
] | [] | [] | [
"constraints",
"pulp",
"python"
] | stackoverflow_0074670229_constraints_pulp_python.txt |
Q:
C: Calculating the distance between 2 floats modulo 12
I require a function dist( a, b ) // 0 β€ a,b < 12 which returns the shortest (absolute ie +ve) distance ala clock arithmetic, using modulo 12.
So for example,
dist( 1, 2 )
= dist( 2, 1 )
= dist( 11, 0 )
= dist( 0, 11 )
= dist( 0.5, 11.5 )
= 1
EDIT: while this can easily be done with a bit of hacking around, I feel that there must be some intuitive solution, may be using fmod and modulo 6
A:
Firstly, an optimal solution is nontrivial, it took a little thinking.
float distMod12(float a,float b)
{
float diff = fabs( b - a );
return ( diff < 6 ) ? diff : 12 - diff;
}
EDIT: Alternatively,
return MIN( diff, 12 - diff ); // needs a MIN function
Complete code listing here: http://ideone.com/XxRIw
A:
If I read that correctly, a and b aren't negative, and they are smaller than 12.
#include <math.h>
#include <stdio.h>
double min( double a, double b ) {
return a < b ? a : b;
}
double dist( double a, double b ) {
return min(
fmod( 12+b-a, 12 ),
fmod( 12+a-b, 12 )
);
}
int main() {
printf("%f\n", dist(1, 2));
printf("%f\n", dist(2, 1));
printf("%f\n", dist(11, 0));
printf("%f\n", dist(0, 11));
printf("%f\n", dist(0.5, 11.5));
return 0;
}
which simplifies to
double dist( double a, double b ) {
double diff = fmod( 12+a-b, 12 );
return diff <= 6 ? diff : 12-diff;
}
A:
Something like
float dist( float a, float b ){
float amod, bmod;
amod = fmod( a, 12 );
bmod = fmod( b, 12 );
if( amod < bmod ) return dist( bmod, amod );
return min( amod-bmod, bmod-amod+12 );
}
Using the math library.
A:
I think we can find the answer without any comparison, or branching. A one-liner. (IMO the most elegant way)
float dist(float a, float b){
return abs(5.5-((b-(a-5.5))%12.0))
}
5.5 here is the middle point of the number line from 0 to 11.
After benchmarking though, it seems to be maybe very slightly slower than just doing it through MIN.
| C: Calculating the distance between 2 floats modulo 12 | I require a function dist( a, b ) // 0 β€ a,b < 12 which returns the shortest (absolute ie +ve) distance ala clock arithmetic, using modulo 12.
So for example,
dist( 1, 2 )
= dist( 2, 1 )
= dist( 11, 0 )
= dist( 0, 11 )
= dist( 0.5, 11.5 )
= 1
EDIT: while this can easily be done with a bit of hacking around, I feel that there must be some intuitive solution, may be using fmod and modulo 6
| [
"Firstly, an optimal solution is nontrivial, it took a little thinking.\nfloat distMod12(float a,float b)\n{\n float diff = fabs( b - a );\n return ( diff < 6 ) ? diff : 12 - diff;\n}\n\nEDIT: Alternatively, \n return MIN( diff, 12 - diff ); // needs a MIN function\n\nComplete code listing here: http://ideone.com/XxRIw\n",
"If I read that correctly, a and b aren't negative, and they are smaller than 12.\n#include <math.h>\n#include <stdio.h>\n\ndouble min( double a, double b ) {\n return a < b ? a : b;\n}\n\ndouble dist( double a, double b ) {\n return min( \n fmod( 12+b-a, 12 ),\n fmod( 12+a-b, 12 )\n );\n}\n\nint main() {\n printf(\"%f\\n\", dist(1, 2));\n printf(\"%f\\n\", dist(2, 1));\n printf(\"%f\\n\", dist(11, 0));\n printf(\"%f\\n\", dist(0, 11));\n printf(\"%f\\n\", dist(0.5, 11.5));\n return 0;\n}\n\nwhich simplifies to\ndouble dist( double a, double b ) {\n double diff = fmod( 12+a-b, 12 );\n return diff <= 6 ? diff : 12-diff;\n}\n\n",
"Something like\nfloat dist( float a, float b ){\n\n float amod, bmod;\n\n amod = fmod( a, 12 );\n bmod = fmod( b, 12 );\n\n if( amod < bmod ) return dist( bmod, amod );\n\n return min( amod-bmod, bmod-amod+12 );\n\n}\n\nUsing the math library.\n",
"I think we can find the answer without any comparison, or branching. A one-liner. (IMO the most elegant way)\nfloat dist(float a, float b){\n return abs(5.5-((b-(a-5.5))%12.0))\n}\n\n5.5 here is the middle point of the number line from 0 to 11.\nAfter benchmarking though, it seems to be maybe very slightly slower than just doing it through MIN.\n"
] | [
16,
7,
6,
1
] | [] | [] | [
"c",
"distance",
"modulo"
] | stackoverflow_0006192825_c_distance_modulo.txt |
Q:
Android KeyStore crashes in Android Instant App
val masterKey =
MasterKey
.Builder(applicationContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
Running this code in an Instant App crashes my app with the following Stack Trace:
2020-12-21 13:07:29.654 28949-28949/com.example.instantappandroidkeystore E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.instantappandroidkeystore, PID: 28949
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instantappandroidkeystore/com.example.instantappandroidkeystore.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.security.keystore.IKeystoreService.exist(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3448)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.security.keystore.IKeystoreService.exist(java.lang.String, int)' on a null object reference
at android.security.KeyStore.contains(KeyStore.java:408)
at android.security.keystore.AndroidKeyStoreSpi.engineContainsAlias(AndroidKeyStoreSpi.java:1038)
at java.security.KeyStore.containsAlias(KeyStore.java:1293)
at androidx.security.crypto.MasterKeys.keyExists(MasterKeys.java:154)
at androidx.security.crypto.MasterKeys.getOrCreate(MasterKeys.java:96)
at androidx.security.crypto.MasterKey$Builder.buildOnM(MasterKey.java:357)
at androidx.security.crypto.MasterKey$Builder.build(MasterKey.java:314)
at com.example.instantappandroidkeystore.MainActivity.onCreate(MainActivity.kt:32)
at android.app.Activity.performCreate(Activity.java:7955)
at android.app.Activity.performCreate(Activity.java:7944)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)Β
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)Β
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)Β
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)Β
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)Β
at android.os.Handler.dispatchMessage(Handler.java:107)Β
at android.os.Looper.loop(Looper.java:237)Β
at android.app.ActivityThread.main(ActivityThread.java:7814)Β
at java.lang.reflect.Method.invoke(Native Method)Β
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)Β
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)Β
I have no luck finding this issue in StackOverflow, but I have found it in Google Issue Tracker, but with no response. So I created submitted an issue to Google with more information. https://issuetracker.google.com/issues/176085956
Has anyone encounter this issue and was able to solve it.
My working environment is:
Mac OS 10.15.7
Android Studio 4.0.1
Samsung A70
Android version 10
A:
While this is not documented formally on developer.android forum, looks like AndroidKeyStore access is restricted for instant apps. I came across this link https://www.reddit.com/r/androiddev/comments/7a4tdw/why_no_hardware_backed_keystore_in_instant_apps/
This is quite strange that keystore is restricted and no android documentation explains it. I am not sure on an alternative to accessing KeyStore as we have lot of dependency on keystore for our regular app (non instant) and I can't think of a better option. Looking forward for suggestions !
A:
App is crashing because IKeystoreService object is null.
One possible reason for this is that the KeyStore service is not available on the device. In an Instant App the KeyStore service is not available by default, so it is needed to explicitly check access by calling InstantApps.isInstantApp(context) method and create MasterKey in the FragmentReadyListener.
Example of checking if the KeyStore service is available before trying to access it:
if (InstantApps.isInstantApp(context)) {
// Request access to the KeyStore service
InstantApps.getInstantAppsSupportFragment(this).requestInstant access(
new InstantApps.OnInstantAppsSupportFragmentReadyListener() {
@Override
public void onInstantAppsSupportFragmentReady(
InstantAppsSupportFragment fragment) {
// The KeyStore service is now available, so you can
// create a MasterKey instance and use it as needed
val masterKey = MasterKey
.Builder(applicationContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
}
},
Manifest.permission.USE_FINGERPRINT
);
} else {
// The KeyStore service is available in a non-Instant App,
// so create a MasterKey instance and use it as needed
val masterKey = MasterKey
.Builder(applicationContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
}
Note that in order to request access to the KeyStore service, declare the USE_FINGERPRINT permission in the app's manifest file.
| Android KeyStore crashes in Android Instant App | val masterKey =
MasterKey
.Builder(applicationContext)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build()
Running this code in an Instant App crashes my app with the following Stack Trace:
2020-12-21 13:07:29.654 28949-28949/com.example.instantappandroidkeystore E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.instantappandroidkeystore, PID: 28949
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instantappandroidkeystore/com.example.instantappandroidkeystore.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.security.keystore.IKeystoreService.exist(java.lang.String, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3448)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.security.keystore.IKeystoreService.exist(java.lang.String, int)' on a null object reference
at android.security.KeyStore.contains(KeyStore.java:408)
at android.security.keystore.AndroidKeyStoreSpi.engineContainsAlias(AndroidKeyStoreSpi.java:1038)
at java.security.KeyStore.containsAlias(KeyStore.java:1293)
at androidx.security.crypto.MasterKeys.keyExists(MasterKeys.java:154)
at androidx.security.crypto.MasterKeys.getOrCreate(MasterKeys.java:96)
at androidx.security.crypto.MasterKey$Builder.buildOnM(MasterKey.java:357)
at androidx.security.crypto.MasterKey$Builder.build(MasterKey.java:314)
at com.example.instantappandroidkeystore.MainActivity.onCreate(MainActivity.kt:32)
at android.app.Activity.performCreate(Activity.java:7955)
at android.app.Activity.performCreate(Activity.java:7944)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3595)Β
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)Β
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)Β
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)Β
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2147)Β
at android.os.Handler.dispatchMessage(Handler.java:107)Β
at android.os.Looper.loop(Looper.java:237)Β
at android.app.ActivityThread.main(ActivityThread.java:7814)Β
at java.lang.reflect.Method.invoke(Native Method)Β
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)Β
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)Β
I have no luck finding this issue in StackOverflow, but I have found it in Google Issue Tracker, but with no response. So I created submitted an issue to Google with more information. https://issuetracker.google.com/issues/176085956
Has anyone encounter this issue and was able to solve it.
My working environment is:
Mac OS 10.15.7
Android Studio 4.0.1
Samsung A70
Android version 10
| [
"While this is not documented formally on developer.android forum, looks like AndroidKeyStore access is restricted for instant apps. I came across this link https://www.reddit.com/r/androiddev/comments/7a4tdw/why_no_hardware_backed_keystore_in_instant_apps/\nThis is quite strange that keystore is restricted and no android documentation explains it. I am not sure on an alternative to accessing KeyStore as we have lot of dependency on keystore for our regular app (non instant) and I can't think of a better option. Looking forward for suggestions !\n",
"App is crashing because IKeystoreService object is null.\nOne possible reason for this is that the KeyStore service is not available on the device. In an Instant App the KeyStore service is not available by default, so it is needed to explicitly check access by calling InstantApps.isInstantApp(context) method and create MasterKey in the FragmentReadyListener.\nExample of checking if the KeyStore service is available before trying to access it:\nif (InstantApps.isInstantApp(context)) {\n // Request access to the KeyStore service\n InstantApps.getInstantAppsSupportFragment(this).requestInstant access(\n new InstantApps.OnInstantAppsSupportFragmentReadyListener() {\n @Override\n public void onInstantAppsSupportFragmentReady(\n InstantAppsSupportFragment fragment) {\n // The KeyStore service is now available, so you can\n // create a MasterKey instance and use it as needed\n val masterKey = MasterKey\n .Builder(applicationContext)\n .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)\n .build()\n }\n },\n Manifest.permission.USE_FINGERPRINT\n );\n} else {\n // The KeyStore service is available in a non-Instant App,\n // so create a MasterKey instance and use it as needed\n val masterKey = MasterKey\n .Builder(applicationContext)\n .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)\n .build()\n}\n\nNote that in order to request access to the KeyStore service, declare the USE_FINGERPRINT permission in the app's manifest file.\n"
] | [
2,
0
] | [] | [] | [
"android_instant_apps",
"android_keystore",
"encryption",
"keystore",
"kotlin"
] | stackoverflow_0065398957_android_instant_apps_android_keystore_encryption_keystore_kotlin.txt |
Q:
how to initialize whole block of array in c on the heap
How do i Initialize whole block of an array in c on the heap
int* a[102875] = {0xff, 0xff..........};
Like the followed example
I Tried also other ways to initialize array
Like:
myArray = (int*)calloc(102875, sizeof(int));
it worked fine but I can't initialize whole block of memory.
A:
The function calloc initializes all the allocated memory to zero.
If you want to initialize all bytes of the memory to a different value, you can use malloc followed by memset.
However, in this case, you don't want to initialize all bytes to a same value, so you can't use memset.
Therefore, it would probably be best to use a loop:
//attempt to allocate memory
myArray = malloc( 102875 * sizeof(int) );
if ( myArray == NULL )
{
fprintf( stderr, "Memory allocation error!\n" );
exit( EXIT_FAILURE );
}
//initialize the memory
for ( size_t i = 0; i < 102875; i++ )
{
myArray[i] = 0xFF;
}
| how to initialize whole block of array in c on the heap | How do i Initialize whole block of an array in c on the heap
int* a[102875] = {0xff, 0xff..........};
Like the followed example
I Tried also other ways to initialize array
Like:
myArray = (int*)calloc(102875, sizeof(int));
it worked fine but I can't initialize whole block of memory.
| [
"The function calloc initializes all the allocated memory to zero.\nIf you want to initialize all bytes of the memory to a different value, you can use malloc followed by memset.\nHowever, in this case, you don't want to initialize all bytes to a same value, so you can't use memset.\nTherefore, it would probably be best to use a loop:\n//attempt to allocate memory\nmyArray = malloc( 102875 * sizeof(int) );\nif ( myArray == NULL )\n{\n fprintf( stderr, \"Memory allocation error!\\n\" );\n exit( EXIT_FAILURE );\n}\n\n//initialize the memory\nfor ( size_t i = 0; i < 102875; i++ )\n{\n myArray[i] = 0xFF;\n}\n\n"
] | [
0
] | [] | [] | [
"arrays",
"c"
] | stackoverflow_0074671557_arrays_c.txt |
Q:
Why is vertical-align: middle not working on my span or div?
I'm trying to vertically center a span or div element within another div element. However when I put vertical-align: middle, nothing happens. I've tried changing the display properties of both elements, and nothing seems to work.
This is what I'm currently doing in my webpage:
.main {
height: 72px;
vertical-align: middle;
border: 1px solid black;
padding: 2px;
}
.inner {
vertical-align: middle;
border: 1px solid red;
}
.second {
border: 1px solid blue;
}
<div class="main">
<div class="inner">
This box should be centered in the larger box
<div class="second">Another box in here</div>
</div>
</div>
Here is a jsfiddle of the implementation showing that it doesn't work: http://jsfiddle.net/gZXWC/
A:
Using CSS3:
<div class="outer">
<div class="inner"/>
</div>
Css:
.outer {
display : flex;
align-items : center;
}
use "justify-content: center;" to align elements horizontally
Note: This might not work in old IE's
A:
This seems to be the best way - some time has passed since my original post and this is what should be done now:
.main {
display: table;
/* optional css start */
height: 90px;
width: 90px;
/* optional css end */
}
.inner {
border: 1px solid #000000;
display: table-cell;
vertical-align: middle;
}
<div class="main">
<div class="inner"> This </div>
</div>
A:
Try this, works for me very well:
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
A:
Setting the line-height to the same height as it's containing div will also work
DEMO http://jsfiddle.net/kevinPHPkevin/gZXWC/7/
.inner {
line-height:72px;
border: 1px solid #000000;
}
A:
In case you cannot rely on flexbox... Place .child into .parent's center. Works when pixel sizes are unknown (in other words, always) and no problems with IE9+ too.
.parent { position: relative; }
.child {
position: absolute;
top : 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform : translate(-50%, -50%);
}
<div class="parent" style="background:lightyellow; padding:6em">
<div class="child" style="background:gold; padding:1em">—</div>
</div>
A:
You should put vertical-align: middle on the inner element, not the outer element. Set the line-height property on the outer element to match the height of the outer element. Then set display: inline-block and line-height: normal on the inner element. By doing this, the text on the inner element will wrap with a normal line-height. Works in Chrome, Firefox, Safari, and IE 8+
.main {
height: 72px;
line-height:72px;
border: 1px solid black;
}
.inner {
display: inline-block;
vertical-align: middle;
line-height: normal;
}
<div class="main">
<div class="inner">Vertically centered text</div>
</div>
Fiddle
A:
I used this to align everything in the center of the wrapper div in case it helps anyone - I found it simplest:
div.wrapper {
/* --- This works --- */
display: flex;
/* Align Vertically */
align-items: center;
/* Align Horizontally */
justify-content: center;
/* --- ---------- ----- */
width: 100%;
height:100px;
background-color: blue;
}
div.inner {
width: 50px;
height: 50px;
background-color: orange;
}
<div class="wrapper">
<div class="inner">
</div>
</div>
A:
This is a modern approach and it utilizes the CSS Flexbox functionality.
You can now vertically align the content within your parent container by just adding these styles to the .main container
.main {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center; // To center align it horizontally as well
}
You can also use CSS Grids ( a two-dimensional grid-based layout system).
.main {
display: grid;
justify-content: center;
align-content: center;
}
Below is a Shorthand approach but browser support is still low - https://caniuse.com/?search=place-items.
.main {
display: grid; // flex - works for both
place-items: center;
}
And you are good to go!
A:
Here you have an example of two ways of doing a vertical alignment. I use them and they work pretty well. One is using absolute positioning and the other using flexbox.
Vertical Align Example
Using flexbox, you can align an element by itself inside another element with display: flex; using align-self. If you need to align it also horizontally, you can use align-items and justify-content in the container.
If you don't want to use flexbox, you can use the position property. If you make the container relative and the content absolute, the content will be able to move freely inside the container. So if you use top: 0; and left: 0; in the content, it will be positioned at the top left corner of the container.
Then, to align it, you just need to change the top and left references to 50%. This will position the content at the container center from the top left corner of the content.
So you need to correct this translating the content half its size to the left and top.
A:
HTML
<div id="myparent">
<div id="mychild">Test Content here</div>
</div>
CSS
#myparent {
display: table;
}
#mychild {
display: table-cell;
vertical-align: middle;
}
We set the parent div to display as a table and the child div to display as a table-cell. We can then use vertical-align on the child div and set its value to middle. Anything inside this child div will be vertically centered.
A:
here is a great article of how to vetical align..
I like the float way.
http://www.vanseodesign.com/css/vertical-centering/
The HTML:
<div id="main">
<div id="floater"></div>
<div id="inner">Content here</div>
</div>
And the corresponding style:
#main {
height: 250px;
}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#inner {
clear: both;
height: 100px;
}
A:
It's simple. Just add display:table-cell in your main class.
.main {
height: 72px;
vertical-align: middle;
display:table-cell;
border: 1px solid #000000;
}
Check out this jsfiddle!
A:
Here is the latest simplest solution - no need to change anything, just add three lines of CSS rules to your container of the div where you wish to center at. I love Flex Box #LoveFlexBox
.main {
/* I changed height to 200px to make it easy to see the alignment. */
height: 200px;
vertical-align: middle;
border: 1px solid #000000;
padding: 2px;
/* Just add the following three rules to the container of which you want to center at. */
display: flex;
flex-direction: column;
justify-content: center;
/* This is true vertical center, no math needed. */
}
.inner {
border: 1px solid #000000;
}
.second {
border: 1px solid #000000;
}
<div class="main">
<div class="inner">This box should be centered in the larger box
<div class="second">Another box in here</div>
</div>
<div class="inner">This box should be centered in the larger box
<div class="second">Another box in here</div>
</div>
</div>
Bonus
the justify-content value can be set to the following few options:
flex-start, which will align the child div to where the flex flow starts in its parent container. In this case, it will stay on top.
center, which will align the child div to the center of its parent container. This is really neat, because you don't need to add an additional div to wrap around all children to put the wrapper in a parent container to center the children. Because of that, this is the true vertical center (in the column flex-direction. similarly, if you change the flow-direction to row, it will become horizontally centered.
flex-end, which will align the child div to where the flex flow ends in its parent container. In this case, it will move to bottom.
space-between, which will spread all children from the beginning of the flow to the end of the flow. If the demo, I added another child div, to show they are spread out.
space-around, similar to space-between, but with half of the space in the beginning and end of the flow.
A:
Since vertical-align works as expected on a td, you could put a single celled table in the div to align its content.
<div>
<table style="width: 100%; height: 100%;"><tr><td style="vertical-align: middle; text-align: center">
Aligned content here...
</td></tr></table>
</div>
Clunky, but works as far as I can tell. It might not have the drawbacks of the other workarounds.
A:
Just put the content inside a table with height 100%, and set the height for the main div
<div style="height:80px;border: 1px solid #000000;">
<table style="height:100%">
<tr><td style="vertical-align: middle;">
This paragraph should be centered in the larger box
</td></tr>
</table>
</div>
A:
To vertically center a span or div element within another div, add position relative to parent div and position absolute to the child div.Now the child div can be positioned anywhere inside the div.Example below centers both horizontally and vertically.
<div class="parent">
<div class="child">Vertically and horizontally centered child div</div>
</div>
css:
.parent{
position: relative;
}
.child{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
A:
set below CSS
/*Parent*/
display: table;
/*immediate child*/
display: table-cell;
vertical-align: middle;
~Rahul Daksh
A:
THIS IS THE ANSWER:
vertical-align aligns elements relative to the dimensions of the line the element appears in.
reference: https://christopheraue.net/design/why-vertical-align-is-not-working
| Why is vertical-align: middle not working on my span or div? | I'm trying to vertically center a span or div element within another div element. However when I put vertical-align: middle, nothing happens. I've tried changing the display properties of both elements, and nothing seems to work.
This is what I'm currently doing in my webpage:
.main {
height: 72px;
vertical-align: middle;
border: 1px solid black;
padding: 2px;
}
.inner {
vertical-align: middle;
border: 1px solid red;
}
.second {
border: 1px solid blue;
}
<div class="main">
<div class="inner">
This box should be centered in the larger box
<div class="second">Another box in here</div>
</div>
</div>
Here is a jsfiddle of the implementation showing that it doesn't work: http://jsfiddle.net/gZXWC/
| [
"Using CSS3:\n<div class=\"outer\">\n <div class=\"inner\"/>\n</div>\n\nCss:\n.outer {\n display : flex;\n align-items : center;\n}\n\nuse \"justify-content: center;\" to align elements horizontally\nNote: This might not work in old IE's\n",
"This seems to be the best way - some time has passed since my original post and this is what should be done now:\n\n\n.main {\n display: table;\n \n /* optional css start */\n height: 90px;\n width: 90px;\n /* optional css end */\n}\n \n.inner {\n border: 1px solid #000000;\n display: table-cell;\n vertical-align: middle;\n}\n<div class=\"main\">\n <div class=\"inner\"> This </div>\n</div>\n\n\n\n",
"Try this, works for me very well:\n/* Internet Explorer 10 */\ndisplay:-ms-flexbox;\n-ms-flex-pack:center;\n-ms-flex-align:center;\n\n/* Firefox */\ndisplay:-moz-box;\n-moz-box-pack:center;\n-moz-box-align:center;\n\n/* Safari, Opera, and Chrome */\ndisplay:-webkit-box;\n-webkit-box-pack:center;\n-webkit-box-align:center;\n\n/* W3C */\ndisplay:box;\nbox-pack:center;\nbox-align:center;\n\n",
"Setting the line-height to the same height as it's containing div will also work \nDEMO http://jsfiddle.net/kevinPHPkevin/gZXWC/7/\n.inner {\n line-height:72px;\n border: 1px solid #000000;\n}\n\n",
"In case you cannot rely on flexbox... Place .child into .parent's center. Works when pixel sizes are unknown (in other words, always) and no problems with IE9+ too. \n\n\n.parent { position: relative; }\r\n\r\n.child {\r\n position: absolute;\r\n top : 50%;\r\n left: 50%;\r\n -ms-transform: translate(-50%, -50%);\r\n transform : translate(-50%, -50%); \r\n}\n<div class=\"parent\" style=\"background:lightyellow; padding:6em\"> \r\n <div class=\"child\" style=\"background:gold; padding:1em\">—</div> \r\n</div>\n\n\n\n",
"You should put vertical-align: middle on the inner element, not the outer element. Set the line-height property on the outer element to match the height of the outer element. Then set display: inline-block and line-height: normal on the inner element. By doing this, the text on the inner element will wrap with a normal line-height. Works in Chrome, Firefox, Safari, and IE 8+\n\n\n.main {\r\n height: 72px;\r\n line-height:72px;\r\n border: 1px solid black;\r\n}\r\n.inner {\r\n display: inline-block;\r\n vertical-align: middle;\r\n line-height: normal;\r\n}\n<div class=\"main\">\r\n <div class=\"inner\">Vertically centered text</div>\r\n</div>\n\n\n\nFiddle\n",
"I used this to align everything in the center of the wrapper div in case it helps anyone - I found it simplest:\n\n\ndiv.wrapper {\r\n /* --- This works --- */\r\n display: flex;\r\n /* Align Vertically */\r\n align-items: center;\r\n /* Align Horizontally */\r\n justify-content: center;\r\n /* --- ---------- ----- */\r\n width: 100%;\r\n height:100px;\r\n background-color: blue;\r\n}\r\ndiv.inner {\r\n width: 50px;\r\n height: 50px;\r\n background-color: orange;\r\n}\n<div class=\"wrapper\">\r\n <div class=\"inner\">\r\n </div>\r\n</div>\n\n\n\n",
"This is a modern approach and it utilizes the CSS Flexbox functionality.\nYou can now vertically align the content within your parent container by just adding these styles to the .main container\n.main {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center; // To center align it horizontally as well\n}\n\nYou can also use CSS Grids ( a two-dimensional grid-based layout system).\n.main {\n display: grid;\n justify-content: center;\n align-content: center;\n}\n\nBelow is a Shorthand approach but browser support is still low - https://caniuse.com/?search=place-items.\n .main {\n display: grid; // flex - works for both\n place-items: center;\n }\n\nAnd you are good to go!\n",
"Here you have an example of two ways of doing a vertical alignment. I use them and they work pretty well. One is using absolute positioning and the other using flexbox.\nVertical Align Example\nUsing flexbox, you can align an element by itself inside another element with display: flex; using align-self. If you need to align it also horizontally, you can use align-items and justify-content in the container.\nIf you don't want to use flexbox, you can use the position property. If you make the container relative and the content absolute, the content will be able to move freely inside the container. So if you use top: 0; and left: 0; in the content, it will be positioned at the top left corner of the container.\n\nThen, to align it, you just need to change the top and left references to 50%. This will position the content at the container center from the top left corner of the content.\n\nSo you need to correct this translating the content half its size to the left and top.\n\n",
"HTML\n<div id=\"myparent\">\n <div id=\"mychild\">Test Content here</div>\n</div>\n\nCSS\n#myparent {\n display: table;\n}\n#mychild {\n display: table-cell;\n vertical-align: middle;\n}\n\nWe set the parent div to display as a table and the child div to display as a table-cell. We can then use vertical-align on the child div and set its value to middle. Anything inside this child div will be vertically centered.\n",
"here is a great article of how to vetical align..\nI like the float way.\nhttp://www.vanseodesign.com/css/vertical-centering/\nThe HTML:\n<div id=\"main\">\n <div id=\"floater\"></div>\n <div id=\"inner\">Content here</div>\n</div>\n\nAnd the corresponding style:\n#main {\n height: 250px;\n}\n\n#floater {\n float: left;\n height: 50%;\n width: 100%;\n margin-bottom: -50px;\n}\n\n#inner {\n clear: both;\n height: 100px;\n}\n\n",
"It's simple. Just add display:table-cell in your main class.\n.main {\n height: 72px;\n vertical-align: middle;\n display:table-cell;\n border: 1px solid #000000;\n}\n\nCheck out this jsfiddle!\n",
"Here is the latest simplest solution - no need to change anything, just add three lines of CSS rules to your container of the div where you wish to center at. I love Flex Box #LoveFlexBox\n\n\n.main {\r\n /* I changed height to 200px to make it easy to see the alignment. */\r\n height: 200px;\r\n vertical-align: middle;\r\n border: 1px solid #000000;\r\n padding: 2px;\r\n \r\n /* Just add the following three rules to the container of which you want to center at. */\r\n display: flex;\r\n flex-direction: column;\r\n justify-content: center;\r\n /* This is true vertical center, no math needed. */\r\n}\r\n.inner {\r\n border: 1px solid #000000;\r\n}\r\n.second {\r\n border: 1px solid #000000;\r\n}\n<div class=\"main\">\r\n <div class=\"inner\">This box should be centered in the larger box\r\n <div class=\"second\">Another box in here</div>\r\n </div>\r\n <div class=\"inner\">This box should be centered in the larger box\r\n <div class=\"second\">Another box in here</div>\r\n </div>\r\n</div>\n\n\n\nBonus\nthe justify-content value can be set to the following few options:\n\nflex-start, which will align the child div to where the flex flow starts in its parent container. In this case, it will stay on top.\ncenter, which will align the child div to the center of its parent container. This is really neat, because you don't need to add an additional div to wrap around all children to put the wrapper in a parent container to center the children. Because of that, this is the true vertical center (in the column flex-direction. similarly, if you change the flow-direction to row, it will become horizontally centered.\nflex-end, which will align the child div to where the flex flow ends in its parent container. In this case, it will move to bottom.\nspace-between, which will spread all children from the beginning of the flow to the end of the flow. If the demo, I added another child div, to show they are spread out.\nspace-around, similar to space-between, but with half of the space in the beginning and end of the flow.\n\n",
"Since vertical-align works as expected on a td, you could put a single celled table in the div to align its content.\n<div>\n <table style=\"width: 100%; height: 100%;\"><tr><td style=\"vertical-align: middle; text-align: center\">\n Aligned content here...\n </td></tr></table>\n</div>\n\nClunky, but works as far as I can tell. It might not have the drawbacks of the other workarounds.\n",
"Just put the content inside a table with height 100%, and set the height for the main div\n<div style=\"height:80px;border: 1px solid #000000;\">\n<table style=\"height:100%\">\n<tr><td style=\"vertical-align: middle;\">\n This paragraph should be centered in the larger box\n</td></tr>\n</table>\n</div>\n\n",
"To vertically center a span or div element within another div, add position relative to parent div and position absolute to the child div.Now the child div can be positioned anywhere inside the div.Example below centers both horizontally and vertically.\n<div class=\"parent\">\n <div class=\"child\">Vertically and horizontally centered child div</div>\n</div>\n\ncss:\n.parent{\n position: relative;\n}\n.child{\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n margin: auto;\n}\n\n",
"set below CSS\n /*Parent*/\n display: table;\n\n/*immediate child*/\ndisplay: table-cell;\nvertical-align: middle;\n\n~Rahul Daksh\n",
"THIS IS THE ANSWER:\n\nvertical-align aligns elements relative to the dimensions of the line the element appears in.\n\nreference: https://christopheraue.net/design/why-vertical-align-is-not-working\n"
] | [
232,
229,
139,
37,
28,
27,
13,
9,
7,
6,
5,
4,
4,
0,
0,
0,
0,
0
] | [] | [] | [
"css",
"html"
] | stackoverflow_0016629561_css_html.txt |
Q:
VueJS - v-bind:style + hover
I need to use CSS hover with VueJS v-bind:style directive but couldn't find information regarding it.
I need to bind styles for hover but v-bind:style.hover={}
doesn't work. All the properties are going to be fetched from back-end, so I need to bind styles dynamically.
Are there other ways to bind styles on mouse over or CSS hover using VueJS?
Here is my code
This is the object :
button: {
colorBackd: '#1e2021',
colorBackdHover: '#000000',
text: 'Results',
color: '#d3e0ff',
colorHover: "#ffffff",
borderColor: '#d3e0ff',
borderColorHover: "#ffffff"
},
Here is the html element that needs to be bound with styles
<button type="button"
:style="{
color:button.color,
backgroundColor:button.colorBackd,
borderColor:button.borderColor,
}"
class="btn btn-outline-info large-button">
{{ button.text }}
</button>
Thanks
A:
Improved solution: use CSS custom properties and variables
If you only intend to work with modern/evergreen browsers, then using CSS custom properties and variables is the way to go! You can actually pass CSS custom properties into the :style binding, e.g.
computed: {
styleObject: function() {
return {
'--color': this.button.color,
'--color-hover': this.button.colorHover
}
}
}
And in your template:
<custom-button :style="styleObject" />
For the CSS, it's just a matter of:
button {
color: var(--color);
}
button:hover {
color: var(--color-hover);
}
The advantage of this method is that you can scope CSS custom properties, so these variables will only apply to your specific button component when you define the CSS properties at the element level (instead of in :root).
The only drawback is that you have to iteratively declare all the variables in both hover and unhovered states, which can be a little bit cumbersome. However, I see this is a very minor disadvantage, compared to the benefits that you reap from using CSS variables.
See proof-of-concept below:
var customButton = Vue.component('custom-button', {
template: '#custom-button',
data() {
return {
button: {
colorBackd: '#1e2021',
colorBackdHover: '#000000',
text: 'Results',
color: '#d3e0ff',
colorHover: "#ffffff",
borderColor: '#d3e0ff',
borderColorHover: "#ffffff"
}
};
},
computed: {
styleObject() {
return {
'--button-color': this.button.color,
'--button-background-color': this.button.colorBackd,
'--button-border-color': this.button.borderColor,
'--button-color--hover': this.button.colorHover,
'--button-background-color--hover': this.button.colorBackdHover,
'--button-border-color': this.button.borderColorHover
};
},
},
});
new Vue({
el: '#app'
});
button {
color: var(--button-color);
background-color: var(--button-background-color);
border-color: var(--button-border-color);
}
button:hover {
color: var(--button-color--hover);
background-color: var(--button-background-color--hover);
border-color: var(--button-border-color--hover);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
<custom-button></custom-button>
</div>
<script type="text/template" id="custom-button">
<button type="button" :style="styleObject" class="btn btn-outline-info large-button">
{{ button.text }}
</button>
</script>
Original sotluion: use JS-based mouse events
You can store the hovered state of the element in its data, say hoverState. It is set to false by default, and is toggled to true when @mouseenter is fired, and back to false when @mouseleave is triggered:
Then, you can simply bind a computed property to the style attribute, for example, styleObject. In this styleObject, you can return the correct CSS styles depending on the hoverState found in the component's data:
var customButton = Vue.component('custom-button', {
template: '#custom-button',
data() {
return {
button: {
colorBackd: '#1e2021',
colorBackdHover: '#000000',
text: 'Results',
color: '#d3e0ff',
colorHover: "#ffffff",
borderColor: '#d3e0ff',
borderColorHover: "#ffffff"
},
hoverState: false
};
},
computed: {
styleObject() {
var modifier = '';
if (this.hoverState)
modifier = 'Hover';
return {
color: this.button['color' + modifier],
backgroundColor: this.button['colorBackd' + modifier],
borderColor: this.button['borderColor' + modifier]
};
},
},
methods: {
updateHoverState(isHover) {
this.hoverState = isHover;
}
}
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
<custom-button></custom-button>
</div>
<script type="text/template" id="custom-button">
<button type="button" :style="styleObject" @mouseenter="updateHoverState(true)" @mouseleave="updateHoverState(false)" class="btn btn-outline-info large-button">
{{ button.text }}
</button>
</script>
A:
Other way (using css variables).
You need create HTML with style
<style>
div[vueid=${_uid}] { --btn-hover: ${`Here your hover brush`} }
</style>
and inject it into your component.
<template>
<div vueid="_uid">
<button></button>
<div v-html="styleCode"></div>
</div>
</template>
Then simply use this variable in static css file to setup button style.
button:hover { background: var(--btn-hover); }
Note: you can describe default variable value in :root selector.
A:
You can assign your Vuejs Component an id and apply the required hover style in a stylesheet.
<button id="styledButton" type="button"
:style="{
color:button.color,
backgroundColor:button.colorBackd,
borderColor:button.borderColor,
}"
class="btn btn-outline-info large-button">
{{ button.text }}
</button>
then in tag,
<style>
styledButton:hover {
color: #FFFFFF
};
</style>
If you want the hover style to contain any dynamic data. make a tag that calls a computed property.
<style>{{computedStyle}}</style>
A:
If you use single file components, then you just need to make the button style scoped:
<template>
<button></button>
</template>
<style scoped>
button {
/* your button style here */
}
</style>
Or even for a more confined styling there are modules, shown here: How to correctly use "scoped" styles in VueJS single file components?
A:
After seeing this is not implemented in vue I decided to use an overlay, which adds up to using :style to the overlay that will be shown by changing the opacity.
It is basically:
<div id="test" :style="style">
<div class="overlay" :style="style.hover"></div>
</div>
var testArea = Vue.component('test-area', {
template: '<div id="test" :style="style"><div class="overlay" :style="style.hover"></div></div>',
computed: {
style() {
return {
backgroundColor: '#0f0',
hover: {
backgroundColor: '#f00'
}
};
},
}
});
new Vue({
el: '#app'
});
#test {
position: relative;
width: 100px;
height: 100px;
}
#test>.overlay {
opacity: 0;
}
#test:hover>.overlay {
width: 100%;
height: 100%;
position: absolute;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<test-area></test-area>
</div>
A:
I wanted to change z-index on hover so that hovered p tag appears at top. To do so I had to listen for event along with some value.
<template>
...
<p @mouseover="changeZIndex"
@mouseleave="changeZIndexToOriginal({$event,old_z_index})
>
...
</template>
<script>
...methods
changeZIndex(e){
//change to new z-index
e.target.style.zIndex = 5 //to show on top
}
changeZIndexToOriginal(e){
//e.$event is an event which is trirgered. to get event along with some value we have to use this approach
// e.old_z_index is z-index that I want to set back again. I am just using loop index to set z-index
e.$event.target.style.zIndex = e.old_z_index
}
...
</script>
Using above approach we can change anything related to target element.
A:
An extremely simple solution I found was to use the v-bind:class directive instead:
in my case i needed to add a hover when this element is inactive:
:class="{'inactive': !item.count}"
In this case, I am able to add an inactive property to my class, and then i can simply style that class with hover properties like so:
.inactive {
color: black;
&:hover {
background-color: green;
}
}
A:
I'm using vue3 with composition api and decided there's 2 good ways to do this. You can use a slot and variable like so:
<MenuItem v-slot="{ active }">
<a href="#" :class="[active ? 'bg-neutral-600' : '', text-sm']">File</a>
</MenuItem>
Or you can use any template variables in the CSS section with v-bind() like so:
<template>
<MenuItem class="menuClass">File</MenuItem>
</template>
<script>
export default {
...
setup() {
return {
myObject,
};
},
};
</script>
<style>
.menuClass:hover {
background-color: v-bind("myObject.hoverColor");
}
</style>
| VueJS - v-bind:style + hover | I need to use CSS hover with VueJS v-bind:style directive but couldn't find information regarding it.
I need to bind styles for hover but v-bind:style.hover={}
doesn't work. All the properties are going to be fetched from back-end, so I need to bind styles dynamically.
Are there other ways to bind styles on mouse over or CSS hover using VueJS?
Here is my code
This is the object :
button: {
colorBackd: '#1e2021',
colorBackdHover: '#000000',
text: 'Results',
color: '#d3e0ff',
colorHover: "#ffffff",
borderColor: '#d3e0ff',
borderColorHover: "#ffffff"
},
Here is the html element that needs to be bound with styles
<button type="button"
:style="{
color:button.color,
backgroundColor:button.colorBackd,
borderColor:button.borderColor,
}"
class="btn btn-outline-info large-button">
{{ button.text }}
</button>
Thanks
| [
"Improved solution: use CSS custom properties and variables\nIf you only intend to work with modern/evergreen browsers, then using CSS custom properties and variables is the way to go! You can actually pass CSS custom properties into the :style binding, e.g.\ncomputed: {\n styleObject: function() {\n return {\n '--color': this.button.color,\n '--color-hover': this.button.colorHover\n }\n }\n}\n\nAnd in your template:\n<custom-button :style=\"styleObject\" />\n\nFor the CSS, it's just a matter of:\nbutton {\n color: var(--color);\n}\n\nbutton:hover {\n color: var(--color-hover);\n}\n\nThe advantage of this method is that you can scope CSS custom properties, so these variables will only apply to your specific button component when you define the CSS properties at the element level (instead of in :root).\nThe only drawback is that you have to iteratively declare all the variables in both hover and unhovered states, which can be a little bit cumbersome. However, I see this is a very minor disadvantage, compared to the benefits that you reap from using CSS variables.\nSee proof-of-concept below:\n\n\nvar customButton = Vue.component('custom-button', {\r\n template: '#custom-button',\r\n data() {\r\n return {\r\n button: {\r\n colorBackd: '#1e2021',\r\n colorBackdHover: '#000000',\r\n text: 'Results',\r\n color: '#d3e0ff',\r\n colorHover: \"#ffffff\",\r\n borderColor: '#d3e0ff',\r\n borderColorHover: \"#ffffff\"\r\n }\r\n };\r\n },\r\n computed: {\r\n styleObject() {\r\n return {\r\n '--button-color': this.button.color,\r\n '--button-background-color': this.button.colorBackd,\r\n '--button-border-color': this.button.borderColor,\r\n \r\n '--button-color--hover': this.button.colorHover,\r\n '--button-background-color--hover': this.button.colorBackdHover,\r\n '--button-border-color': this.button.borderColorHover\r\n };\r\n },\r\n },\r\n});\r\n\r\nnew Vue({\r\n el: '#app'\r\n});\nbutton {\r\n color: var(--button-color);\r\n background-color: var(--button-background-color);\r\n border-color: var(--button-border-color);\r\n}\r\n\r\nbutton:hover {\r\n color: var(--button-color--hover);\r\n background-color: var(--button-background-color--hover);\r\n border-color: var(--button-border-color--hover);\r\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js\"></script>\r\n<div id=\"app\">\r\n <custom-button></custom-button>\r\n</div>\r\n\r\n<script type=\"text/template\" id=\"custom-button\">\r\n <button type=\"button\" :style=\"styleObject\" class=\"btn btn-outline-info large-button\">\r\n {{ button.text }}\r\n </button>\r\n</script>\n\n\n\nOriginal sotluion: use JS-based mouse events\nYou can store the hovered state of the element in its data, say hoverState. It is set to false by default, and is toggled to true when @mouseenter is fired, and back to false when @mouseleave is triggered:\nThen, you can simply bind a computed property to the style attribute, for example, styleObject. In this styleObject, you can return the correct CSS styles depending on the hoverState found in the component's data:\n\n\nvar customButton = Vue.component('custom-button', {\r\n template: '#custom-button',\r\n data() {\r\n return {\r\n button: {\r\n colorBackd: '#1e2021',\r\n colorBackdHover: '#000000',\r\n text: 'Results',\r\n color: '#d3e0ff',\r\n colorHover: \"#ffffff\",\r\n borderColor: '#d3e0ff',\r\n borderColorHover: \"#ffffff\"\r\n },\r\n hoverState: false\r\n };\r\n },\r\n computed: {\r\n styleObject() {\r\n var modifier = '';\r\n if (this.hoverState)\r\n modifier = 'Hover';\r\n \r\n return {\r\n color: this.button['color' + modifier],\r\n backgroundColor: this.button['colorBackd' + modifier],\r\n borderColor: this.button['borderColor' + modifier]\r\n };\r\n },\r\n },\r\n methods: {\r\n updateHoverState(isHover) {\r\n this.hoverState = isHover;\r\n }\r\n }\r\n});\r\n\r\nnew Vue({\r\n el: '#app'\r\n});\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js\"></script>\r\n<div id=\"app\">\r\n <custom-button></custom-button>\r\n</div>\r\n\r\n<script type=\"text/template\" id=\"custom-button\">\r\n <button type=\"button\" :style=\"styleObject\" @mouseenter=\"updateHoverState(true)\" @mouseleave=\"updateHoverState(false)\" class=\"btn btn-outline-info large-button\">\r\n {{ button.text }}\r\n </button>\r\n</script>\n\n\n\n",
"Other way (using css variables). \nYou need create HTML with style \n<style>\n div[vueid=${_uid}] { --btn-hover: ${`Here your hover brush`} }\n</style>\n\nand inject it into your component. \n<template>\n <div vueid=\"_uid\">\n <button></button>\n <div v-html=\"styleCode\"></div>\n </div>\n</template>\n\nThen simply use this variable in static css file to setup button style.\nbutton:hover { background: var(--btn-hover); }\n\nNote: you can describe default variable value in :root selector.\n",
"You can assign your Vuejs Component an id and apply the required hover style in a stylesheet.\n<button id=\"styledButton\" type=\"button\"\n:style=\"{\ncolor:button.color,\n backgroundColor:button.colorBackd,\n borderColor:button.borderColor,\n}\"\nclass=\"btn btn-outline-info large-button\">\n\n {{ button.text }}\n</button>\n\nthen in tag,\n<style>\nstyledButton:hover {\ncolor: #FFFFFF\n};\n</style>\n\nIf you want the hover style to contain any dynamic data. make a tag that calls a computed property.\n<style>{{computedStyle}}</style>\n\n",
"If you use single file components, then you just need to make the button style scoped:\n<template>\n <button></button>\n</template>\n\n<style scoped>\n button {\n /* your button style here */\n }\n</style>\n\nOr even for a more confined styling there are modules, shown here: How to correctly use \"scoped\" styles in VueJS single file components?\n",
"After seeing this is not implemented in vue I decided to use an overlay, which adds up to using :style to the overlay that will be shown by changing the opacity.\nIt is basically:\n<div id=\"test\" :style=\"style\">\n <div class=\"overlay\" :style=\"style.hover\"></div>\n</div>\n\n\n\nvar testArea = Vue.component('test-area', {\r\n template: '<div id=\"test\" :style=\"style\"><div class=\"overlay\" :style=\"style.hover\"></div></div>',\r\n computed: {\r\n style() {\r\n return {\r\n backgroundColor: '#0f0',\r\n hover: {\r\n backgroundColor: '#f00'\r\n }\r\n };\r\n },\r\n }\r\n});\r\n\r\nnew Vue({\r\n el: '#app'\r\n});\n#test {\r\n position: relative;\r\n width: 100px;\r\n height: 100px;\r\n}\r\n\r\n#test>.overlay {\r\n opacity: 0;\r\n}\r\n\r\n#test:hover>.overlay {\r\n width: 100%;\r\n height: 100%;\r\n position: absolute;\r\n opacity: 1;\r\n}\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"></script>\r\n<div id=\"app\">\r\n <test-area></test-area>\r\n</div>\n\n\n\n",
"I wanted to change z-index on hover so that hovered p tag appears at top. To do so I had to listen for event along with some value.\n\n<template>\n...\n<p @mouseover=\"changeZIndex\"\n @mouseleave=\"changeZIndexToOriginal({$event,old_z_index})\n>\n...\n</template>\n\n\n<script>\n...methods\nchangeZIndex(e){\n //change to new z-index\n e.target.style.zIndex = 5 //to show on top\n}\nchangeZIndexToOriginal(e){\n //e.$event is an event which is trirgered. to get event along with some value we have to use this approach\n // e.old_z_index is z-index that I want to set back again. I am just using loop index to set z-index\n e.$event.target.style.zIndex = e.old_z_index\n}\n...\n</script>\n\nUsing above approach we can change anything related to target element.\n",
"An extremely simple solution I found was to use the v-bind:class directive instead:\nin my case i needed to add a hover when this element is inactive:\n:class=\"{'inactive': !item.count}\"\nIn this case, I am able to add an inactive property to my class, and then i can simply style that class with hover properties like so:\n.inactive {\n color: black;\n\n &:hover {\n background-color: green; \n }\n}\n\n",
"I'm using vue3 with composition api and decided there's 2 good ways to do this. You can use a slot and variable like so:\n<MenuItem v-slot=\"{ active }\">\n <a href=\"#\" :class=\"[active ? 'bg-neutral-600' : '', text-sm']\">File</a>\n</MenuItem>\n\nOr you can use any template variables in the CSS section with v-bind() like so:\n<template>\n <MenuItem class=\"menuClass\">File</MenuItem>\n</template>\n\n<script>\nexport default {\n ...\n setup() {\n return {\n myObject,\n };\n },\n};\n</script>\n\n<style>\n.menuClass:hover {\n background-color: v-bind(\"myObject.hoverColor\");\n}\n</style>\n\n"
] | [
42,
5,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"vue.js",
"vuejs2"
] | stackoverflow_0046551925_vue.js_vuejs2.txt |
Q:
Error in converting torch tensor to numpy.ndarray
var1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.],
[0., 0., 1., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 1.],
...,
[0., 0., 0., ..., 1., 1., 1.],
[0., 0., 0., ..., 1., 1., 1.],
[0., 0., 0., ..., 1., 1., 1.]]]])
print(var1.size())
print(type(var1))
print(var1.dtype)
Output:
torch.Size([1, 1, 480, 640])
<class 'torch.Tensor'>
torch.float32
When I tried to convert torch tensor into numpy.ndarray, all values became zero.
nump_var1 = var1.argmax(dim=1).squeeze(0).cpu().numpy()
print(nump_var1)
print(nump_var1.shape)
print(type(nump_var1))
print(nump_var1.dtype)
Output:
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
(480, 640)
<class 'numpy.ndarray'>
int64
Can anyone point out the mistake I have made?
Thanks for the help.
A:
As hpaulj hinted at in a comment, var1.argmax(dim=1) will result in a zero tensor because you have var1.size(1) == 1.
A:
The error seems to occur when using argmax() on the tensor. The argmax() function returns the index of the maximum value of a tensor along a given dimension. In your code, you are using argmax() with the dim argument set to 1, which will return the indices of the maximum value along the second dimension of the tensor.
However, since your tensor has only one element in the second dimension, the argmax() function will always return 0 as the index of the maximum value, which means that all the values in your tensor will be set to 0 when you convert it to a NumPy array.
To avoid this issue, you can try using the numpy() function instead of the argmax() function to convert your tensor to a NumPy array. This will simply convert the tensor to a NumPy array without changing the values.
Here is how you can do it:
nump_var1 = var1.squeeze(0).cpu().numpy()
You can also remove the squeeze() function, as it is not necessary in this case. The squeeze() function is used to remove dimensions of size 1 from a tensor, but since your tensor has only one element in the first and second dimensions, the squeeze() function will not have any effect.
Here is the updated code:
var1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.],
[0., 0., 1., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 1.],
...,
[0., 0., 0., ..., 1., 1., 1.],
[0., 0., 0., ..., 1., 1., 1.],
[0., 0., 0., ..., 1., 1., 1.]]]])
print(var1.size())
print(type(var1))
print(var1.dtype)
# Use the numpy() function to convert the tensor to a NumPy array
nump_var1 = var1.cpu().numpy()
print(nump_var1)
print(nump_var1.shape)
print(type(nump_var1))
print(nump_var1.dtype)
This should fix the issue and give you the expected output. Let me know if this helps.
| Error in converting torch tensor to numpy.ndarray | var1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.],
[0., 0., 1., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 1.],
...,
[0., 0., 0., ..., 1., 1., 1.],
[0., 0., 0., ..., 1., 1., 1.],
[0., 0., 0., ..., 1., 1., 1.]]]])
print(var1.size())
print(type(var1))
print(var1.dtype)
Output:
torch.Size([1, 1, 480, 640])
<class 'torch.Tensor'>
torch.float32
When I tried to convert torch tensor into numpy.ndarray, all values became zero.
nump_var1 = var1.argmax(dim=1).squeeze(0).cpu().numpy()
print(nump_var1)
print(nump_var1.shape)
print(type(nump_var1))
print(nump_var1.dtype)
Output:
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
(480, 640)
<class 'numpy.ndarray'>
int64
Can anyone point out the mistake I have made?
Thanks for the help.
| [
"As hpaulj hinted at in a comment, var1.argmax(dim=1) will result in a zero tensor because you have var1.size(1) == 1.\n",
"The error seems to occur when using argmax() on the tensor. The argmax() function returns the index of the maximum value of a tensor along a given dimension. In your code, you are using argmax() with the dim argument set to 1, which will return the indices of the maximum value along the second dimension of the tensor.\nHowever, since your tensor has only one element in the second dimension, the argmax() function will always return 0 as the index of the maximum value, which means that all the values in your tensor will be set to 0 when you convert it to a NumPy array.\nTo avoid this issue, you can try using the numpy() function instead of the argmax() function to convert your tensor to a NumPy array. This will simply convert the tensor to a NumPy array without changing the values.\nHere is how you can do it:\nnump_var1 = var1.squeeze(0).cpu().numpy()\n\nYou can also remove the squeeze() function, as it is not necessary in this case. The squeeze() function is used to remove dimensions of size 1 from a tensor, but since your tensor has only one element in the first and second dimensions, the squeeze() function will not have any effect.\nHere is the updated code:\nvar1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.],\n [0., 0., 1., ..., 0., 0., 0.],\n [0., 0., 0., ..., 0., 0., 1.],\n ...,\n [0., 0., 0., ..., 1., 1., 1.],\n [0., 0., 0., ..., 1., 1., 1.],\n [0., 0., 0., ..., 1., 1., 1.]]]])\n\nprint(var1.size())\nprint(type(var1))\nprint(var1.dtype)\n\n# Use the numpy() function to convert the tensor to a NumPy array\nnump_var1 = var1.cpu().numpy()\n\nprint(nump_var1)\nprint(nump_var1.shape)\nprint(type(nump_var1))\nprint(nump_var1.dtype)\n\nThis should fix the issue and give you the expected output. Let me know if this helps.\n"
] | [
0,
0
] | [] | [] | [
"machine_learning",
"numpy",
"python",
"pytorch",
"tensor"
] | stackoverflow_0074669588_machine_learning_numpy_python_pytorch_tensor.txt |
Q:
How do I run python cgi script on apache2 server on Ubuntu 16.04?
I am a newbie so I saw some tutorials.
I have a python script as first.py
#!/usr/bin/python3
print "Content-type: text/html\n"
print "Hello, world!"
I have multiple versions of python on my computer.
I couldn't figure out my cgi enabled directory so I pasted this code at three places
/usr/lib/cgi-bin/first.py
/usr/lib/cups/cgi-bin/first.py
/var/www/html/first.py
Now when I run this code in terminal it works fine but when I type
curl http://localhost/first.py
it spit out just simple text and does not execute.
I have given all the permissions to first.py
I have enabled and started the server by commands
a2enmod cgi
systemctl restart apache2
Please tell how do I execute and what is going on here?
Thanks in advance.
A:
To python cgi script on apache2 server on Ubuntu(Tested on Ubuntu 20.04) from scratch, Follow these steps(Expects python is installed and works perfectly).
Install apache2 sever.
sudo apt install apache2
Enable CGI module.
sudo a2enmod cgi
Here we set /var/www/cgi-bin/ as cgi-bin directory. If you want a different directory, change files appropriately.
Open Apache server configuration file [/etc/apache2/apache2.conf] by,
sudo gedit /etc/apache2/apache2.conf
And following lines to the end of the file.
######### Adding capaility to run CGI-scripts #################
ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py
Open file /etc/apache2/conf-available/serve-cgi-bin.conf by,
sudo gedit /etc/apache2/conf-available/serve-cgi-bin.conf
Change lines :
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Require all granted
</Directory>
To :
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
<Directory "/var/www/cgi-bin/">
AllowOverride None
Options +ExecCGI
</Directory>
Now restart apache2 server by,
sudo service apache2 restart
Now create python script say, first.py inside directory
/var/www/cgi-bin/ by,
sudo gedit /var/www/cgi-bin/first.py
and add following sample code :
#!/usr/bin/env python
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print ("Content-type:text/html\r\n")
print("<H1> Hello, From python server :) </H1>")
And give executable permission to first.py by,
sudo chmod +x /var/www/cgi-bin/first.py
Now curl will work.
:~$ curl http://localhost/cgi-bin/first.py
<H1> Hello, From python server :) </H1>
Or open browser and browse http://localhost/cgi-bin/first.py. This should work and will display webpage showing "Hello, From python server :)".
Hope it helps... Happy coding :)
A:
These lines need to be in your apache2 site configuration file
(for example /etc/apache2/sites-available/default-ssl.conf
if your website uses HTTPS):
<Directory /var/www/yoursite/yourdir/>
Options +ExecCGI
PassEnv LANG
AddHandler cgi-script .py
</Directory>
Add them for the directory you want and restart apache2. You might also need to add
AddHandler python-program .py
to your httpd.conf if not present already.
A more detailed discussion concerning python scripts and apache2 is found here: Executing a Python script in Apache2.
A:
Probably the problem you're running in Python 3 and your code is written in Python 2
Change the title to python2:
#!/usr/bin/python
print "Content-type: text/html\n"
print "Hello, world!"
A:
For just proof of concept, use this python script ; No input nor output needed.
#!/usr/bin/env python3
import cgitb
cgitb.enable()
outputfile = open("javascriptPython.out", "a")
outputfile.write("Hello from Python\n\n")
| How do I run python cgi script on apache2 server on Ubuntu 16.04? | I am a newbie so I saw some tutorials.
I have a python script as first.py
#!/usr/bin/python3
print "Content-type: text/html\n"
print "Hello, world!"
I have multiple versions of python on my computer.
I couldn't figure out my cgi enabled directory so I pasted this code at three places
/usr/lib/cgi-bin/first.py
/usr/lib/cups/cgi-bin/first.py
/var/www/html/first.py
Now when I run this code in terminal it works fine but when I type
curl http://localhost/first.py
it spit out just simple text and does not execute.
I have given all the permissions to first.py
I have enabled and started the server by commands
a2enmod cgi
systemctl restart apache2
Please tell how do I execute and what is going on here?
Thanks in advance.
| [
"To python cgi script on apache2 server on Ubuntu(Tested on Ubuntu 20.04) from scratch, Follow these steps(Expects python is installed and works perfectly).\n\nInstall apache2 sever.\nsudo apt install apache2\n\n\nEnable CGI module.\nsudo a2enmod cgi\n\n\n\n\nHere we set /var/www/cgi-bin/ as cgi-bin directory. If you want a different directory, change files appropriately.\n\n\nOpen Apache server configuration file [/etc/apache2/apache2.conf] by,\nsudo gedit /etc/apache2/apache2.conf\n\nAnd following lines to the end of the file.\n######### Adding capaility to run CGI-scripts #################\nServerName localhost\nScriptAlias /cgi-bin/ /var/www/cgi-bin/\nOptions +ExecCGI\nAddHandler cgi-script .cgi .pl .py\n\n\nOpen file /etc/apache2/conf-available/serve-cgi-bin.conf by,\nsudo gedit /etc/apache2/conf-available/serve-cgi-bin.conf\n\nChange lines :\nScriptAlias /cgi-bin/ /usr/lib/cgi-bin/\n<Directory \"/usr/lib/cgi-bin\">\n AllowOverride None\n Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch\n Require all granted\n</Directory> \n\nTo :\nScriptAlias /cgi-bin/ /var/www/cgi-bin/\n<Directory \"/var/www/cgi-bin/\">\n AllowOverride None\n Options +ExecCGI\n</Directory>\n\n\nNow restart apache2 server by,\nsudo service apache2 restart\n\n\nNow create python script say, first.py inside directory\n/var/www/cgi-bin/ by,\nsudo gedit /var/www/cgi-bin/first.py\n\nand add following sample code :\n#!/usr/bin/env python\nimport cgitb\n\ncgitb.enable()\n\nprint(\"Content-Type: text/html;charset=utf-8\")\nprint (\"Content-type:text/html\\r\\n\")\nprint(\"<H1> Hello, From python server :) </H1>\")\n\nAnd give executable permission to first.py by,\nsudo chmod +x /var/www/cgi-bin/first.py\n\n\n\nNow curl will work.\n:~$ curl http://localhost/cgi-bin/first.py\n<H1> Hello, From python server :) </H1>\n\nOr open browser and browse http://localhost/cgi-bin/first.py. This should work and will display webpage showing \"Hello, From python server :)\".\nHope it helps... Happy coding :)\n",
"These lines need to be in your apache2 site configuration file\n(for example /etc/apache2/sites-available/default-ssl.conf\nif your website uses HTTPS):\n<Directory /var/www/yoursite/yourdir/>\n Options +ExecCGI\n PassEnv LANG\n AddHandler cgi-script .py\n</Directory>\n\nAdd them for the directory you want and restart apache2. You might also need to add\nAddHandler python-program .py\n\nto your httpd.conf if not present already.\nA more detailed discussion concerning python scripts and apache2 is found here: Executing a Python script in Apache2.\n",
"Probably the problem you're running in Python 3 and your code is written in Python 2\nChange the title to python2:\n#!/usr/bin/python\nprint \"Content-type: text/html\\n\"\nprint \"Hello, world!\"\n\n",
"For just proof of concept, use this python script ; No input nor output needed.\n#!/usr/bin/env python3\nimport cgitb\ncgitb.enable()\noutputfile = open(\"javascriptPython.out\", \"a\")\noutputfile.write(\"Hello from Python\\n\\n\")\n\n"
] | [
7,
4,
0,
0
] | [] | [] | [
"apache2",
"cgi",
"python",
"server_side_scripting",
"ubuntu"
] | stackoverflow_0044871139_apache2_cgi_python_server_side_scripting_ubuntu.txt |
Q:
How would I select all rows that contain a specific genre and aggregate the columns?
Here is a very simple database schema I made on the fly where the primary entity: movie, has two many-to-many relationships with genres, actors, along with their respective bridge tables:
database schema
Here is query I am using get all movies and all the actors and genres belonging to those movies (note: the actual actors and genres are not accurate as they've been randomized to serve as quick mock data).
SELECT
movie.movie_id,
string_agg(DISTINCT movie_name, ',') AS "movies",
string_agg(DISTINCT genre.genre_name, ',') AS "genres",
string_agg(DISTINCT actor.actor_name, ',') AS "actors"
FROM movie
INNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id
INNER JOIN genre ON movie_genre.genre_id = genre.genre_id
INNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id
INNER JOIN actor ON movie_actor.actor_id = actor.actor_id
GROUP BY movie.movie_id;
Example of result:
result
Now what I want to do is search for all movies that contain a specific genre such as action but I also want to include the other genres as well in the result. How would I accomplish this in the most efficient way?
Here is what I've tried so far:
SELECT
movie.movie_id,
string_agg(DISTINCT movie_name, ',') AS "movies",
string_agg(DISTINCT genre.genre_name, ',') AS "genres",
string_agg(DISTINCT actor.actor_name, ',') AS "actors"
FROM movie
INNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id
INNER JOIN genre ON movie_genre.genre_id = genre.genre_id
INNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id
INNER JOIN actor ON movie_actor.actor_id = actor.actor_id
WHERE EXISTS (SELECT 1
FROM movie_genre
WHERE LOWER(genre_name) = 'action')
GROUP BY movie.movie_id;
While this works to filter the data, it excludes all of the genres except for the one inside the where clause as seen in the image below:
only one genre
How would I instead get something like the below instead when filtering and how would I make it as efficient as possible?
What I want: (multiple genres showing under the genres column after searching) :
result
A:
To achieve the result you want, you can use a combination of CASE statements and GROUP BY to filter the genres.
Here is one way to do this:
SELECT
movie.movie_id,
string_agg(DISTINCT movie_name, ',') AS "movies",
string_agg(DISTINCT
CASE
WHEN LOWER(genre.genre_name) = 'action' THEN genre.genre_name
ELSE NULL
END, ',') AS "action_genres",
string_agg(DISTINCT
CASE
WHEN LOWER(genre.genre_name) != 'action' THEN genre.genre_name
ELSE NULL
END, ',') AS "other_genres",
string_agg(DISTINCT actor.actor_name, ',') AS "actors"
FROM movie
INNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id
INNER JOIN genre ON movie_genre.genre_id = genre.genre_id
INNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id
INNER JOIN actor ON movie_actor.actor_id = actor.actor_id
GROUP BY movie.movie_id;
This will return a result set with two columns for genres, one for action genres and one for other genres. This way, you can filter the genres based on the action genre, while still maintaining the other genres in the result set.
You can further optimize the query by using a subquery to filter the movies by the action genre before joining to the other tables. This will reduce the amount of data that needs to be processed by the rest of the query, which can improve its performance. Here is an example of how you can do this:
SELECT
movie.movie_id,
string_agg(DISTINCT movie_name, ',') AS "movies",
string_agg(DISTINCT genre.genre_name, ',') AS "genres",
string_agg(DISTINCT actor.actor_name, ',') AS "actors"
FROM (
SELECT movie_id
FROM movie_genre
WHERE LOWER(genre_name) = 'action'
) AS action_movies
INNER JOIN movie ON action_movies.movie_id = movie.movie_id
INNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id
INNER JOIN genre ON movie_genre.genre_id = genre.genre_id
INNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id
INNER JOIN actor ON movie_actor.actor_id = actor.actor_id
GROUP BY movie.movie_id;
This query will first select only the movies that have the action genre, and then join to the other tables to get the full information for those movies. This can help improve the performance of the query, especially if there are a large number of movies in the database.
| How would I select all rows that contain a specific genre and aggregate the columns? | Here is a very simple database schema I made on the fly where the primary entity: movie, has two many-to-many relationships with genres, actors, along with their respective bridge tables:
database schema
Here is query I am using get all movies and all the actors and genres belonging to those movies (note: the actual actors and genres are not accurate as they've been randomized to serve as quick mock data).
SELECT
movie.movie_id,
string_agg(DISTINCT movie_name, ',') AS "movies",
string_agg(DISTINCT genre.genre_name, ',') AS "genres",
string_agg(DISTINCT actor.actor_name, ',') AS "actors"
FROM movie
INNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id
INNER JOIN genre ON movie_genre.genre_id = genre.genre_id
INNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id
INNER JOIN actor ON movie_actor.actor_id = actor.actor_id
GROUP BY movie.movie_id;
Example of result:
result
Now what I want to do is search for all movies that contain a specific genre such as action but I also want to include the other genres as well in the result. How would I accomplish this in the most efficient way?
Here is what I've tried so far:
SELECT
movie.movie_id,
string_agg(DISTINCT movie_name, ',') AS "movies",
string_agg(DISTINCT genre.genre_name, ',') AS "genres",
string_agg(DISTINCT actor.actor_name, ',') AS "actors"
FROM movie
INNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id
INNER JOIN genre ON movie_genre.genre_id = genre.genre_id
INNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id
INNER JOIN actor ON movie_actor.actor_id = actor.actor_id
WHERE EXISTS (SELECT 1
FROM movie_genre
WHERE LOWER(genre_name) = 'action')
GROUP BY movie.movie_id;
While this works to filter the data, it excludes all of the genres except for the one inside the where clause as seen in the image below:
only one genre
How would I instead get something like the below instead when filtering and how would I make it as efficient as possible?
What I want: (multiple genres showing under the genres column after searching) :
result
| [
"To achieve the result you want, you can use a combination of CASE statements and GROUP BY to filter the genres.\nHere is one way to do this:\nSELECT \n movie.movie_id, \n string_agg(DISTINCT movie_name, ',') AS \"movies\", \n string_agg(DISTINCT \n CASE\n WHEN LOWER(genre.genre_name) = 'action' THEN genre.genre_name\n ELSE NULL\n END, ',') AS \"action_genres\",\n string_agg(DISTINCT \n CASE\n WHEN LOWER(genre.genre_name) != 'action' THEN genre.genre_name\n ELSE NULL\n END, ',') AS \"other_genres\",\n string_agg(DISTINCT actor.actor_name, ',') AS \"actors\"\nFROM movie\nINNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id\nINNER JOIN genre ON movie_genre.genre_id = genre.genre_id\nINNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id\nINNER JOIN actor ON movie_actor.actor_id = actor.actor_id\nGROUP BY movie.movie_id;\n\nThis will return a result set with two columns for genres, one for action genres and one for other genres. This way, you can filter the genres based on the action genre, while still maintaining the other genres in the result set.\nYou can further optimize the query by using a subquery to filter the movies by the action genre before joining to the other tables. This will reduce the amount of data that needs to be processed by the rest of the query, which can improve its performance. Here is an example of how you can do this:\nSELECT \n movie.movie_id, \n string_agg(DISTINCT movie_name, ',') AS \"movies\", \n string_agg(DISTINCT genre.genre_name, ',') AS \"genres\",\n string_agg(DISTINCT actor.actor_name, ',') AS \"actors\"\nFROM (\n SELECT movie_id\n FROM movie_genre\n WHERE LOWER(genre_name) = 'action'\n) AS action_movies\nINNER JOIN movie ON action_movies.movie_id = movie.movie_id\nINNER JOIN movie_genre ON movie.movie_id = movie_genre.movie_id\nINNER JOIN genre ON movie_genre.genre_id = genre.genre_id\nINNER JOIN movie_actor ON movie.movie_id = movie_actor.movie_id\nINNER JOIN actor ON movie_actor.actor_id = actor.actor_id\nGROUP BY movie.movie_id;\n\nThis query will first select only the movies that have the action genre, and then join to the other tables to get the full information for those movies. This can help improve the performance of the query, especially if there are a large number of movies in the database.\n"
] | [
0
] | [] | [] | [
"database",
"postgresql",
"sql"
] | stackoverflow_0074671642_database_postgresql_sql.txt |
Q:
Pycharm how to switch back to English?
I have been using Pycharm in English but today when I opened it, its interface got partially translated to Chinese, totally unexpected and unwanted.
How can I switch back to English without reinstalling Pycharm? Thanks!
A:
go for settings and make it as default settings,consider the below image for the referance,count the row and select ok
A:
New version of pycharm let you unselect the Chinese interface and back to English interface.
| Pycharm how to switch back to English? | I have been using Pycharm in English but today when I opened it, its interface got partially translated to Chinese, totally unexpected and unwanted.
How can I switch back to English without reinstalling Pycharm? Thanks!
| [
"go for settings and make it as default settings,consider the below image for the referance,count the row and select ok\n",
"New version of pycharm let you unselect the Chinese interface and back to English interface.\n"
] | [
2,
0
] | [] | [] | [
"internationalization",
"locale",
"pycharm",
"python",
"user_interface"
] | stackoverflow_0047129007_internationalization_locale_pycharm_python_user_interface.txt |
Q:
Converting buffer to array of strings
I downloaded text from the edit field to the buffer and I want to convert it to an array of strings. Every string is ending with %.
void Converter(HWND hwnd)
{
int Length = GetWindowTextLength(hEdit) + 1;
LPSTR data = (LPSTR)malloc(Length);
char set[500][11];
GetWindowTextA(hEdit, data, Length);
int x = 0, y = 0;
char record[10];
for (int i = 0; i < Length, x<500; i++)
{
if(data[i]!= '\0' )
{
record[y] = data[i];
y++;
}
else if(data[i] == '%')
{
strcpy(set[x], record);
x++;
y = 0;
}
}
free(data);
}
The error message I got:
Exception thrown at location 0x00007FF684C91F9B in myproject.exe: 0xC0000005: Access violation while reading at location 0x000000CBFC8D5DAF.
A:
The problem is in this line
for (int i = 0; i < Length, x<500; i++)
Your condition is wrong, it should be:
for (int i = 0; i < Length && x<500; i++)
Also, the else if block is never executed, because '%' is not equal to '\0'. This can be fixed by swapping them.
if(data[i] == '%')
{
strcpy(set[x], record);
x++;
y = 0;
}
else if(data[i] != '\0')
{
record[y] = data[i];
y++;
}
The third problem is that the last word in your %-delimited string will not be copied into set since there is no percent sign after it.
There is one more bug. You forgot to put a null-terminator at the end of record before copying it, this causes shorter strings to retain letters from previous ones.
record[y] = '\0';
strcpy(set[x], record);
At this point I recommend using strtok from <string.h>, and a memory safe programming language like Rust.
A:
Sample code to show strcpy with 2d array is use:
#include <stdio.h>
int main() {
char set[500][11];
strcpy(&set[x][0], "a record");
printf(">> %s", &set[x][0]);
}
Output:
>> a record
A:
you can do like this
char** make_array(_In_ char* buf, _Out_ unsigned* pn)
{
char* pc = buf;
unsigned n = 1;
while(pc = strchr(pc, '%')) n++, *pc++ = 0;
if (char** arr = new char*[n])
{
*pn = n;
char** ppc = arr;
do {
*ppc++ = buf;
buf += strlen(buf) + 1;
} while(--n);
return arr;
}
*pn = 0;
return 0;
}
void demo()
{
char buf[] = "1111%2222%33333";
unsigned n;
if (char** arr = make_array(buf, &n))
{
char** ppc = arr;
do {
printf("%s\n", *ppc++);
} while (--n);
delete [] arr;
}
}
| Converting buffer to array of strings | I downloaded text from the edit field to the buffer and I want to convert it to an array of strings. Every string is ending with %.
void Converter(HWND hwnd)
{
int Length = GetWindowTextLength(hEdit) + 1;
LPSTR data = (LPSTR)malloc(Length);
char set[500][11];
GetWindowTextA(hEdit, data, Length);
int x = 0, y = 0;
char record[10];
for (int i = 0; i < Length, x<500; i++)
{
if(data[i]!= '\0' )
{
record[y] = data[i];
y++;
}
else if(data[i] == '%')
{
strcpy(set[x], record);
x++;
y = 0;
}
}
free(data);
}
The error message I got:
Exception thrown at location 0x00007FF684C91F9B in myproject.exe: 0xC0000005: Access violation while reading at location 0x000000CBFC8D5DAF.
| [
"The problem is in this line\nfor (int i = 0; i < Length, x<500; i++)\n\nYour condition is wrong, it should be:\nfor (int i = 0; i < Length && x<500; i++)\n\nAlso, the else if block is never executed, because '%' is not equal to '\\0'. This can be fixed by swapping them.\nif(data[i] == '%')\n{\n strcpy(set[x], record);\n x++;\n y = 0;\n}\nelse if(data[i] != '\\0')\n{\n record[y] = data[i];\n y++;\n}\n\nThe third problem is that the last word in your %-delimited string will not be copied into set since there is no percent sign after it.\nThere is one more bug. You forgot to put a null-terminator at the end of record before copying it, this causes shorter strings to retain letters from previous ones.\nrecord[y] = '\\0';\nstrcpy(set[x], record);\n\nAt this point I recommend using strtok from <string.h>, and a memory safe programming language like Rust.\n",
"Sample code to show strcpy with 2d array is use:\n#include <stdio.h>\n\nint main() {\n \n char set[500][11];\n \n strcpy(&set[x][0], \"a record\");\n\n printf(\">> %s\", &set[x][0]);\n}\n\nOutput:\n>> a record\n\n",
"you can do like this\nchar** make_array(_In_ char* buf, _Out_ unsigned* pn)\n{\n char* pc = buf;\n unsigned n = 1;\n \n while(pc = strchr(pc, '%')) n++, *pc++ = 0;\n\n if (char** arr = new char*[n])\n {\n *pn = n;\n\n char** ppc = arr;\n \n do {\n *ppc++ = buf;\n buf += strlen(buf) + 1;\n } while(--n);\n\n return arr;\n }\n\n *pn = 0;\n return 0;\n}\n\nvoid demo()\n{\n char buf[] = \"1111%2222%33333\";\n unsigned n;\n if (char** arr = make_array(buf, &n))\n {\n char** ppc = arr;\n do {\n printf(\"%s\\n\", *ppc++);\n } while (--n);\n delete [] arr;\n }\n}\n\n"
] | [
2,
0,
0
] | [] | [] | [
"c",
"winapi"
] | stackoverflow_0074671112_c_winapi.txt |
Q:
RelativeLayout add multiple view one below another
I want to make add button that add the views one below another. I dont want a Listview. I tried settings id's on each views and then add using setIDs but when I click on the button the views are created excacly on the same spot.
final Button addView = (Button)findViewById(R.id.addView);
mainLayout = (RelativeLayout)findViewById(R.id.activity_mainID);
final RelativeLayout rv = new RelativeLayout(MainActivity.this);
rv.setId(-1);
TextView tx = new TextView(this);
rv.setBackgroundColor(ContextCompat.getColor(this,R.color.colorAccent));
rv.addView(tx);
mainLayout.addView(rv,100,100);
addView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout view = new RelativeLayout(MainActivity.this);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(200,200);
view.setId(id);
TextView tv = new TextView(MainActivity.this);
tv.setText("TEXT"+id);
view.addView(tv);
view.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorPrimary));
params1.addRule(RelativeLayout.BELOW, id--);
mainLayout.addView(view,params1);
id=id+2;
}
});
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="10"
android:id="@+id/activity_mainID"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/addView"
android:text="ADD"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
EDIT: I solve my problem using LinearLayout, but still dont know what is incorrect in my first solution. If someone discover it please share with me.
A:
I have tried to do the same and faced odd problems when my initial id was -1, 0 or 1. Setting it to a higher initial number (I set it to 4) and suddenly everything works as expected. I guess the reason is that these values represent constants in the ViewGroup class.
A:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_mainID">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/addView"
android:text="ADD"
android:layout_below="@+id/activity_mainID"/>
</RelativeLayout>
| RelativeLayout add multiple view one below another | I want to make add button that add the views one below another. I dont want a Listview. I tried settings id's on each views and then add using setIDs but when I click on the button the views are created excacly on the same spot.
final Button addView = (Button)findViewById(R.id.addView);
mainLayout = (RelativeLayout)findViewById(R.id.activity_mainID);
final RelativeLayout rv = new RelativeLayout(MainActivity.this);
rv.setId(-1);
TextView tx = new TextView(this);
rv.setBackgroundColor(ContextCompat.getColor(this,R.color.colorAccent));
rv.addView(tx);
mainLayout.addView(rv,100,100);
addView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout view = new RelativeLayout(MainActivity.this);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(200,200);
view.setId(id);
TextView tv = new TextView(MainActivity.this);
tv.setText("TEXT"+id);
view.addView(tv);
view.setBackgroundColor(ContextCompat.getColor(MainActivity.this,R.color.colorPrimary));
params1.addRule(RelativeLayout.BELOW, id--);
mainLayout.addView(view,params1);
id=id+2;
}
});
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="10"
android:id="@+id/activity_mainID"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/addView"
android:text="ADD"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
EDIT: I solve my problem using LinearLayout, but still dont know what is incorrect in my first solution. If someone discover it please share with me.
| [
"I have tried to do the same and faced odd problems when my initial id was -1, 0 or 1. Setting it to a higher initial number (I set it to 4) and suddenly everything works as expected. I guess the reason is that these values represent constants in the ViewGroup class.\n",
" <RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/activity_mainID\">\n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/addView\"\n android:text=\"ADD\"\n android:layout_below=\"@+id/activity_mainID\"/>\n </RelativeLayout>\n\n"
] | [
0,
0
] | [] | [] | [
"android",
"android_layout",
"view"
] | stackoverflow_0040383882_android_android_layout_view.txt |
Q:
SPARQL filter by date for multiple predicates parameters with same subject
I would like to select the car brands (filter contains prefix "dbr:") where schema:Motor and filter schema:dateManufactured > year 2000.
This is the source data (at the bottom you will find my query).
As per RedCrusaderJr answer, we got now the brands but I don't know how to specify the query to filter the date of manufacture and the schema:Motor.
cars = '''@prefix ex: <https://example.org/resource/> .
@prefix schema: <https://schema.org/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix dbr: <http://dbpedia.org/resource/> .
@prefix dbo: <http://dbpedia.org/ontology/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
ex:Mustang ex:Deportivo dbr:Ford ;
schema:Motor ex:Gasolina ;
ex:potencia "450";
ex:km "120000";
schema:dateManufactured "2020-05-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ford Mustang GT"@en .
ex:GT ex:Deportivo dbr:Ford ;
schema:Motor ex:Gasolina ;
ex:potencia "550";
ex:km "25000";
schema:dateManufactured "1968-04-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ford GT"@en .
ex:Fiesta ex:Utilitario dbr:Ford ;
schema:Motor ex:Diesel ;
ex:potencia "100";
ex:km "45000";
schema:dateManufactured "2020-02-10"^^xsd:date ;
rdfs:label "Ford Fiesta"@en .
ex:206 ex:Utilitario dbr:Peugeot ;
schema:Motor ex:Diesel ;
ex:potencia "68";
ex:km "173100";
schema:dateManufactured "2004-01-01"^^xsd:date ;
rdfs:label "Peugeot 206"@en .
ex:California ex:Deportivo dbr:Ferrari;
schema:Motor ex:Gasolina;
ex:potencia "460";
ex:km "500000";
schema:dateManufactured "2010-05-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ferrari California"@en .
ex:Enzo ex:Deportivo dbr:Ferrari;
schema:Motor ex:Gasolina;
ex:potencia "";
ex:km "200000";
schema:dateManufactured "2002-05-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ferrari Enzo"@en .
'''
g_q1 = RDFGraph()
g_q1.parse (data=cars, format="turtle")
my initial query ='''
SELECT ?h
{
?h schema:Motor ?t;
:dateManufactured ?date.
FILTER (?date > "2000-12-31"^^xsd:date)
}
'''
RedCrusaderJr answer = SELECT *
{
{
SELECT DISTINCT ?o
{
?s ?p ?o
FILTER CONTAINS(str(?o), "http://dbpedia.org/resource/")
}
}
#here I understand it would go the schema:motor and date manufactured part.
}
Thanks!
A:
For the follow up on the original question, if I understand you correctly, you want all URIs with a specific prefix, which you'd get with this query:
SELECT DISTINCT ?o
{
?s ?p ?o
FILTER CONTAINS(str(?o), "http://dbpedia.org/resource/")
}
For your data set you'd get these URIs:
dbpedia:Ford
dbpedia:LeMans
dbpedia:Peugeot
dbpedia:Delorean_Motor_Company
dbpedia:Pontiac
dbpedia:Ferrari
And if you want to use those URIs further on, you can do it like this:
SELECT *
{
{
SELECT DISTINCT ?o
{
?s ?p ?o
FILTER CONTAINS(str(?o), "http://dbpedia.org/resource/")
}
}
#rest of the query where ?o can be used
}
EDIT:
If I run this
SELECT ?car ?brand ?motor ?dateManufactured
{
?car ex:Deportivo ?brand;
schema:Motor ?motor;
schema:dateManufactured ?dateManufactured.
FILTER (?dateManufactured > "2000-12-31"^^xsd:date)
}
I get these triples
car brand motor dateManufactured
ex:Mustang dbpedia:Ford ex:Gasolina "2020-05-29"
ex:California dbpedia:Ferrari ex:Gasolina "2010-05-29"
ex:Enzo dbpedia:Ferrari ex:Gasolina "2002-05-29"
Can you edit your answer again, so I can see exactly what result you want to get? If you want to merge brands with car/motor/dateManufactured, you don't have to get all brands first, but simply use the ex:Deportivo that connect them -> ?car ex:Deportivo ?brand.
| SPARQL filter by date for multiple predicates parameters with same subject | I would like to select the car brands (filter contains prefix "dbr:") where schema:Motor and filter schema:dateManufactured > year 2000.
This is the source data (at the bottom you will find my query).
As per RedCrusaderJr answer, we got now the brands but I don't know how to specify the query to filter the date of manufacture and the schema:Motor.
cars = '''@prefix ex: <https://example.org/resource/> .
@prefix schema: <https://schema.org/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix dbr: <http://dbpedia.org/resource/> .
@prefix dbo: <http://dbpedia.org/ontology/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
ex:Mustang ex:Deportivo dbr:Ford ;
schema:Motor ex:Gasolina ;
ex:potencia "450";
ex:km "120000";
schema:dateManufactured "2020-05-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ford Mustang GT"@en .
ex:GT ex:Deportivo dbr:Ford ;
schema:Motor ex:Gasolina ;
ex:potencia "550";
ex:km "25000";
schema:dateManufactured "1968-04-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ford GT"@en .
ex:Fiesta ex:Utilitario dbr:Ford ;
schema:Motor ex:Diesel ;
ex:potencia "100";
ex:km "45000";
schema:dateManufactured "2020-02-10"^^xsd:date ;
rdfs:label "Ford Fiesta"@en .
ex:206 ex:Utilitario dbr:Peugeot ;
schema:Motor ex:Diesel ;
ex:potencia "68";
ex:km "173100";
schema:dateManufactured "2004-01-01"^^xsd:date ;
rdfs:label "Peugeot 206"@en .
ex:California ex:Deportivo dbr:Ferrari;
schema:Motor ex:Gasolina;
ex:potencia "460";
ex:km "500000";
schema:dateManufactured "2010-05-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ferrari California"@en .
ex:Enzo ex:Deportivo dbr:Ferrari;
schema:Motor ex:Gasolina;
ex:potencia "";
ex:km "200000";
schema:dateManufactured "2002-05-29"^^xsd:date ;
schema:wasInCompetition dbr:LeMans;
rdfs:label "Ferrari Enzo"@en .
'''
g_q1 = RDFGraph()
g_q1.parse (data=cars, format="turtle")
my initial query ='''
SELECT ?h
{
?h schema:Motor ?t;
:dateManufactured ?date.
FILTER (?date > "2000-12-31"^^xsd:date)
}
'''
RedCrusaderJr answer = SELECT *
{
{
SELECT DISTINCT ?o
{
?s ?p ?o
FILTER CONTAINS(str(?o), "http://dbpedia.org/resource/")
}
}
#here I understand it would go the schema:motor and date manufactured part.
}
Thanks!
| [
"For the follow up on the original question, if I understand you correctly, you want all URIs with a specific prefix, which you'd get with this query:\nSELECT DISTINCT ?o\n{ \n ?s ?p ?o\n FILTER CONTAINS(str(?o), \"http://dbpedia.org/resource/\")\n}\n\nFor your data set you'd get these URIs:\ndbpedia:Ford\ndbpedia:LeMans\ndbpedia:Peugeot\ndbpedia:Delorean_Motor_Company\ndbpedia:Pontiac\ndbpedia:Ferrari\n\nAnd if you want to use those URIs further on, you can do it like this:\nSELECT * \n{\n {\n SELECT DISTINCT ?o\n { \n ?s ?p ?o\n FILTER CONTAINS(str(?o), \"http://dbpedia.org/resource/\")\n }\n }\n\n #rest of the query where ?o can be used\n}\n\n\n\nEDIT:\n\n\nIf I run this\nSELECT ?car ?brand ?motor ?dateManufactured\n{\n ?car ex:Deportivo ?brand;\n schema:Motor ?motor;\n schema:dateManufactured ?dateManufactured.\n FILTER (?dateManufactured > \"2000-12-31\"^^xsd:date)\n}\n\nI get these triples\ncar brand motor dateManufactured\nex:Mustang dbpedia:Ford ex:Gasolina \"2020-05-29\"\nex:California dbpedia:Ferrari ex:Gasolina \"2010-05-29\"\nex:Enzo dbpedia:Ferrari ex:Gasolina \"2002-05-29\"\n\nCan you edit your answer again, so I can see exactly what result you want to get? If you want to merge brands with car/motor/dateManufactured, you don't have to get all brands first, but simply use the ex:Deportivo that connect them -> ?car ex:Deportivo ?brand.\n"
] | [
0
] | [] | [] | [
"python",
"rdf",
"schema",
"sparql"
] | stackoverflow_0074666967_python_rdf_schema_sparql.txt |
Q:
checking for collision of a rotated shape in p5.js
I am trying to recreate the game duet but I can't figure out how to check collision on an that has been translated and rotated.
To rotate my players blue and red ball I translated the object to the center of the screen and then rotated it based on that point.
here is my code (I know its not the best code, this is just a prototype)
how can I check for collision with the white obstacles and the players circles?
What exactly happens to the X and Y coordinates when you translate/rotate the shape?
A:
If you don't mind your polygon hit testing being based on a single point then it is fairly trivial. You can implement the point in polygon algorithm which basically consists of counting intersections between a horizontal line and the edges of the polygon.
const pts = []
function setup() {
createCanvas(windowWidth, windowHeight);
pts.push(
createVector(56, 89), createVector(108, 37), createVector(117, 118)
)
}
function draw() {
background('#fff29c');
if (pts.length > 1) {
stroke('#301551');
fill(pointInPoly(pts, createVector(mouseX, mouseY)) ? 'white' : 'grey');
beginShape();
pts.forEach(pt => vertex(pt.x, pt.y));
endShape(CLOSE);
} else if (pts.length == 1) {
stroke('#301551');
beginShape();
pts.forEach(pt => vertex(pt.x, pt.y));
vertex(mouseX, mouseY);
endShape(CLOSE);
}
stroke('white');
line(0, mouseY, mouseX, mouseY);
noStroke();
intersections.sort((v1, v2) => v1.x < v2.x ? -1 : (v1.x > v2.x ? 1 : 0))
for (let i = 0; i < intersections.length; i++) {
fill(i % 2 == 0 ? 'green': 'red');
circle(intersections[i].x, intersections[i].y, 5);
}
fill('#ed8a0a');
noStroke();
circle(mouseX, mouseY, 10);
}
let intersections = [];
function pointInPoly(verts, pt) {
intersections = [];
let c = false;
// for each edge of the polygon
for (let i = 0, j = verts.length - 1; i < verts.length; j = i++) {
// Compute the slope of the edge
let slope = (verts[j].y - verts[i].y) / (verts[j].x - verts[i].x);
// If the mouse is positioned within the vertical bounds of the edge
if (((verts[i].y > pt.y) != (verts[j].y > pt.y)) &&
// And it is far enough to the right that a horizontal line from the
// left edge of the screen to the mouse would cross the edge
(pt.x > (pt.y - verts[i].y) / slope + verts[i].x)) {
// To help visualize the algorithm.
intersections.push({ x: (pt.y - verts[i].y) / slope + verts[i].x, y: mouseY });
// Flip the flag
c = !c;
}
}
return c;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>
If you want your hit testing to be based on a circle you could also perform collision detection between the circle and each polygon edge segment in addition to the point-in-polygon algorithm.
Here is a description of how to do this from a tutorial I wrote on detecting calculating circle collisions:
Given a line defined by two points on that line (p1 and p2), let the boundaryVector be a vector from the first point to the second. We will assume that the vector produced by rotating boundaryVector clockwise 90 degrees orients it towards the inside of the bounded area. In other words the points must be specified in a clockwise order around the boundary.
Given boundaryVector we can find the distance of the center of a circular body, give by pos, to the nearest point on the line, by taking the distance from p1 to pos, and multiplying it by the sine of the angle between boundaryVector and the vector from p1 to pos.
If the distance from the center of the circular body to the nearest point on the line is less than or equal to the radius of the circle, then a collision has occurred.
This assumes that the boundary is infinite, but you should be able to adopt this technique to properly handle finite line segments.
| checking for collision of a rotated shape in p5.js | I am trying to recreate the game duet but I can't figure out how to check collision on an that has been translated and rotated.
To rotate my players blue and red ball I translated the object to the center of the screen and then rotated it based on that point.
here is my code (I know its not the best code, this is just a prototype)
how can I check for collision with the white obstacles and the players circles?
What exactly happens to the X and Y coordinates when you translate/rotate the shape?
| [
"If you don't mind your polygon hit testing being based on a single point then it is fairly trivial. You can implement the point in polygon algorithm which basically consists of counting intersections between a horizontal line and the edges of the polygon.\n\n\nconst pts = []\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n pts.push(\n createVector(56, 89), createVector(108, 37), createVector(117, 118) \n )\n}\n\nfunction draw() {\n background('#fff29c');\n\n if (pts.length > 1) {\n stroke('#301551');\n fill(pointInPoly(pts, createVector(mouseX, mouseY)) ? 'white' : 'grey');\n beginShape();\n pts.forEach(pt => vertex(pt.x, pt.y));\n endShape(CLOSE);\n } else if (pts.length == 1) {\n stroke('#301551');\n beginShape();\n pts.forEach(pt => vertex(pt.x, pt.y));\n vertex(mouseX, mouseY);\n endShape(CLOSE);\n }\n \n stroke('white');\n line(0, mouseY, mouseX, mouseY);\n noStroke();\n intersections.sort((v1, v2) => v1.x < v2.x ? -1 : (v1.x > v2.x ? 1 : 0))\n for (let i = 0; i < intersections.length; i++) {\n fill(i % 2 == 0 ? 'green': 'red');\n circle(intersections[i].x, intersections[i].y, 5);\n }\n\n fill('#ed8a0a');\n noStroke();\n circle(mouseX, mouseY, 10);\n}\n\nlet intersections = [];\n\nfunction pointInPoly(verts, pt) {\n intersections = [];\n let c = false;\n // for each edge of the polygon\n for (let i = 0, j = verts.length - 1; i < verts.length; j = i++) {\n // Compute the slope of the edge\n let slope = (verts[j].y - verts[i].y) / (verts[j].x - verts[i].x);\n \n // If the mouse is positioned within the vertical bounds of the edge\n if (((verts[i].y > pt.y) != (verts[j].y > pt.y)) &&\n // And it is far enough to the right that a horizontal line from the\n // left edge of the screen to the mouse would cross the edge\n (pt.x > (pt.y - verts[i].y) / slope + verts[i].x)) {\n \n // To help visualize the algorithm.\n intersections.push({ x: (pt.y - verts[i].y) / slope + verts[i].x, y: mouseY });\n // Flip the flag\n c = !c;\n }\n }\n return c;\n}\n<script src=\"https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js\"></script>\n\n\n\nIf you want your hit testing to be based on a circle you could also perform collision detection between the circle and each polygon edge segment in addition to the point-in-polygon algorithm.\nHere is a description of how to do this from a tutorial I wrote on detecting calculating circle collisions:\n\nGiven a line defined by two points on that line (p1 and p2), let the boundaryVector be a vector from the first point to the second. We will assume that the vector produced by rotating boundaryVector clockwise 90 degrees orients it towards the inside of the bounded area. In other words the points must be specified in a clockwise order around the boundary.\n\n\nGiven boundaryVector we can find the distance of the center of a circular body, give by pos, to the nearest point on the line, by taking the distance from p1 to pos, and multiplying it by the sine of the angle between boundaryVector and the vector from p1 to pos.\n\n\n\nIf the distance from the center of the circular body to the nearest point on the line is less than or equal to the radius of the circle, then a collision has occurred.\n\nThis assumes that the boundary is infinite, but you should be able to adopt this technique to properly handle finite line segments.\n"
] | [
1
] | [] | [] | [
"collision_detection",
"javascript",
"p5.js",
"processing",
"rotation"
] | stackoverflow_0074636513_collision_detection_javascript_p5.js_processing_rotation.txt |
Q:
Inserting alpha value to a 4-dimentsional RGB numpy array
Following this tutorial, I am trying to build a color cube in matplotlib.
spatialAxes = [self.step, self.step, self.step]
r, g, b= np.indices((self.step+1, self.step+1, self.step+1)) / 16.0
rc = self.midpoints(r)
gc = self.midpoints(g)
bc = self.midpoints(b)
cube = np.ones(spatialAxes, dtype=np.bool)
# combine the color components
colors = np.zeros(cube.shape + (3,))
colors[..., 0] = rc
colors[..., 1] = gc
colors[..., 2] = bc
self.axes.voxels(r, g, b, cube,
facecolors = colors,
linewidth = 0)
midpoints is from the link above and is defined as
def midpoints(self, x):
sl = ()
for i in range(x.ndim):
x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
sl += np.index_exp[:]
return x
This does produce a color cube, but it is completely opaque. So I tried to add opacity by:
colors = np.dstack( (colors, np.ones(spatialAxes) * .5) ) # .5 opacity
Which did not work.
Given that colors is a 4-dimensional array with a shape of (X, X, X, 3), where X is the value of self.step. How do I append the alpha channel to this array?
A:
You can make colors an array with a forth component like this:
# combine the color components
colors = np.zeros(sphere.shape + (4, ))
colors[..., 0] = rc
colors[..., 1] = gc
colors[..., 2] = bc
colors[..., 3] = 0.2 # opacity (alpha)
BTW, I (half unconsciously) used the matplotlib example that you linked to. The challenge with your code is that it's not complete, so I cannot run it myself (hint ;)).
| Inserting alpha value to a 4-dimentsional RGB numpy array | Following this tutorial, I am trying to build a color cube in matplotlib.
spatialAxes = [self.step, self.step, self.step]
r, g, b= np.indices((self.step+1, self.step+1, self.step+1)) / 16.0
rc = self.midpoints(r)
gc = self.midpoints(g)
bc = self.midpoints(b)
cube = np.ones(spatialAxes, dtype=np.bool)
# combine the color components
colors = np.zeros(cube.shape + (3,))
colors[..., 0] = rc
colors[..., 1] = gc
colors[..., 2] = bc
self.axes.voxels(r, g, b, cube,
facecolors = colors,
linewidth = 0)
midpoints is from the link above and is defined as
def midpoints(self, x):
sl = ()
for i in range(x.ndim):
x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
sl += np.index_exp[:]
return x
This does produce a color cube, but it is completely opaque. So I tried to add opacity by:
colors = np.dstack( (colors, np.ones(spatialAxes) * .5) ) # .5 opacity
Which did not work.
Given that colors is a 4-dimensional array with a shape of (X, X, X, 3), where X is the value of self.step. How do I append the alpha channel to this array?
| [
"You can make colors an array with a forth component like this:\n# combine the color components\ncolors = np.zeros(sphere.shape + (4, ))\ncolors[..., 0] = rc\ncolors[..., 1] = gc\ncolors[..., 2] = bc\ncolors[..., 3] = 0.2 # opacity (alpha)\n\nBTW, I (half unconsciously) used the matplotlib example that you linked to. The challenge with your code is that it's not complete, so I cannot run it myself (hint ;)).\n"
] | [
1
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074671536_matplotlib_numpy_python.txt |
Q:
I need help regarding a python error: _tkinter.TclError: bitmap "class.ico" not defined
I wanted to create an image classification app in python as a university project, but I get the error you can see on the pic below:
Error message:
Error_image
I have 2 python files a teach.py, which teaches the pictures to the algorithm and saves it and a main.py which loads the saved model and a gui to uplad and predict the images, but when I debug I get the error don't know why neither do I know how to fix it...
You can see main.py below:
main.py:
import keras
import numpy as np
import gradio as gr
import pathlib
import os
import PIL
import tkinter as tk
import warnings
import h5py
import zipfile
import tensorflow as tf
import joblib
import globals
import matplotlib.pyplot as plt
from keras.applications import vgg16
from keras.applications.vgg16 import decode_predictions
from keras.utils import img_to_array
from tkinter import *
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.vgg16 import preprocess_input
from keras.models import Sequential
from keras.layers import Dense,Flatten,Dropout
from sklearn import model_selection, datasets
from sklearn.tree import DecisionTreeClassifier
from pathlib import Path
from PIL import ImageTk, Image
from tkinter import filedialog
from tensorflow import keras
from keras import layers
from keras.models import Sequential
warnings.filterwarnings('ignore')
data_dir='birbs/birbs'
class_names = os.listdir(data_dir)
loaded_model = tf.keras.models.load_model("saved_model.h5")
def load_img():
global img, image_data
for img_display in frame.winfo_children():
img_display.destroy()
image_data = filedialog.askopenfilename(initialdir="/", title="Choose an image",
filetypes=(("all files", "*.*"), ("png files", "*.png")))
basewidth = 150 # Processing image for dysplaying
img = Image.open(image_data)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
file_name = image_data.split('/')
panel = tk.Label(frame, text= str(file_name[len(file_name)-1]).upper()).pack()
panel_image = tk.Label(frame, image=img).pack()
def classify():
original = Image.open(image_data)
original = original.resize((224, 224), Image.ANTIALIAS)
numpy_image = img_to_array(original)
image_batch = np.expand_dims(numpy_image, axis=0)
processed_image = vgg16.preprocess_input(image_batch.copy())
predictions = vgg_model.predict(processed_image)
label = decode_predictions(predictions)
table = tk.Label(frame, text="Top image class predictions and confidences").pack()
for i in range(0, len(label[0])):
result = tk.Label(frame, text= str(label[0][i][1]).upper() + ': ' + str(round(float(label[0][i][2])*100, 3)) + '%').pack()
root = tk.Tk()
root.title('Portable Image Classifier')
root.iconbitmap('class.ico')
root.resizable(False, False)
tit = tk.Label(root, text="Portable Image Classifier", padx=25, pady=6, font=("", 12)).pack()
canvas = tk.Canvas(root, height=500, width=500, bg='grey')
canvas.pack()
frame = tk.Frame(root, bg='white')
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
chose_image = tk.Button(root, text='Choose Image',
padx=35, pady=10,
fg="white", bg="grey", command=load_img)
chose_image.pack(side=tk.LEFT)
class_image = tk.Button(root, text='Classify Image',
padx=35, pady=10,
fg="white", bg="grey", command=classify)
class_image.pack(side=tk.RIGHT)
vgg_model = vgg16.VGG16(weights='imagenet')
root.mainloop()
A:
It looks like you are trying to use a bitmap image with the Tkinter library in Python, but the image you are trying to use has not been defined. To fix this error, you need to make sure that the bitmap image has been defined before you try to use it. This can be done by using the BitmapImage class in Tkinter to create a new instance of the image. For example:
from tkinter import BitmapImage
image = BitmapImage("class.ico")
Once you have defined the image, you can use it in your Tkinter application. For example, you can set it as the icon for a window using the iconbitmap method:
root = tk.Tk()
root.iconbitmap(image)
I hope this helps! Let me know if you have any other questions.
| I need help regarding a python error: _tkinter.TclError: bitmap "class.ico" not defined | I wanted to create an image classification app in python as a university project, but I get the error you can see on the pic below:
Error message:
Error_image
I have 2 python files a teach.py, which teaches the pictures to the algorithm and saves it and a main.py which loads the saved model and a gui to uplad and predict the images, but when I debug I get the error don't know why neither do I know how to fix it...
You can see main.py below:
main.py:
import keras
import numpy as np
import gradio as gr
import pathlib
import os
import PIL
import tkinter as tk
import warnings
import h5py
import zipfile
import tensorflow as tf
import joblib
import globals
import matplotlib.pyplot as plt
from keras.applications import vgg16
from keras.applications.vgg16 import decode_predictions
from keras.utils import img_to_array
from tkinter import *
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.vgg16 import preprocess_input
from keras.models import Sequential
from keras.layers import Dense,Flatten,Dropout
from sklearn import model_selection, datasets
from sklearn.tree import DecisionTreeClassifier
from pathlib import Path
from PIL import ImageTk, Image
from tkinter import filedialog
from tensorflow import keras
from keras import layers
from keras.models import Sequential
warnings.filterwarnings('ignore')
data_dir='birbs/birbs'
class_names = os.listdir(data_dir)
loaded_model = tf.keras.models.load_model("saved_model.h5")
def load_img():
global img, image_data
for img_display in frame.winfo_children():
img_display.destroy()
image_data = filedialog.askopenfilename(initialdir="/", title="Choose an image",
filetypes=(("all files", "*.*"), ("png files", "*.png")))
basewidth = 150 # Processing image for dysplaying
img = Image.open(image_data)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
file_name = image_data.split('/')
panel = tk.Label(frame, text= str(file_name[len(file_name)-1]).upper()).pack()
panel_image = tk.Label(frame, image=img).pack()
def classify():
original = Image.open(image_data)
original = original.resize((224, 224), Image.ANTIALIAS)
numpy_image = img_to_array(original)
image_batch = np.expand_dims(numpy_image, axis=0)
processed_image = vgg16.preprocess_input(image_batch.copy())
predictions = vgg_model.predict(processed_image)
label = decode_predictions(predictions)
table = tk.Label(frame, text="Top image class predictions and confidences").pack()
for i in range(0, len(label[0])):
result = tk.Label(frame, text= str(label[0][i][1]).upper() + ': ' + str(round(float(label[0][i][2])*100, 3)) + '%').pack()
root = tk.Tk()
root.title('Portable Image Classifier')
root.iconbitmap('class.ico')
root.resizable(False, False)
tit = tk.Label(root, text="Portable Image Classifier", padx=25, pady=6, font=("", 12)).pack()
canvas = tk.Canvas(root, height=500, width=500, bg='grey')
canvas.pack()
frame = tk.Frame(root, bg='white')
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
chose_image = tk.Button(root, text='Choose Image',
padx=35, pady=10,
fg="white", bg="grey", command=load_img)
chose_image.pack(side=tk.LEFT)
class_image = tk.Button(root, text='Classify Image',
padx=35, pady=10,
fg="white", bg="grey", command=classify)
class_image.pack(side=tk.RIGHT)
vgg_model = vgg16.VGG16(weights='imagenet')
root.mainloop()
| [
"It looks like you are trying to use a bitmap image with the Tkinter library in Python, but the image you are trying to use has not been defined. To fix this error, you need to make sure that the bitmap image has been defined before you try to use it. This can be done by using the BitmapImage class in Tkinter to create a new instance of the image. For example:\nfrom tkinter import BitmapImage\n\nimage = BitmapImage(\"class.ico\")\n\nOnce you have defined the image, you can use it in your Tkinter application. For example, you can set it as the icon for a window using the iconbitmap method:\nroot = tk.Tk()\nroot.iconbitmap(image)\n\nI hope this helps! Let me know if you have any other questions.\n"
] | [
0
] | [] | [] | [
"keras",
"machine_learning",
"python",
"tensorflow",
"tkinter"
] | stackoverflow_0074670274_keras_machine_learning_python_tensorflow_tkinter.txt |
Q:
Apache Airflow - Multiple deployment environments
When handling multiple environments (such as Dev/Staging/Prod etc) having separate (preferably identical) Airflow instances for each of these environments would be the best case scenario.
I'm using the GCP managed Airflow ( GCP Cloud Composer), which is not very cheap to run, and having multiple instances would increase our monthly bill significantly.
So, I'd like to know if anyone has recommendations on using a single Airflow instance to handle multiple environments?
One approach I was considering of was to have separate top-level folders within my dags folder corresponding to each of the environment (i.e. dags/dev, dags/prod etc)
and copy my DAG scripts to the relevant folder through the CI/CD pipeline.
So, within my source code repository if my dag looks like:
airflow_dags/my_dag_A.py
During the CI stage, I could have a build step that creates 2 separate versions of this file:
airflow_dags/DEV/my_dag_A.py
airflow_dags/PROD/my_dag_A.py
I would follow a strict naming convention for naming my DAGs, Airflow Variables etc to reflect the environment name, so that the above build step can automatically rename those accordingly.
I wanted check if this is an approach others may have used? Or are there any better/alternative suggestions?
Please let me know if any additional clarifications are needed.
Thank you in advance for your support. Highly appreciated.
A:
I think it can be a good approach to have a shared environement because it's cost effective.
However if you have a Composer cluster per environment, it's simpler to manage, and it's allows having a better separation.
If you stay on a shared environment, I think you are on the good direction with a separation on the Composer bucket DAG and a folder per environment.
If you use Airflow variables, you also have to deal with environment in addition to the DAGs part.
You can then manage the access to each folder in the bucket.
In my team, we chose another approach.
Cloud Composer uses GKE with autopilot mode and it's more cost effective than the previous version.
It's also easier to manage the environement size of the cluster and play with differents parameters (workers, cpu, webserver...).
In our case, we created a cluster per environment but we have a different configuration per environment (managed by Terraform):
For dev and uat envs, we have a little sizing and an environment size as small
For prod env, we have a higher sizing and an environment size as Medium
It's not perfect but this allows us to have a compromise between cost and separation.
| Apache Airflow - Multiple deployment environments | When handling multiple environments (such as Dev/Staging/Prod etc) having separate (preferably identical) Airflow instances for each of these environments would be the best case scenario.
I'm using the GCP managed Airflow ( GCP Cloud Composer), which is not very cheap to run, and having multiple instances would increase our monthly bill significantly.
So, I'd like to know if anyone has recommendations on using a single Airflow instance to handle multiple environments?
One approach I was considering of was to have separate top-level folders within my dags folder corresponding to each of the environment (i.e. dags/dev, dags/prod etc)
and copy my DAG scripts to the relevant folder through the CI/CD pipeline.
So, within my source code repository if my dag looks like:
airflow_dags/my_dag_A.py
During the CI stage, I could have a build step that creates 2 separate versions of this file:
airflow_dags/DEV/my_dag_A.py
airflow_dags/PROD/my_dag_A.py
I would follow a strict naming convention for naming my DAGs, Airflow Variables etc to reflect the environment name, so that the above build step can automatically rename those accordingly.
I wanted check if this is an approach others may have used? Or are there any better/alternative suggestions?
Please let me know if any additional clarifications are needed.
Thank you in advance for your support. Highly appreciated.
| [
"I think it can be a good approach to have a shared environement because it's cost effective.\nHowever if you have a Composer cluster per environment, it's simpler to manage, and it's allows having a better separation.\nIf you stay on a shared environment, I think you are on the good direction with a separation on the Composer bucket DAG and a folder per environment.\nIf you use Airflow variables, you also have to deal with environment in addition to the DAGs part.\nYou can then manage the access to each folder in the bucket.\nIn my team, we chose another approach.\nCloud Composer uses GKE with autopilot mode and it's more cost effective than the previous version.\nIt's also easier to manage the environement size of the cluster and play with differents parameters (workers, cpu, webserver...).\nIn our case, we created a cluster per environment but we have a different configuration per environment (managed by Terraform):\n\nFor dev and uat envs, we have a little sizing and an environment size as small\nFor prod env, we have a higher sizing and an environment size as Medium\n\nIt's not perfect but this allows us to have a compromise between cost and separation.\n"
] | [
0
] | [] | [] | [
"airflow",
"google_cloud_composer"
] | stackoverflow_0074666211_airflow_google_cloud_composer.txt |
Q:
How do I decompose() a reoccurring row in a table that I find located in an html page?
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:
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:
It is possible to create a loop that iterates through each row in an HTML table and delete a row if the first cell in the row matches a certain value. This can be done using a combination of the HTML DOM (Document Object Model) and JavaScript.
First, you will need to use the getElementsByTagName method to retrieve all of the tr elements (table rows) in the table. Then, you can use a for loop to iterate over each of these rows.
Inside the loop, you can use the getElementsByTagName method again to retrieve all of the th elements (table headers) in the current row. If the first th element has a data-stat attribute with a value of "player", then you can use the deleteRow method to delete the current row from the table.
Here is an example of how this might look in code:
// Get all of the table rows in the table
var rows = document.getElementsByTagName("tr");
// Loop through each row
for (var i = 0; i < rows.length; i++) {
// Get all of the table headers in the current row
var headers = rows[i].getElementsByTagName("th");
// If the first header has a data-stat attribute with a value of "player"
if (headers[0].getAttribute("data-stat") == "player") {
// Delete the current row
rows[i].deleteRow();
}
}
Keep in mind that this is just an example and may need to be modified to fit the specific structure of your HTML table.
| How do I decompose() a reoccurring row in a table that I find located in an html page? | 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:
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")
| [
"It is possible to create a loop that iterates through each row in an HTML table and delete a row if the first cell in the row matches a certain value. This can be done using a combination of the HTML DOM (Document Object Model) and JavaScript.\nFirst, you will need to use the getElementsByTagName method to retrieve all of the tr elements (table rows) in the table. Then, you can use a for loop to iterate over each of these rows.\nInside the loop, you can use the getElementsByTagName method again to retrieve all of the th elements (table headers) in the current row. If the first th element has a data-stat attribute with a value of \"player\", then you can use the deleteRow method to delete the current row from the table.\nHere is an example of how this might look in code:\n// Get all of the table rows in the table\nvar rows = document.getElementsByTagName(\"tr\");\n\n// Loop through each row\nfor (var i = 0; i < rows.length; i++) {\n // Get all of the table headers in the current row\n var headers = rows[i].getElementsByTagName(\"th\");\n \n // If the first header has a data-stat attribute with a value of \"player\"\n if (headers[0].getAttribute(\"data-stat\") == \"player\") {\n // Delete the current row\n rows[i].deleteRow();\n }\n}\n\nKeep in mind that this is just an example and may need to be modified to fit the specific structure of your HTML table.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074671640_python.txt |
Q:
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15)
after running this code I keep getting the same error:
note:(the data is in excel file (Heights : 16 column) and (Wights:16 column)
I tried to change the epochs_num and it keeps giving the same problem...
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the dataset
data = pd.read_csv('heights_weights.csv')
# Plot the data distribution
plt.scatter(data['Height'], data['Weight'], color='b')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs. Weight')
plt.show()
# Define the linear regression model
def linearRegression_model(X, weights):
y_pred = np.dot(X, weights)
return y_pred
# Define the update weights function
def linearRegression_update_weights(X, y, weights, learning_rate):
y_pred = linearRegression_model(X, weights)
weights_delta = np.dot(X.T, y_pred - y)
m = len(y)
weights -= (learning_rate/m) * weights_delta
return weights
# Define the train function
def linearRegression_train(X, y, learning_rate, num_epochs):
# Initialize weights and bias
weights = np.zeros(X.shape[1])
for epoch in range(num_epochs):
weights = linearRegression_update_weights(X, y, weights, learning_rate)
if (epoch % 100 == 0):
print('epoch: %s, weights: %s' % (epoch, weights))
return weights
# Define the predict function
def linearRegression_predict(X, weights):
y_pred = linearRegression_model(X, weights)
return y_pred
# Define the mean squared error function
def mean_squared_error(y_true, y_pred):
mse = np.mean(np.power(y_true-y_pred, 2))
return mse
# Prepare the data
X = data['Height'].values.reshape(-1, 1)
y = data['Weight'].values.reshape(-1, 1)
# Train the model
lr = 0.01
n_epochs = 1000
weights = linearRegression_train(X, y, lr, n_epochs)
# Predict
y_pred = linearRegression_predict(X, weights)
# Evaluate the model
mse = mean_squared_error(y, y_pred)
print('Mean Squared Error: %s' % mse)
# Plot the regression line
plt.scatter(data['Height'], data['Weight'], color='b')
plt.plot(X, y_pred, color='k')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs. Weight')
plt.show()
# Plot the predicted and actual values
plt.scatter(data['Height'], y, color='b', label='Actual')
plt.scatter(data['Height'], y_pred, color='r', label='Predicted')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Actual vs. Predicted')
plt.legend()
plt.show()
i try the same code to run step by step in google colab and i also change the epochs to 62 and run it many times but still the same :
ValueError Traceback (most recent call last)
<ipython-input-23-98703406a0a3> in <module>
2 learning_rate = 0.01
3 num_epochs = 62
----> 4 weights = linearRegression_train(X, y, learning_rate, num_epochs)
1 frames
<ipython-input-12-8f66dacdd5fc> in linearRegression_update_weights(X, y, weights, learning_rate)
4 weights_delta = np.dot(X.T, y_pred - y)
5 m = len(y)
----> 6 weights -= (learning_rate/m) * weights_delta
7 return weights
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15)
A:
I can reproduce the error message with
In [5]: x=np.array([1])
In [6]: x+=np.ones((1,5),int)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 x+=np.ones((1,5),int)
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,5)
A:
In linearRegression_update_weights, weights.shape == (1,) but weights_delta.shape == (1, 15) so the in-place subtraction fails. The shape of weights_delta is wrong because y_pred.shape == (15,) but y.shape == (15, 1) so (y_pred - y).shape == (15, 15) because of broadcasting. This results in the wrong shape of weights_delta after multiplied by X.T. The fix is to ensure y is a 1-D array to match the shape of y_pred, preventing broadcasting:
y = data['Weight'].values.reshape(-1)
| ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15) | after running this code I keep getting the same error:
note:(the data is in excel file (Heights : 16 column) and (Wights:16 column)
I tried to change the epochs_num and it keeps giving the same problem...
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the dataset
data = pd.read_csv('heights_weights.csv')
# Plot the data distribution
plt.scatter(data['Height'], data['Weight'], color='b')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs. Weight')
plt.show()
# Define the linear regression model
def linearRegression_model(X, weights):
y_pred = np.dot(X, weights)
return y_pred
# Define the update weights function
def linearRegression_update_weights(X, y, weights, learning_rate):
y_pred = linearRegression_model(X, weights)
weights_delta = np.dot(X.T, y_pred - y)
m = len(y)
weights -= (learning_rate/m) * weights_delta
return weights
# Define the train function
def linearRegression_train(X, y, learning_rate, num_epochs):
# Initialize weights and bias
weights = np.zeros(X.shape[1])
for epoch in range(num_epochs):
weights = linearRegression_update_weights(X, y, weights, learning_rate)
if (epoch % 100 == 0):
print('epoch: %s, weights: %s' % (epoch, weights))
return weights
# Define the predict function
def linearRegression_predict(X, weights):
y_pred = linearRegression_model(X, weights)
return y_pred
# Define the mean squared error function
def mean_squared_error(y_true, y_pred):
mse = np.mean(np.power(y_true-y_pred, 2))
return mse
# Prepare the data
X = data['Height'].values.reshape(-1, 1)
y = data['Weight'].values.reshape(-1, 1)
# Train the model
lr = 0.01
n_epochs = 1000
weights = linearRegression_train(X, y, lr, n_epochs)
# Predict
y_pred = linearRegression_predict(X, weights)
# Evaluate the model
mse = mean_squared_error(y, y_pred)
print('Mean Squared Error: %s' % mse)
# Plot the regression line
plt.scatter(data['Height'], data['Weight'], color='b')
plt.plot(X, y_pred, color='k')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Height vs. Weight')
plt.show()
# Plot the predicted and actual values
plt.scatter(data['Height'], y, color='b', label='Actual')
plt.scatter(data['Height'], y_pred, color='r', label='Predicted')
plt.xlabel('Height')
plt.ylabel('Weight')
plt.title('Actual vs. Predicted')
plt.legend()
plt.show()
i try the same code to run step by step in google colab and i also change the epochs to 62 and run it many times but still the same :
ValueError Traceback (most recent call last)
<ipython-input-23-98703406a0a3> in <module>
2 learning_rate = 0.01
3 num_epochs = 62
----> 4 weights = linearRegression_train(X, y, learning_rate, num_epochs)
1 frames
<ipython-input-12-8f66dacdd5fc> in linearRegression_update_weights(X, y, weights, learning_rate)
4 weights_delta = np.dot(X.T, y_pred - y)
5 m = len(y)
----> 6 weights -= (learning_rate/m) * weights_delta
7 return weights
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15)
| [
"I can reproduce the error message with\nIn [5]: x=np.array([1])\n\nIn [6]: x+=np.ones((1,5),int)\n---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\nInput In [6], in <cell line: 1>()\n----> 1 x+=np.ones((1,5),int)\n\nValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,5)\n\n",
"In linearRegression_update_weights, weights.shape == (1,) but weights_delta.shape == (1, 15) so the in-place subtraction fails. The shape of weights_delta is wrong because y_pred.shape == (15,) but y.shape == (15, 1) so (y_pred - y).shape == (15, 15) because of broadcasting. This results in the wrong shape of weights_delta after multiplied by X.T. The fix is to ensure y is a 1-D array to match the shape of y_pred, preventing broadcasting:\ny = data['Weight'].values.reshape(-1)\n\n"
] | [
0,
0
] | [] | [] | [
"linear_regression",
"numpy",
"pandas",
"python"
] | stackoverflow_0074658165_linear_regression_numpy_pandas_python.txt |
Q:
C# I want to use either a switch or if statement to select a sorting algorithm
I am writing a program that will take user input and run it through whichever sort they choose. Where I am having a problem is if I try to use a switch I cannot figure out how to add arguments to a switch or if I use an if statement how do I implement that with the user's input? here is the code and thank you all for your help.
'''
using System;
namespace ASortAboveTheRest
{
internal class Program
{
static void Main(string[] args)
{
MainMenu();
}
static void MainMenu()
{
Console.Clear();
Console.WriteLine("Choose a sort algorithm to perform on the Array");
Console.WriteLine("");
Console.WriteLine("Option 1: Heap Sort");
Console.WriteLine("Option 2: Bubble Sort");
Console.WriteLine("Option 3: Shell Sort");
Console.WriteLine("Please type: 1, 2, or 3");
string myOption;
myOption = Console.ReadLine();
int[] arr = new int[10];
int i;
Console.Write("Input 10 elements in the array :\n");
for (i = 0; i < 10; i++)
{
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for (i = 0; i < 10; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
'''
A:
Following code should do the trick:
using System;
namespace ASortAboveTheRest {
internal class Program
{
static void Main(string[] args)
{
MainMenu();
}
static void MainMenu()
{
Console.Clear();
Console.WriteLine("Choose a sort algorithm to perform on the Array");
Console.WriteLine("");
Console.WriteLine("Option 1: Heap Sort");
Console.WriteLine("Option 2: Bubble Sort");
Console.WriteLine("Option 3: Shell Sort");
Console.WriteLine("Please type: 1, 2, or 3");
// Take Option input as an INT
int myOption;
myOption = Convert.ToInt32(Console.ReadLine());
int[] arr = new int[10];
int i;
Console.Write("Input 10 elements in the array :\n");
for (i = 0; i < 10; i++)
{
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for (i = 0; i < 10; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
//Use switch case after taking array input from the user
switch(myOption) {
case 1:
//Call Heap Sort Function and pass your array
break;
case 2:
// Call Bubble Sort Function and pass your array
break;
case 3:
//Call Shell Sort Function and pass your array
break;
default:
break;
}
}
}
}
| C# I want to use either a switch or if statement to select a sorting algorithm | I am writing a program that will take user input and run it through whichever sort they choose. Where I am having a problem is if I try to use a switch I cannot figure out how to add arguments to a switch or if I use an if statement how do I implement that with the user's input? here is the code and thank you all for your help.
'''
using System;
namespace ASortAboveTheRest
{
internal class Program
{
static void Main(string[] args)
{
MainMenu();
}
static void MainMenu()
{
Console.Clear();
Console.WriteLine("Choose a sort algorithm to perform on the Array");
Console.WriteLine("");
Console.WriteLine("Option 1: Heap Sort");
Console.WriteLine("Option 2: Bubble Sort");
Console.WriteLine("Option 3: Shell Sort");
Console.WriteLine("Please type: 1, 2, or 3");
string myOption;
myOption = Console.ReadLine();
int[] arr = new int[10];
int i;
Console.Write("Input 10 elements in the array :\n");
for (i = 0; i < 10; i++)
{
Console.Write("element - {0} : ", i);
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\nElements in array are: ");
for (i = 0; i < 10; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.Write("\n");
'''
| [
"Following code should do the trick:\nusing System;\n\nnamespace ASortAboveTheRest { \n internal class Program\n {\n static void Main(string[] args)\n {\n MainMenu();\n }\n\n static void MainMenu()\n {\n\n Console.Clear();\n Console.WriteLine(\"Choose a sort algorithm to perform on the Array\");\n Console.WriteLine(\"\");\n Console.WriteLine(\"Option 1: Heap Sort\");\n Console.WriteLine(\"Option 2: Bubble Sort\");\n Console.WriteLine(\"Option 3: Shell Sort\");\n\n Console.WriteLine(\"Please type: 1, 2, or 3\");\n // Take Option input as an INT\n int myOption;\n myOption = Convert.ToInt32(Console.ReadLine());\n\n int[] arr = new int[10];\n int i;\n Console.Write(\"Input 10 elements in the array :\\n\");\n for (i = 0; i < 10; i++)\n {\n Console.Write(\"element - {0} : \", i);\n arr[i] = Convert.ToInt32(Console.ReadLine());\n }\n\n\n\n Console.Write(\"\\nElements in array are: \");\n for (i = 0; i < 10; i++)\n {\n Console.Write(\"{0} \", arr[i]);\n }\n Console.Write(\"\\n\");\n \n //Use switch case after taking array input from the user\n switch(myOption) {\n case 1:\n //Call Heap Sort Function and pass your array\n break;\n case 2:\n // Call Bubble Sort Function and pass your array\n break;\n case 3:\n //Call Shell Sort Function and pass your array\n break;\n default:\n break;\n }\n }\n }\n}\n\n"
] | [
0
] | [] | [] | [
"c#",
"heapsort",
"shellsort",
"switch_statement"
] | stackoverflow_0074671572_c#_heapsort_shellsort_switch_statement.txt |
Q:
Java 8 - Difference between reduce(0, Integer::sum) and reduce(0, (a, b) -> a+b)
I am new to Java 8 and did find some ways to do addition, multiply and subtraction. I will be posting question for add only.
I have written below code and gathering output in Sum1 and Sum2. Both the methods reduce(0, Integer::sum) and .reduce(0, (a, b) -> a+b); gives the same result. What would be the best method to use performance wise and if using large integer values and why ?
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
Integer sum1 = numbers.stream().reduce(0, (a, b) -> a+b);
System.out.println("SUM ="+sum1);
Integer product = numbers.stream().reduce(0, (a, b) -> a*b);
System.out.println("PRODUCT = "+product);
int sum2 = numbers.stream().reduce(0, Integer::sum);
System.out.println("SUM 2= "+sum2);
Optional<Integer> sum3 = numbers.stream().reduce((a, b) -> (a + b));
System.out.println("SUM3="+sum3);
// Updated as per @Hadi J comment
int sum4 = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum ="+sum4);
A:
What would be the best method to use performance wise and if using large integer values and why ?
The main idea is to ignore auto-boxing/unboxing when juggling with primitives and their object representations.
Adding two Integer objects is much more sophisticated than adding two int primitives. You can find more details in this post.
So the best case is when you have a primitive array int[] and sum its elements into an accumulator of type int. Thus no boxing involved here.
A worse (but not the worst) case is when you sum an object Integer with a primitive int. It will cause unboxing of the first argument.
This is how it works when your initial array or collection contains objects (e.g. Integer[], List, etc...) and the accumulator is primitive. This will cause unboxing of each element of your collection exactly once, while the accumulator will remain the same.
The worst case is summing up a collection of objects into an Integer accumulator.
Plain old Java:
Summing Integer[] into Integer
Integer[] array = {0,1,2,3,4,5,6,7,8,9};
Integer sum = 0;
// Each element of the array will be unboxed exactly once
// sum will be unboxed 10 times
// result of the sum will be boxed 10 times
for(int i : array) sum += i;
Summing Integer[] into int
Integer[] array = {0,1,2,3,4,5,6,7,8,9};
int sum = 0;
// Each element of the array will be unboxed exactly once
// result of the sum will be boxed 10 times
for(int i : array) sum += i;
Summing int[] into int
int[] array = {0,1,2,3,4,5,6,7,8,9};
int sum = 0;
// No boxing/unboxing at all
for(int i : array) sum += i;
Stream API
Reducing sum of Stream<Integer>
Stream<Integer> stream = Stream.of(0,1,2,3,4,5,6,7,8,9);
// Each element will be unboxed exactly once
// The accumulator will be unboxed 10 times
// The result of the sum operation will be boxed 10 times
Integer sum = stream.reduce(0, Integer::sum);
Reducing sum of Stream<Integer> mapping to primitive int
Stream<Integer> stream = Stream.of(0,1,2,3,4,5,6,7,8,9);
// Each element will be unboxed exactly once
// Neither accumulator not result will be unboxed/boxed
int sum = stream.mapToInt(Integer::intValue).reduce(0, Integer::sum);
Reducing sum of IntStream
IntStream stream = IntStream.of(0,1,2,3,4,5,6,7,8,9);
// No boxing/unboxing at all
int sum = stream.reduce(0, Integer::sum);
// same as
int sum2 = stream.sum();
A:
Something interesting:
In Intellij IDEA, when you pass the mouse over the sum() function, there is a ToolTip like this one:
Returns the sum of the elements in this stream. This is a special case of a reduction and is equivalent to:
Public abstract int sum()
//equal function to
return reduce(0, Integer::sum);
| Java 8 - Difference between reduce(0, Integer::sum) and reduce(0, (a, b) -> a+b) | I am new to Java 8 and did find some ways to do addition, multiply and subtraction. I will be posting question for add only.
I have written below code and gathering output in Sum1 and Sum2. Both the methods reduce(0, Integer::sum) and .reduce(0, (a, b) -> a+b); gives the same result. What would be the best method to use performance wise and if using large integer values and why ?
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
Integer sum1 = numbers.stream().reduce(0, (a, b) -> a+b);
System.out.println("SUM ="+sum1);
Integer product = numbers.stream().reduce(0, (a, b) -> a*b);
System.out.println("PRODUCT = "+product);
int sum2 = numbers.stream().reduce(0, Integer::sum);
System.out.println("SUM 2= "+sum2);
Optional<Integer> sum3 = numbers.stream().reduce((a, b) -> (a + b));
System.out.println("SUM3="+sum3);
// Updated as per @Hadi J comment
int sum4 = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum ="+sum4);
| [
"\nWhat would be the best method to use performance wise and if using large integer values and why ?\n\nThe main idea is to ignore auto-boxing/unboxing when juggling with primitives and their object representations. \nAdding two Integer objects is much more sophisticated than adding two int primitives. You can find more details in this post.\nSo the best case is when you have a primitive array int[] and sum its elements into an accumulator of type int. Thus no boxing involved here.\nA worse (but not the worst) case is when you sum an object Integer with a primitive int. It will cause unboxing of the first argument. \nThis is how it works when your initial array or collection contains objects (e.g. Integer[], List, etc...) and the accumulator is primitive. This will cause unboxing of each element of your collection exactly once, while the accumulator will remain the same.\nThe worst case is summing up a collection of objects into an Integer accumulator.\n\nPlain old Java:\n\nSumming Integer[] into Integer\nInteger[] array = {0,1,2,3,4,5,6,7,8,9};\nInteger sum = 0;\n// Each element of the array will be unboxed exactly once\n// sum will be unboxed 10 times\n// result of the sum will be boxed 10 times\nfor(int i : array) sum += i;\n\nSumming Integer[] into int\nInteger[] array = {0,1,2,3,4,5,6,7,8,9};\nint sum = 0;\n// Each element of the array will be unboxed exactly once\n// result of the sum will be boxed 10 times\nfor(int i : array) sum += i;\n\nSumming int[] into int\nint[] array = {0,1,2,3,4,5,6,7,8,9};\nint sum = 0;\n// No boxing/unboxing at all\nfor(int i : array) sum += i;\n\n\nStream API\n\nReducing sum of Stream<Integer>\nStream<Integer> stream = Stream.of(0,1,2,3,4,5,6,7,8,9);\n// Each element will be unboxed exactly once\n// The accumulator will be unboxed 10 times\n// The result of the sum operation will be boxed 10 times\nInteger sum = stream.reduce(0, Integer::sum);\n\nReducing sum of Stream<Integer> mapping to primitive int\nStream<Integer> stream = Stream.of(0,1,2,3,4,5,6,7,8,9);\n// Each element will be unboxed exactly once\n// Neither accumulator not result will be unboxed/boxed\nint sum = stream.mapToInt(Integer::intValue).reduce(0, Integer::sum);\n\nReducing sum of IntStream\nIntStream stream = IntStream.of(0,1,2,3,4,5,6,7,8,9);\n// No boxing/unboxing at all\nint sum = stream.reduce(0, Integer::sum);\n// same as\nint sum2 = stream.sum();\n\n\n\n",
"Something interesting:\nIn Intellij IDEA, when you pass the mouse over the sum() function, there is a ToolTip like this one:\n\nReturns the sum of the elements in this stream. This is a special case of a reduction and is equivalent to:\nPublic abstract int sum() \n//equal function to\nreturn reduce(0, Integer::sum);\n\n"
] | [
5,
0
] | [] | [] | [
"collections",
"java",
"java_8",
"java_stream",
"reduce"
] | stackoverflow_0052716180_collections_java_java_8_java_stream_reduce.txt |
Q:
I'm wondering why I'm getting a TypeError: argument of type 'int' is not iterable
I'm trying to make a list of names based off the last number in the values list. The new list will be ordered based on highest number to lowest number but is a list of the names.
folks = {'Leia': [28, 'F', 'W', False, True, 'Unemployed',1],
'Junipero': [15, 'M', 'E', False, False, 'Teacher', 0.21158336054026594],
'Sunita': [110, 'D', 'E', True, False, 'Business', 0.9834949767416051],
'Issur': [17, 'F', 'O', True, False, 'Service', 0.7599396397686616],
'Luitgard': [0, 'D', 'U', True, True, 'Unemployed', 0.8874638219100845],
'Rudy': [112, 'M', 'W', True, True, 'Tradesperson', 0.6035917636433216],
'Ioudith': [20, 'D', 'W', True, True, 'Medical', 0.24957574519928294],
'Helmi': [109, 'D', 'M', False, False, 'Service', 0.20239906854483214],
'Katerina': [108, 'M', 'W', False, True, 'Student', 0.3046268530221382],
'Durai': [106, 'M', 'U', True, False, 'Business', 0.32332997497778493],
'Euphemios': [83, 'M', 'L', True, True, 'Banker', 0.17369577419188664],
'Lorinda': [8, 'F', 'E', False, True, 'Retail', 0.6667783756618852],
'Lasse': [30, 'D', 'U', True, True, 'Business', 0.6716420300452077],
'Adnan': [117, 'D', 'U', True, False, 'Banker', 0.7043759366238305],
'Pavica': [112, 'F', 'L', False, False, 'Business', 0.5875152728319836],
'Adrastos': [118, 'F', 'L', False, True, 'Service', 0.0660146284846359],
'Kobus': [49, 'D', 'S', False, False, 'Service', 0.4738056051140088],
'Daniel': [115, 'D', 'L', False, True, 'Service', 0.5182765931408372],
'Samantha': [97, 'D', 'W', True, True, 'Medical', 0.07082409148069169],
'Sacagawea': [28, 'F', 'U', True, True, 'Medical', 0.29790328657890996],
'Ixchel': [26, 'F', 'S', False, False, 'Business', 0.22593704520870372],
'Nobutoshi': [31, 'M', 'W', False, True, 'Business', 0.37923896100469956],
'Gorou': [55, 'M', 'B', True, True, 'Banker', 0.8684653864827863],
'Keiko': [34, 'M', 'L', False, True, 'Student', 0.02499269016601946],
'Seong-Su': [1, 'M', 'M', False, True, 'Retail', 0.3214997836868769],
'Aya': [41, 'M', 'B', True, True, 'Teacher', 0.3378161065313626],
'Okan': [11, 'D', 'W', True, True, 'Banker', 0.35535128959244744],
'Mai': [31, 'F', 'M', False, False, 'Service', 0.7072299366468716],
'Chaza-el': [84, 'D', 'E', True, True, 'Teacher', 0.263795143996962],
'Estera': [79, 'M', 'U', True, False, 'Tradesperson', 0.09970175216521693],
'Dante': [82, 'M', 'L', True, False, 'Unemployed', 0.2126494288577333],
'Leofric': [68, 'F', 'B', True, False, 'Unemployed', 0.19591887643941486],
'Anabelle': [63, 'M', 'B', False, False, 'Teacher', 0.3558324357405023],
'Harsha': [119, 'D', 'O', False, True, 'Retail', 0.3359989642837887],
'Dionisia': [92, 'F', 'B', True, False, 'Doctor', 0.42704604164789706],
'Rajesh': [55, 'F', 'M', True, False, 'Doctor', 0.485752225148387],
'Scilla': [60, 'F', 'M', False, False, 'Student', 0.7294089528796434],
'Arsenio': [10, 'D', 'L', False, True, 'Teacher', 0.0819890866210915]}
def generate_prioritized_list(unordered_people):
nums=[]
for i in folks:
nums.append(folks[i][6])
nums.sort(reverse=True)
for i in nums:
names=[]
for name in folks:
if i in folks[name][6]:
names.append(folks[i])
for i in names:
print(i)
print(generate_prioritized_list(folks))
I'm trying to get a list of the names ordered highest to lowest by the last value in the list each persons attributes.
A:
I would use the key argument to the sorted function
sorted(folks, key=lambda x: folks[x][-1])[::-1]
sorted pulls the keys out of the dictionary
key=lambda x: folks[x][-1] determines how to sort those keys
[::-1] reverses the list.
I get:
['Leia',
'Sunita',
'Luitgard',
'Gorou',
'Issur',
# ...
'Estera',
'Arsenio',
'Samantha',
'Adrastos',
'Keiko']
A:
Here is one way to do it:
# Get the values of the last item in each sublist
last_values = [folks[name][-1] for name in folks]
# Sort the values in descending order
sorted_values = sorted(last_values, reverse=True)
# Create a list of names, sorted by the last value in their sublist
sorted_names = [name for value in sorted_values
for name in folks
if folks[name][-1] == value]
# Print the resulting list
print(sorted_names)
This code uses two nested list comprehensions to create the sorted list of names. The first list comprehension gets the values of the last item in each sublist, and the second list comprehension uses those values to create the sorted list of names.
| I'm wondering why I'm getting a TypeError: argument of type 'int' is not iterable | I'm trying to make a list of names based off the last number in the values list. The new list will be ordered based on highest number to lowest number but is a list of the names.
folks = {'Leia': [28, 'F', 'W', False, True, 'Unemployed',1],
'Junipero': [15, 'M', 'E', False, False, 'Teacher', 0.21158336054026594],
'Sunita': [110, 'D', 'E', True, False, 'Business', 0.9834949767416051],
'Issur': [17, 'F', 'O', True, False, 'Service', 0.7599396397686616],
'Luitgard': [0, 'D', 'U', True, True, 'Unemployed', 0.8874638219100845],
'Rudy': [112, 'M', 'W', True, True, 'Tradesperson', 0.6035917636433216],
'Ioudith': [20, 'D', 'W', True, True, 'Medical', 0.24957574519928294],
'Helmi': [109, 'D', 'M', False, False, 'Service', 0.20239906854483214],
'Katerina': [108, 'M', 'W', False, True, 'Student', 0.3046268530221382],
'Durai': [106, 'M', 'U', True, False, 'Business', 0.32332997497778493],
'Euphemios': [83, 'M', 'L', True, True, 'Banker', 0.17369577419188664],
'Lorinda': [8, 'F', 'E', False, True, 'Retail', 0.6667783756618852],
'Lasse': [30, 'D', 'U', True, True, 'Business', 0.6716420300452077],
'Adnan': [117, 'D', 'U', True, False, 'Banker', 0.7043759366238305],
'Pavica': [112, 'F', 'L', False, False, 'Business', 0.5875152728319836],
'Adrastos': [118, 'F', 'L', False, True, 'Service', 0.0660146284846359],
'Kobus': [49, 'D', 'S', False, False, 'Service', 0.4738056051140088],
'Daniel': [115, 'D', 'L', False, True, 'Service', 0.5182765931408372],
'Samantha': [97, 'D', 'W', True, True, 'Medical', 0.07082409148069169],
'Sacagawea': [28, 'F', 'U', True, True, 'Medical', 0.29790328657890996],
'Ixchel': [26, 'F', 'S', False, False, 'Business', 0.22593704520870372],
'Nobutoshi': [31, 'M', 'W', False, True, 'Business', 0.37923896100469956],
'Gorou': [55, 'M', 'B', True, True, 'Banker', 0.8684653864827863],
'Keiko': [34, 'M', 'L', False, True, 'Student', 0.02499269016601946],
'Seong-Su': [1, 'M', 'M', False, True, 'Retail', 0.3214997836868769],
'Aya': [41, 'M', 'B', True, True, 'Teacher', 0.3378161065313626],
'Okan': [11, 'D', 'W', True, True, 'Banker', 0.35535128959244744],
'Mai': [31, 'F', 'M', False, False, 'Service', 0.7072299366468716],
'Chaza-el': [84, 'D', 'E', True, True, 'Teacher', 0.263795143996962],
'Estera': [79, 'M', 'U', True, False, 'Tradesperson', 0.09970175216521693],
'Dante': [82, 'M', 'L', True, False, 'Unemployed', 0.2126494288577333],
'Leofric': [68, 'F', 'B', True, False, 'Unemployed', 0.19591887643941486],
'Anabelle': [63, 'M', 'B', False, False, 'Teacher', 0.3558324357405023],
'Harsha': [119, 'D', 'O', False, True, 'Retail', 0.3359989642837887],
'Dionisia': [92, 'F', 'B', True, False, 'Doctor', 0.42704604164789706],
'Rajesh': [55, 'F', 'M', True, False, 'Doctor', 0.485752225148387],
'Scilla': [60, 'F', 'M', False, False, 'Student', 0.7294089528796434],
'Arsenio': [10, 'D', 'L', False, True, 'Teacher', 0.0819890866210915]}
def generate_prioritized_list(unordered_people):
nums=[]
for i in folks:
nums.append(folks[i][6])
nums.sort(reverse=True)
for i in nums:
names=[]
for name in folks:
if i in folks[name][6]:
names.append(folks[i])
for i in names:
print(i)
print(generate_prioritized_list(folks))
I'm trying to get a list of the names ordered highest to lowest by the last value in the list each persons attributes.
| [
"I would use the key argument to the sorted function\nsorted(folks, key=lambda x: folks[x][-1])[::-1]\n\n\nsorted pulls the keys out of the dictionary\nkey=lambda x: folks[x][-1] determines how to sort those keys\n[::-1] reverses the list.\n\nI get:\n['Leia',\n 'Sunita',\n 'Luitgard',\n 'Gorou',\n 'Issur',\n # ... \n 'Estera',\n 'Arsenio',\n 'Samantha',\n 'Adrastos',\n 'Keiko']\n\n",
"Here is one way to do it:\n# Get the values of the last item in each sublist\nlast_values = [folks[name][-1] for name in folks]\n\n# Sort the values in descending order\nsorted_values = sorted(last_values, reverse=True)\n\n# Create a list of names, sorted by the last value in their sublist\nsorted_names = [name for value in sorted_values\n for name in folks\n if folks[name][-1] == value]\n\n# Print the resulting list\nprint(sorted_names)\n\nThis code uses two nested list comprehensions to create the sorted list of names. The first list comprehension gets the values of the last item in each sublist, and the second list comprehension uses those values to create the sorted list of names.\n"
] | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"typeerror"
] | stackoverflow_0074671633_dictionary_list_python_typeerror.txt |
Q:
Xcode 14.1 editor extremely slow
We are using dictionaries to hold parameters for network requests on our app.
For example:
var params: [String: Any] = [:]
params["pageSize"] = 20
params["pageIndex"] = 0
We weren't experiencing any issues on Xcode 13, but after updating to Xcode 14 this approach seems to slow down editor extremely. So much so that even deleting a single line takes multiple seconds. Since we cannot change every single network request in our app and continue using Xcode 13 forever, is there a way to fix this issue?
Tried to edit a single line of code in a file that includes lots of dictionaries using Xcode 14, took several seconds instead of being instant.
A:
One way to try to fix this issue would be to switch to using structs to store the parameters rather than dictionaries. Structs can be more efficient at runtime and may be better-suited to the task at hand. Another approach would be to try using a Swift compiler optimization flag, such as -O-whole-module-optimization, when compiling the code. This may provide better performance at the cost of a longer compilation time. Finally, you could try profiling the code to identify any potential bottlenecks that could be causing the slowdowns.
Here is an example of how one could use structs to store parameters for network requests:
struct NetworkParams {
let pageSize: Int
let pageIndex: Int
}
let params = NetworkParams(pageSize: 20, pageIndex: 0)
| Xcode 14.1 editor extremely slow | We are using dictionaries to hold parameters for network requests on our app.
For example:
var params: [String: Any] = [:]
params["pageSize"] = 20
params["pageIndex"] = 0
We weren't experiencing any issues on Xcode 13, but after updating to Xcode 14 this approach seems to slow down editor extremely. So much so that even deleting a single line takes multiple seconds. Since we cannot change every single network request in our app and continue using Xcode 13 forever, is there a way to fix this issue?
Tried to edit a single line of code in a file that includes lots of dictionaries using Xcode 14, took several seconds instead of being instant.
| [
"One way to try to fix this issue would be to switch to using structs to store the parameters rather than dictionaries. Structs can be more efficient at runtime and may be better-suited to the task at hand. Another approach would be to try using a Swift compiler optimization flag, such as -O-whole-module-optimization, when compiling the code. This may provide better performance at the cost of a longer compilation time. Finally, you could try profiling the code to identify any potential bottlenecks that could be causing the slowdowns.\nHere is an example of how one could use structs to store parameters for network requests:\nstruct NetworkParams {\nlet pageSize: Int\nlet pageIndex: Int\n\n}\nlet params = NetworkParams(pageSize: 20, pageIndex: 0)\n"
] | [
0
] | [] | [] | [
"editor",
"ios",
"swift",
"xcode",
"xcode14"
] | stackoverflow_0074654854_editor_ios_swift_xcode_xcode14.txt |
Q:
My WCHAR* variable prints unicode chars in my C project
I made a small linked map for my C project.
And I'm using this map for cache my checks,
I'm putting current file path to map. If the same file path request again, it has to get value from the cache map.
struct StrBoolNode {
const WCHAR* key;
BOOL* value;
struct StrBoolNode* next;
};
struct StrBoolTable {
struct StrBoolNode* first;
};
BOOL* strBoolTable_get(struct StrBoolTable* table, const WCHAR* key) {
wprintf(L"TEST strBoolTable_get %s \n", key);
struct StrBoolNode* node = table->first;
while (node != NULL) {
wprintf(L"strBoolTable_get WHILE %s \n", node->key); <<< prints here broken
if (wcscmp(key, node->key) == 0) return node->value;
node = node->next;
}
return NULL;
}
void strBoolTable_push(struct StrBoolTable* table, const WCHAR* key, BOOL value) {
wprintf(L"TEST strBoolTable_push 1 %s \n", key); <<< prints here normal
struct StrBoolNode* tmp = (StrBoolNode*)malloc(sizeof(struct StrBoolNode));
tmp->key = cloneKey;
tmp->value = (BOOL*)malloc(sizeof(BOOL));
*(tmp->value) = value;
tmp->next = NULL;
wprintf(L"TEST strBoolTable_push 2 %s \n", tmp->key); <<< prints here normal
if (table->first == NULL) {
table->first = tmp;
wprintf(L"TEST strBoolTable_push 3 %s \n", table->first->key); <<< prints here normal
return;
}
struct StrBoolNode* node = table->first;
while (node->next != NULL) {
node = node->next;
}
node->next = tmp;
wprintf(L"TEST strBoolTable_push 4 %s \n", node->next->key); <<< prints here normal
}
struct StrBoolTable cacheMap = { NULL };
WCHAR szFileName[MAX_PATH];
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)retAddr,
&hModule);
GetModuleFileNameW(hModule, szFileName, 2048);
BOOL* cacheVal = strBoolTable_get(&cacheMap, szFileName);
if (cacheVal != NULL) return *cacheVal;
wprintf(L"Check => %s \n", szFileName); <<<< szFileName prints normal
strBoolTable_push(&cacheMap, szFileName, TRUE);
return TRUE;
There is no problem when pushing object to this map, but when I iterate and print the key in object, it returns unicode chars. Like this "Γ,β₯".
Why does my object's key change to this later?
I marked where printed wrong print with <<<< in the code.
A:
What is cloneKey that I see referenced in strBoolTable_push. It's note declared anywhere. How does that code compile?
My psychic powers suggest you are pushing a local array variable:
WCHAR szFileName[MAX_PATH];
Into your collection. But as soon as the function declaring szFileName returns, all bets are off (undefined behavior). The memory space is easily reclaimed and overwritten by anything that happens after the function returns. Your key is getting corrupted in the linked list when this happens.
Make sure you duplicate the string key before persisting it into your collection:
void strBoolTable_push(struct StrBoolTable* table, const WCHAR* key, BOOL value) {
wprintf(L"TEST strBoolTable_push 1 %s \n", key); <<< prints here normal
struct StrBoolNode* tmp = (StrBoolNode*)malloc(sizeof(struct StrBoolNode));
// wcsdup is equivalent to saying: tmp->key = malloc((wcslen(key)+1)*sizeof(WCHAR))); wcscpy(tmp->key, key);
tmp->key = _wcsdup(key);
Likewise, when you take a node out of list, make sure you free both the key and value members of each node.
| My WCHAR* variable prints unicode chars in my C project | I made a small linked map for my C project.
And I'm using this map for cache my checks,
I'm putting current file path to map. If the same file path request again, it has to get value from the cache map.
struct StrBoolNode {
const WCHAR* key;
BOOL* value;
struct StrBoolNode* next;
};
struct StrBoolTable {
struct StrBoolNode* first;
};
BOOL* strBoolTable_get(struct StrBoolTable* table, const WCHAR* key) {
wprintf(L"TEST strBoolTable_get %s \n", key);
struct StrBoolNode* node = table->first;
while (node != NULL) {
wprintf(L"strBoolTable_get WHILE %s \n", node->key); <<< prints here broken
if (wcscmp(key, node->key) == 0) return node->value;
node = node->next;
}
return NULL;
}
void strBoolTable_push(struct StrBoolTable* table, const WCHAR* key, BOOL value) {
wprintf(L"TEST strBoolTable_push 1 %s \n", key); <<< prints here normal
struct StrBoolNode* tmp = (StrBoolNode*)malloc(sizeof(struct StrBoolNode));
tmp->key = cloneKey;
tmp->value = (BOOL*)malloc(sizeof(BOOL));
*(tmp->value) = value;
tmp->next = NULL;
wprintf(L"TEST strBoolTable_push 2 %s \n", tmp->key); <<< prints here normal
if (table->first == NULL) {
table->first = tmp;
wprintf(L"TEST strBoolTable_push 3 %s \n", table->first->key); <<< prints here normal
return;
}
struct StrBoolNode* node = table->first;
while (node->next != NULL) {
node = node->next;
}
node->next = tmp;
wprintf(L"TEST strBoolTable_push 4 %s \n", node->next->key); <<< prints here normal
}
struct StrBoolTable cacheMap = { NULL };
WCHAR szFileName[MAX_PATH];
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)retAddr,
&hModule);
GetModuleFileNameW(hModule, szFileName, 2048);
BOOL* cacheVal = strBoolTable_get(&cacheMap, szFileName);
if (cacheVal != NULL) return *cacheVal;
wprintf(L"Check => %s \n", szFileName); <<<< szFileName prints normal
strBoolTable_push(&cacheMap, szFileName, TRUE);
return TRUE;
There is no problem when pushing object to this map, but when I iterate and print the key in object, it returns unicode chars. Like this "Γ,β₯".
Why does my object's key change to this later?
I marked where printed wrong print with <<<< in the code.
| [
"What is cloneKey that I see referenced in strBoolTable_push. It's note declared anywhere. How does that code compile?\nMy psychic powers suggest you are pushing a local array variable:\nWCHAR szFileName[MAX_PATH];\n\nInto your collection. But as soon as the function declaring szFileName returns, all bets are off (undefined behavior). The memory space is easily reclaimed and overwritten by anything that happens after the function returns. Your key is getting corrupted in the linked list when this happens.\nMake sure you duplicate the string key before persisting it into your collection:\nvoid strBoolTable_push(struct StrBoolTable* table, const WCHAR* key, BOOL value) {\n\n\n wprintf(L\"TEST strBoolTable_push 1 %s \\n\", key); <<< prints here normal\n\n struct StrBoolNode* tmp = (StrBoolNode*)malloc(sizeof(struct StrBoolNode));\n\n // wcsdup is equivalent to saying: tmp->key = malloc((wcslen(key)+1)*sizeof(WCHAR))); wcscpy(tmp->key, key);\n\n tmp->key = _wcsdup(key); \n\nLikewise, when you take a node out of list, make sure you free both the key and value members of each node.\n"
] | [
1
] | [] | [] | [
"c",
"wchar"
] | stackoverflow_0074671552_c_wchar.txt |
Q:
Run a airflow dag on 2nd and 5th working day every month
I want to run a DAG on 2nd and 5th working day of every month.
eg1: Suppose, 1st Day of the month falls on Friday. In that case the 2nd working day of the month falls on 4th of that Month(i.e. on Monday) and 5th working Day falls on 7th of that month.
eg2: Suppose 1st Day of Month falls on Wednesday. In that case, the 2nd working Day will fall on 2nd Day of that Month, but the 5th Working Day will fall on 7th of that month (i.e. on Tuesday)
eg3: suppose 1st Day of Month falls on Sunday. In that case, the 2nd working day will fall on 3rd of that month and the 5th working day will fall on 6th of that month (i.e. on Friday)
So, how to schedule the DAG in Airflow for such scenarios.
#aiflow #DAG #schedule
I am looking for scheduling logic or code
A:
Could you provide a code of your DAG?
It depends what operators are you using/willing to use.
Also, you might keep in mind bank holidays. Be sure that it is okay to run your airflow job on the 2nd day even if it is bank holiday?
You can schedule your dag daily and use python operator to validate if current date fits your restirctions. I would push this value to XCOM and then read and process this value in your DAG definition.
Another option would be to use bash operator in the beggining of flow and fail it in case current date violates your logic. This will not execute the rest of depented tasks.
Airflow uses cron definition of scheduling times so you must define your logic inside the code as cron can only run tasks on defined schedule and cannot do any calculations.
A:
You can use custom timetables: https://airflow.apache.org/docs/apache-airflow/stable/howto/timetable.html
A:
For a similar use case we implemented a branching operator with a logic to run the selected tasks when it is a specific workday of the month (I think we were using the workday package to identify specific holidays) and then this dag run daily. But the DAG had to complete some other tasks in all cases.
| Run a airflow dag on 2nd and 5th working day every month | I want to run a DAG on 2nd and 5th working day of every month.
eg1: Suppose, 1st Day of the month falls on Friday. In that case the 2nd working day of the month falls on 4th of that Month(i.e. on Monday) and 5th working Day falls on 7th of that month.
eg2: Suppose 1st Day of Month falls on Wednesday. In that case, the 2nd working Day will fall on 2nd Day of that Month, but the 5th Working Day will fall on 7th of that month (i.e. on Tuesday)
eg3: suppose 1st Day of Month falls on Sunday. In that case, the 2nd working day will fall on 3rd of that month and the 5th working day will fall on 6th of that month (i.e. on Friday)
So, how to schedule the DAG in Airflow for such scenarios.
#aiflow #DAG #schedule
I am looking for scheduling logic or code
| [
"Could you provide a code of your DAG?\nIt depends what operators are you using/willing to use.\nAlso, you might keep in mind bank holidays. Be sure that it is okay to run your airflow job on the 2nd day even if it is bank holiday?\nYou can schedule your dag daily and use python operator to validate if current date fits your restirctions. I would push this value to XCOM and then read and process this value in your DAG definition.\nAnother option would be to use bash operator in the beggining of flow and fail it in case current date violates your logic. This will not execute the rest of depented tasks.\nAirflow uses cron definition of scheduling times so you must define your logic inside the code as cron can only run tasks on defined schedule and cannot do any calculations.\n",
"You can use custom timetables: https://airflow.apache.org/docs/apache-airflow/stable/howto/timetable.html\n",
"For a similar use case we implemented a branching operator with a logic to run the selected tasks when it is a specific workday of the month (I think we were using the workday package to identify specific holidays) and then this dag run daily. But the DAG had to complete some other tasks in all cases.\n"
] | [
0,
0,
0
] | [] | [] | [
"airflow",
"scheduled_tasks"
] | stackoverflow_0074626761_airflow_scheduled_tasks.txt |
Q:
How can I take input of a select class and print is somewhere?
I have a dropdown menu as a select class and I want to print the selection that I choose from the dropdown, what should I do ?
<div>
<select class = "selection">
<option value=""> selection1 </option>
<option value=""> selection1 </option>
<option value=""> selection1 </option>
<option value=""> selection1 </option>
</select>
<div>
Print in vue:
{{ session.user.selection }}
I have multiple user picking different selections
A:
To print the selected option from the dropdown menu in Vue.js, you can bind the value of the select element to a property in your Vue instance and use the v-model directive to control the selection. For example:
<div id="app">
<select v-model="selectedOption" class="selection">
<option value=""> selection1 </option>
<option value=""> selection2 </option>
<option value=""> selection3 </option>
<option value=""> selection4 </option>
</select>
<div>
Selected option: {{ selectedOption }}
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
selectedOption: ''
}
})
</script>
In this example, the selectedOption property in the Vue instance is bound to the select element using the v-model directive. When a user selects an option from the dropdown menu, the selectedOption property will be updated with the value of the selected option. You can then use the {{ selectedOption }} syntax to print the selected option in the HTML.
| How can I take input of a select class and print is somewhere? | I have a dropdown menu as a select class and I want to print the selection that I choose from the dropdown, what should I do ?
<div>
<select class = "selection">
<option value=""> selection1 </option>
<option value=""> selection1 </option>
<option value=""> selection1 </option>
<option value=""> selection1 </option>
</select>
<div>
Print in vue:
{{ session.user.selection }}
I have multiple user picking different selections
| [
"To print the selected option from the dropdown menu in Vue.js, you can bind the value of the select element to a property in your Vue instance and use the v-model directive to control the selection. For example:\n<div id=\"app\">\n <select v-model=\"selectedOption\" class=\"selection\">\n <option value=\"\"> selection1 </option>\n <option value=\"\"> selection2 </option>\n <option value=\"\"> selection3 </option>\n <option value=\"\"> selection4 </option>\n </select>\n <div>\n Selected option: {{ selectedOption }}\n </div>\n</div>\n\n<script>\nnew Vue({\n el: '#app',\n data: {\n selectedOption: ''\n }\n})\n</script>\n\nIn this example, the selectedOption property in the Vue instance is bound to the select element using the v-model directive. When a user selects an option from the dropdown menu, the selectedOption property will be updated with the value of the selected option. You can then use the {{ selectedOption }} syntax to print the selected option in the HTML.\n"
] | [
0
] | [] | [] | [
"css",
"html",
"javascript",
"vue.js"
] | stackoverflow_0074671547_css_html_javascript_vue.js.txt |
Q:
What is wrong with my code? I am a newbie and I don't know why it isn't working. (Python)
Sorry, I've only been using python for about an hour, I'm using PyCharm if that has to do with the problem, I don't think it does though.
Here is my code:
userAge = input("Hi, how old are you?\n")
longRussiaString = (
"When will you guys stop telling me about how you had to walk uphill both ways for 10 miles to"
"get to school amidst the icy tundra of Russia? We get it!")
def reply_detect():
if userAge != 0 - 5:
pass
else:
print("Wait a minute... Stop lying! I know your brain is too small for this!")
if userAge != 6 - 18:
pass
else:
print("You're too young to be interested in this. Unless your dad forced you to just like me :(")
if userAge != 19 - 24:
pass
else:
print("""Good luck dealing with those "taxes" things or whatever. Wait, you haven't heard of those?""")
if userAge != 25 - 40:
pass
else:
print("You post-millennial scumbags... No, just kidding, you guys are the ones carrying our society.")
if userAge != 41 - 55:
pass
else:
print(longRussiaString)
def age_reply():
print(f"So, you're {userAge} years old, huh?")
reply_detect()
age_reply()
I tried to inverse the if loops making a second function to neaten things up a bit, and lots of other things, what happens is that it shows the "So, you're {userAge} years old part, but it ends there and doesn't show me the rest, which is the function "reply_detect".
Thanks!
A:
It seems you're looking to see if a number occurs in a range. This can be accomplished very directly in Python. Just remember that the end of the range is exclusive: 0 to 5 is covered by range(0, 6).
>>> n = 16
>>> n in range(0, 17)
True
>>> n in range(0, 6)
False
>>> n not in range(0, 6)
True
>>>
A:
you are using a test of 0 - 5 but to python this means zero minus five which is negative five, just as you would do in a calculator. Instead you mean if userAge >= 0 and userAge <= 5 and so on for the remaining tests.
| What is wrong with my code? I am a newbie and I don't know why it isn't working. (Python) | Sorry, I've only been using python for about an hour, I'm using PyCharm if that has to do with the problem, I don't think it does though.
Here is my code:
userAge = input("Hi, how old are you?\n")
longRussiaString = (
"When will you guys stop telling me about how you had to walk uphill both ways for 10 miles to"
"get to school amidst the icy tundra of Russia? We get it!")
def reply_detect():
if userAge != 0 - 5:
pass
else:
print("Wait a minute... Stop lying! I know your brain is too small for this!")
if userAge != 6 - 18:
pass
else:
print("You're too young to be interested in this. Unless your dad forced you to just like me :(")
if userAge != 19 - 24:
pass
else:
print("""Good luck dealing with those "taxes" things or whatever. Wait, you haven't heard of those?""")
if userAge != 25 - 40:
pass
else:
print("You post-millennial scumbags... No, just kidding, you guys are the ones carrying our society.")
if userAge != 41 - 55:
pass
else:
print(longRussiaString)
def age_reply():
print(f"So, you're {userAge} years old, huh?")
reply_detect()
age_reply()
I tried to inverse the if loops making a second function to neaten things up a bit, and lots of other things, what happens is that it shows the "So, you're {userAge} years old part, but it ends there and doesn't show me the rest, which is the function "reply_detect".
Thanks!
| [
"It seems you're looking to see if a number occurs in a range. This can be accomplished very directly in Python. Just remember that the end of the range is exclusive: 0 to 5 is covered by range(0, 6).\n>>> n = 16\n>>> n in range(0, 17)\nTrue\n>>> n in range(0, 6)\nFalse\n>>> n not in range(0, 6)\nTrue\n>>>\n\n",
"you are using a test of 0 - 5 but to python this means zero minus five which is negative five, just as you would do in a calculator. Instead you mean if userAge >= 0 and userAge <= 5 and so on for the remaining tests.\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074671685_python.txt |
Q:
Cannot create table in MYSQL with UNICODE and INTEGER types, ERROR: 1064
I am trying to create a simple table in mysql but I am getting a syntax error.
Here is the code:
CREATE TABLE survey(
id INTEGER(15) NOT NULL,
`name` UNICODE(65) NOT NULL,
parentId INTEGER(15) NOT NULL,
createdAt TIMESTAMP(30) NOT NULL,
modifiedAt TIMESTAMP (30) NOT NULL,
surveyUrl UNICODE(100) NOT NULL,
PRIMARY KEY(id)
);
I have tried changing the UNICODE to STRING and placing the column names between marks with no luck. Thank you!
A:
a Datatype UNICOde and the prcision 30 for timestampo are not allowed.
You can switch to following format, iff you need another character set and collation besides the default
More about collations
CREATE TABLE survey(
id BIGINT NOT NULL,
`name` varchar(65) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
parentId BIGINT NOT NULL,
createdAt TIMESTAMP(6) NOT NULL,
modifiedAt TIMESTAMP (6) NOT NULL,
surveyUrl varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
PRIMARY KEY(id)
);
| Cannot create table in MYSQL with UNICODE and INTEGER types, ERROR: 1064 | I am trying to create a simple table in mysql but I am getting a syntax error.
Here is the code:
CREATE TABLE survey(
id INTEGER(15) NOT NULL,
`name` UNICODE(65) NOT NULL,
parentId INTEGER(15) NOT NULL,
createdAt TIMESTAMP(30) NOT NULL,
modifiedAt TIMESTAMP (30) NOT NULL,
surveyUrl UNICODE(100) NOT NULL,
PRIMARY KEY(id)
);
I have tried changing the UNICODE to STRING and placing the column names between marks with no luck. Thank you!
| [
"a Datatype UNICOde and the prcision 30 for timestampo are not allowed.\nYou can switch to following format, iff you need another character set and collation besides the default\nMore about collations\nCREATE TABLE survey(\n id BIGINT NOT NULL,\n `name` varchar(65) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,\n parentId BIGINT NOT NULL, \n createdAt TIMESTAMP(6) NOT NULL, \n modifiedAt TIMESTAMP (6) NOT NULL, \n surveyUrl varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,\n PRIMARY KEY(id)\n);\n\n"
] | [
1
] | [] | [] | [
"mysql"
] | stackoverflow_0074671665_mysql.txt |
Q:
Unable to locate tools.jar
I am building a project in Java.
I have this error:
Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar
I have installed a JDK and the folder: C:\Program Files\Java\jre6\lib is in my system but the file tools.jar is not there.
A:
Yes, you've downloaded and installed the Java Runtime Environment (JRE) instead of the Java Development Kit (JDK). The latter has the tools.jar, java.exe, javac.exe, etc.
A:
In case this is still an issue for anyone, I have a bit of clarification on the previous answers. I was running into this same issue using ant with only a JDK installed. Although, the JDK installer gave me a directory structure like this:
Directory of C:\Program Files\Java
05/08/2012 09:43 AM <DIR> .
05/08/2012 09:43 AM <DIR> ..
05/08/2012 09:46 AM <DIR> jdk1.7.0_04
05/08/2012 09:19 AM <DIR> jre6
05/08/2012 09:44 AM <DIR> jre7
0 File(s) 0 bytes
and when I ran ant, it complained about not finding tools.jar under the jre7 subdirectory. It wasn't until I set "JAVA_HOME=C:\Program Files\Java\jdk1.7.0_04" that the error went away.
A:
Install the Java SDK.
Add a System Environment Variable called JAVA_HOME with the value of JDK location.
Go to Control Panel\System and Security\System. Advanced System Settings, Environment Variables, System Variables, New... Example:
Variable Name:JAVA_HOME
Variable Value: C:\Program Files\Java\jdk1.7.0_21
Close/reopen your CMD window so that the new variable takes effect before attempting to re-run the ant command.
A:
I had the same problem and copying C:\Program Files\Java\jdk1.6.0_26\lib\tools.jar to C:\Program Files\Java\jre6\lib\ext worked for me
A:
If you have installed JDK 9.0.1 you will also have this problem as the tools.jar has been deprecated. See migration document.
A:
Set your JAVA_HOME environmental variable to point to C:\Program Files\Java\jdk1.7.0_02.
A:
If you are in Linux you can solve this by installing java on the system:
sudo apt-get install openjdk-7-jdk openjdk-7-jre
A:
No, according to your directory structure, you have installed a JRE, not a JDK. There's a difference.
C:\Program Files\Java\jre6\lib
^^^^
It should be something like:
C:\Program Files\Java\jdk1.6.0_24
A:
Don't spend too much time looking for tools.jar. If you get an error like that, don't be upset.
If you already have java JDK 1.5, go to your lib folder, and the tools.jar should be available there. Copy and paste it in your ant bin folder, then try to use the command ant -version.
You should see the expected result.
A:
I had the same issue on a linux machine. I was quite frustrated at first, because I have installed both the JDK and JRE. I am using version 1.6, 1.7 and 1.8 simultaneously, and I have played a lot with the alternatives to have everything set properly.
The problem was quite stupid to solve, yet counter-intuitive. While I was using the correct JDK, I paid attention to the path of the tools jar maven complained about - it was expecting it to be
$JAVA_HOME\..\lib\tools.jar
The $JAVA_HOME variable pointed directly to my jdk folder (/usr/local/java which was also the correct $PATH entry and alternative sym link). It actually searches for the lib folder outside the java directory, because:
$JAVA_HOME\..\lib\tools.jar
will resolve to
/usr/local/lib/tools.jar
and that is not a valid location.
To solve this, the $JAVA_HOME variable should instead point to this location /usr/local/java/jre (assuming the JDK path is /usr/local/java) -- there is actually jre folder inside the JDK installation directory, that comes with each JDK. This new setup will cause maven to look at the JRE directory, that is part of the JDK:
$JAVA_HOME\..\lib\tools
which now resolves to
/usr/local/java/jre/../lib/tools.jar
and finally to
/usr/local/java/lib/tools.jar
which is where the tools.jar really resides.
So, even if you are indeed using the JDK instead of the JRE, the $JAVA_HOME has to point to the JRE. Remember, the OS alternative should still refer to the JDK.
A:
go to your jdk path where you installed your java
For e.g In my PC JDK installed in the following path
"C:\Program Files\Java\jdk1.7.0_17\";
After go to the lib folder e.g "C:\Program Files\Java\jdk1.7.0_17\lib"
in the lib directory there is tool.jar file
Copy this file and past it in the lib forlder of jre7 directory
for e.g
"C:\Program Files\Java\jre7\lib"
A:
You may face similar problem on Ubuntu:
Embedded error: tools.jar not found: /usr/lib/jvm/java-7-openjdk-amd64/jre/../lib/tools.jar
The problem is with JAVA_HOME that is not set properly.
So, on Ubuntu 14.04 x64 using Java8:
sudo apt-get install openjdk-8-jdk openjdk-8-jre
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
A:
As many people mentioned, it looks like you are looking in your JRE instead of the JDK for the tools.jar file.
I would also like to mention that on recent versions of the JDK, there is no more tools.jar file. I downloaded the most recent JDK as of today (JDK version 12) and I could not find any tools.jar. I had to download JDK version 8 (1.8.0) here https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html to get the tools.jar file. I downloaded that version, took the tools.jar file and put it into my recent version's lib folder.
A:
It's worth observing that tools.jar has been removed from the JDK since Java 9. https://docs.oracle.com/javase/9/migrate/toc.htm#JSMIG-GUID-055EA9F4-835E-463F-B9E1-9081B3D9E55D
If people are facing this issue compiling a Java program with JDK 9+, you may need to review the dependencies of your projects.
In my case, I was trying to compile a project using AspectJ and the Maven plugin org.codehaus.mojo:aspectj-maven-plugin:1.11. After searching online, I found an alternative that supports Java 9+: dev.aspectj:aspectj-maven-plugin:1.13.M3.
A:
I had the same problem even after installing Java JDK and set JAVA_HOME to ..\jdk1.6.0_45\bin folder.
Ant is still trying to find tools.jar in C:\Program Files\Java\jre6\lib folder.
I've fixed it by adding JAVACMD environment variable and set path for it to java.exe in the jdk folder.
In my case it was C:\Program Files\Java\jdk1.6.0_45\bin\java.exe
A:
it has been solved with me in windows os by setting the JAVA_HOME variable before running as follows:
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_111
A:
Make sure that both the %JAVA_HOME% and %JAVA_HOME%/bin paths are added to your PATH variable.
All the answers about copying tools.jar into the correct position is a poor idea at best.
Make sure that your IDE can find these jars the way it was designed and intended for.
A:
In eclipse window> preferences>Java> Installed JRE, I pointed the directory to the jre directory in the jdk 1.7 and i worked file for me
e.g C:\Program Files\Java\jdk1.7.0_71\jre
A:
I had my JDK_path (C:\Program Files\Java\jdk1.7.0_79) in my JAVA_HOME and also the JDK_path\bin in my PATH. But, still my ant was using the JRE instead of JDK.
The issue was I had C:\ProgramData\Oracle\Java\javapathbefore my JDK_path in PATH variable. I simply moved my JDK_path before the oracle one and the issue solved.
A:
solving this problem I have simply copied the tools.jar file from C:\Program Files\Java\jre1.8.0_112\lib to C:\Program Files\Java\jdk1.8.0_112\lib so that I have two tools.jar files instead of one and problem disappeared.
A:
Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar
if you have installed jdk then
..Java/jdkx.x.x
folder must exist there so in stall it and give full path like
C:\Program Files\Java\jdk1.6.0\lib\tools.jar
A:
Make sure that your classpath is set correctly and pointing to the correct version of the JDK that you have installed. Also, are you using Open JDK? I have had this issue before after I tried to move from open JDK to Suns JDK. This is an example of how that issue could be fixed.
A:
maven-compiler-plugin use jdk ,not jre,
tools.jar is in C:\Program Files\Java\jdk1.6.0\lib\tools.jar
you must config project JRE System Libary with jdk,not jar. This is the simplest solution.
A:
Right click on your ant file
Go to "Run as" then click on "Ant Build..."
Go to the "JRE" tab
Select a JDK and not a JRE
A:
For me what's working: I downloaded an old version of Java 1.7
I actually set my JAVA_HOME from C:/program files X86/Java BUT after I installed the 1.7 version I had another Java in program files/Java. And at this moment I found the tools.jar here. Then I changed for this new path and it's working
A:
I was also facing the same error.
This was removed after setting Java_Home path to C:\Program Files\Java\jdk1.8.0_121.
Please ensure bin is not included in the path and no slash is there after jdk1.8.0_121 after you have defined %JAVA_HOME%\bin in the system path variable.
A:
If you're in a RHEL environment the package name containing tools.jar would end with "openjdk-devel".
A:
This is the solution for Windows: in Computer > Advanced system settings > Advanced > Environment variables..., add this in System variables:
A:
I have downloaded tools.jar and after that I copied it into path in error message.
C:\Program Files\Java\jdk-11.0.1\bin > paste here tools.jar
After that I have restarted Spring Tool Suit 4 and everything was working.
When I was trying to fix that problem I have made new environmental variable:
Control Panel / System / Advenced / Environmental variables / new
Name : JAVA_HOME
Value: C:\Program Files\Java\jdk-11.0.1
But I do not know is it necessary.
A:
maybe you have updated the JREs in the OS, and the addition has added in the "path" of the environment variables an entry ".../Oracle/jer" that overwrites your JAVA_HOME.
try to remove it from the "path" by leaving JAVA_HOME.
A:
Incase it helps, the problem for me was that I had 2 entries in my PATH environment variable which pointed to a location containing the javaw executable.
I cleaned up the variable to make sure that "%JAVA_HOME%\bin" was the only entry referencing a location containing my java executables.
A:
This happens when the Environment Variable JAVA_HOME is not set, or points to the wrong directory. You can see the value that Ant has by running the command:
ant -diagnostics
And looking for the line that shows java.home. If you have grep installed then you can simple run:
ant -diagnostics | grep java.home
To fix the issue, set the JAVA_HOME Environment Variable to the JDK directory. While setting the variable differs slightly between *nix and Windows, the rest works the same on all operating systems. So it doesn't matter if you use the GUI that Windows provides, or the set or setx commands, as long as the value is set prior to calling ant (if you've set it globally then it must exist before you open the shell/terminal window).
After setting JAVA_HOME you can run ant -version, for example, and get the result, e.g.
Apache Ant(TM) version 1.10.8 compiled on May 10 2020
A:
Step1 Check your jdk is installed. and variable path is setted.
Step2 unistall your eclipes and reinstall it. other wise It will continue to be a problem
A:
The latest versions of Java do not have tools.jar in the lib folder. Remove tools.jar entry in environment variables and retry it.
| Unable to locate tools.jar | I am building a project in Java.
I have this error:
Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar
I have installed a JDK and the folder: C:\Program Files\Java\jre6\lib is in my system but the file tools.jar is not there.
| [
"Yes, you've downloaded and installed the Java Runtime Environment (JRE) instead of the Java Development Kit (JDK). The latter has the tools.jar, java.exe, javac.exe, etc.\n",
"In case this is still an issue for anyone, I have a bit of clarification on the previous answers. I was running into this same issue using ant with only a JDK installed. Although, the JDK installer gave me a directory structure like this:\n Directory of C:\\Program Files\\Java\n\n05/08/2012 09:43 AM <DIR> .\n05/08/2012 09:43 AM <DIR> ..\n05/08/2012 09:46 AM <DIR> jdk1.7.0_04\n05/08/2012 09:19 AM <DIR> jre6\n05/08/2012 09:44 AM <DIR> jre7\n 0 File(s) 0 bytes\n\nand when I ran ant, it complained about not finding tools.jar under the jre7 subdirectory. It wasn't until I set \"JAVA_HOME=C:\\Program Files\\Java\\jdk1.7.0_04\" that the error went away.\n",
"\nInstall the Java SDK. \nAdd a System Environment Variable called JAVA_HOME with the value of JDK location.\nGo to Control Panel\\System and Security\\System. Advanced System Settings, Environment Variables, System Variables, New... Example:\nVariable Name:JAVA_HOME\nVariable Value: C:\\Program Files\\Java\\jdk1.7.0_21 \nClose/reopen your CMD window so that the new variable takes effect before attempting to re-run the ant command.\n\n",
"I had the same problem and copying C:\\Program Files\\Java\\jdk1.6.0_26\\lib\\tools.jar to C:\\Program Files\\Java\\jre6\\lib\\ext worked for me \n",
"If you have installed JDK 9.0.1 you will also have this problem as the tools.jar has been deprecated. See migration document.\n",
"Set your JAVA_HOME environmental variable to point to C:\\Program Files\\Java\\jdk1.7.0_02.\n",
"If you are in Linux you can solve this by installing java on the system:\nsudo apt-get install openjdk-7-jdk openjdk-7-jre\n\n",
"No, according to your directory structure, you have installed a JRE, not a JDK. There's a difference.\nC:\\Program Files\\Java\\jre6\\lib\n ^^^^\n\nIt should be something like:\nC:\\Program Files\\Java\\jdk1.6.0_24\n\n",
"Don't spend too much time looking for tools.jar. If you get an error like that, don't be upset. \nIf you already have java JDK 1.5, go to your lib folder, and the tools.jar should be available there. Copy and paste it in your ant bin folder, then try to use the command ant -version.\nYou should see the expected result.\n",
"I had the same issue on a linux machine. I was quite frustrated at first, because I have installed both the JDK and JRE. I am using version 1.6, 1.7 and 1.8 simultaneously, and I have played a lot with the alternatives to have everything set properly.\nThe problem was quite stupid to solve, yet counter-intuitive. While I was using the correct JDK, I paid attention to the path of the tools jar maven complained about - it was expecting it to be\n$JAVA_HOME\\..\\lib\\tools.jar\n\nThe $JAVA_HOME variable pointed directly to my jdk folder (/usr/local/java which was also the correct $PATH entry and alternative sym link). It actually searches for the lib folder outside the java directory, because:\n$JAVA_HOME\\..\\lib\\tools.jar\n\nwill resolve to\n/usr/local/lib/tools.jar\n\nand that is not a valid location.\nTo solve this, the $JAVA_HOME variable should instead point to this location /usr/local/java/jre (assuming the JDK path is /usr/local/java) -- there is actually jre folder inside the JDK installation directory, that comes with each JDK. This new setup will cause maven to look at the JRE directory, that is part of the JDK:\n$JAVA_HOME\\..\\lib\\tools\n\nwhich now resolves to\n/usr/local/java/jre/../lib/tools.jar\n\nand finally to\n/usr/local/java/lib/tools.jar\n\nwhich is where the tools.jar really resides.\nSo, even if you are indeed using the JDK instead of the JRE, the $JAVA_HOME has to point to the JRE. Remember, the OS alternative should still refer to the JDK.\n",
"go to your jdk path where you installed your java\nFor e.g In my PC JDK installed in the following path\n\"C:\\Program Files\\Java\\jdk1.7.0_17\\\";\nAfter go to the lib folder e.g \"C:\\Program Files\\Java\\jdk1.7.0_17\\lib\"\nin the lib directory there is tool.jar file\nCopy this file and past it in the lib forlder of jre7 directory\nfor e.g\n\"C:\\Program Files\\Java\\jre7\\lib\"\n",
"You may face similar problem on Ubuntu:\nEmbedded error: tools.jar not found: /usr/lib/jvm/java-7-openjdk-amd64/jre/../lib/tools.jar\n\nThe problem is with JAVA_HOME that is not set properly.\nSo, on Ubuntu 14.04 x64 using Java8:\nsudo apt-get install openjdk-8-jdk openjdk-8-jre\nexport JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\n\n",
"As many people mentioned, it looks like you are looking in your JRE instead of the JDK for the tools.jar file.\nI would also like to mention that on recent versions of the JDK, there is no more tools.jar file. I downloaded the most recent JDK as of today (JDK version 12) and I could not find any tools.jar. I had to download JDK version 8 (1.8.0) here https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html to get the tools.jar file. I downloaded that version, took the tools.jar file and put it into my recent version's lib folder.\n",
"It's worth observing that tools.jar has been removed from the JDK since Java 9. https://docs.oracle.com/javase/9/migrate/toc.htm#JSMIG-GUID-055EA9F4-835E-463F-B9E1-9081B3D9E55D\nIf people are facing this issue compiling a Java program with JDK 9+, you may need to review the dependencies of your projects.\nIn my case, I was trying to compile a project using AspectJ and the Maven plugin org.codehaus.mojo:aspectj-maven-plugin:1.11. After searching online, I found an alternative that supports Java 9+: dev.aspectj:aspectj-maven-plugin:1.13.M3.\n",
"I had the same problem even after installing Java JDK and set JAVA_HOME to ..\\jdk1.6.0_45\\bin folder. \nAnt is still trying to find tools.jar in C:\\Program Files\\Java\\jre6\\lib folder.\nI've fixed it by adding JAVACMD environment variable and set path for it to java.exe in the jdk folder.\nIn my case it was C:\\Program Files\\Java\\jdk1.6.0_45\\bin\\java.exe\n",
"it has been solved with me in windows os by setting the JAVA_HOME variable before running as follows:\nset JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_111\n",
"Make sure that both the %JAVA_HOME% and %JAVA_HOME%/bin paths are added to your PATH variable.\nAll the answers about copying tools.jar into the correct position is a poor idea at best.\nMake sure that your IDE can find these jars the way it was designed and intended for.\n",
"In eclipse window> preferences>Java> Installed JRE, I pointed the directory to the jre directory in the jdk 1.7 and i worked file for me\ne.g C:\\Program Files\\Java\\jdk1.7.0_71\\jre\n",
"I had my JDK_path (C:\\Program Files\\Java\\jdk1.7.0_79) in my JAVA_HOME and also the JDK_path\\bin in my PATH. But, still my ant was using the JRE instead of JDK.\nThe issue was I had C:\\ProgramData\\Oracle\\Java\\javapathbefore my JDK_path in PATH variable. I simply moved my JDK_path before the oracle one and the issue solved.\n",
"solving this problem I have simply copied the tools.jar file from C:\\Program Files\\Java\\jre1.8.0_112\\lib to C:\\Program Files\\Java\\jdk1.8.0_112\\lib so that I have two tools.jar files instead of one and problem disappeared.\n",
"Expected to find it in C:\\Program Files\\Java\\jre6\\lib\\tools.jar\n\nif you have installed jdk then \n..Java/jdkx.x.x \nfolder must exist there so in stall it and give full path like\nC:\\Program Files\\Java\\jdk1.6.0\\lib\\tools.jar\n\n",
"Make sure that your classpath is set correctly and pointing to the correct version of the JDK that you have installed. Also, are you using Open JDK? I have had this issue before after I tried to move from open JDK to Suns JDK. This is an example of how that issue could be fixed.\n",
"maven-compiler-plugin use jdk ,not jre, \n tools.jar is in C:\\Program Files\\Java\\jdk1.6.0\\lib\\tools.jar\nyou must config project JRE System Libary with jdk,not jar. This is the simplest solution.\n",
"\nRight click on your ant file\nGo to \"Run as\" then click on \"Ant Build...\"\nGo to the \"JRE\" tab\nSelect a JDK and not a JRE\n\n",
"For me what's working: I downloaded an old version of Java 1.7\nI actually set my JAVA_HOME from C:/program files X86/Java BUT after I installed the 1.7 version I had another Java in program files/Java. And at this moment I found the tools.jar here. Then I changed for this new path and it's working\n",
"I was also facing the same error.\nThis was removed after setting Java_Home path to C:\\Program Files\\Java\\jdk1.8.0_121.\nPlease ensure bin is not included in the path and no slash is there after jdk1.8.0_121 after you have defined %JAVA_HOME%\\bin in the system path variable.\n",
"If you're in a RHEL environment the package name containing tools.jar would end with \"openjdk-devel\".\n",
"This is the solution for Windows: in Computer > Advanced system settings > Advanced > Environment variables..., add this in System variables:\n\n",
"I have downloaded tools.jar and after that I copied it into path in error message.\nC:\\Program Files\\Java\\jdk-11.0.1\\bin > paste here tools.jar\nAfter that I have restarted Spring Tool Suit 4 and everything was working.\nWhen I was trying to fix that problem I have made new environmental variable:\nControl Panel / System / Advenced / Environmental variables / new \nName : JAVA_HOME\nValue: C:\\Program Files\\Java\\jdk-11.0.1\nBut I do not know is it necessary. \n",
"maybe you have updated the JREs in the OS, and the addition has added in the \"path\" of the environment variables an entry \".../Oracle/jer\" that overwrites your JAVA_HOME.\ntry to remove it from the \"path\" by leaving JAVA_HOME.\n",
"Incase it helps, the problem for me was that I had 2 entries in my PATH environment variable which pointed to a location containing the javaw executable.\nI cleaned up the variable to make sure that \"%JAVA_HOME%\\bin\" was the only entry referencing a location containing my java executables.\n",
"This happens when the Environment Variable JAVA_HOME is not set, or points to the wrong directory. You can see the value that Ant has by running the command:\nant -diagnostics\n\nAnd looking for the line that shows java.home. If you have grep installed then you can simple run:\nant -diagnostics | grep java.home\n\nTo fix the issue, set the JAVA_HOME Environment Variable to the JDK directory. While setting the variable differs slightly between *nix and Windows, the rest works the same on all operating systems. So it doesn't matter if you use the GUI that Windows provides, or the set or setx commands, as long as the value is set prior to calling ant (if you've set it globally then it must exist before you open the shell/terminal window).\nAfter setting JAVA_HOME you can run ant -version, for example, and get the result, e.g.\n\nApache Ant(TM) version 1.10.8 compiled on May 10 2020\n\n",
"Step1 Check your jdk is installed. and variable path is setted.\nStep2 unistall your eclipes and reinstall it. other wise It will continue to be a problem\n",
"The latest versions of Java do not have tools.jar in the lib folder. Remove tools.jar entry in environment variables and retry it.\n"
] | [
202,
91,
42,
32,
20,
10,
10,
7,
5,
5,
3,
3,
3,
3,
2,
2,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
"I have resolved tool.jar file error recently. I am using eclipse oxygen ide. It works perfectly and easy. Repeat these steps on your system as\n\nDownload tool.jar file according to your jre jdk version. Lets suppose tool.jar file is 1.8.0.tool.jar\nAfter donwload 1.8 .0 tool.jar file rename is as as tool.jar\nThen go to your jdk installation folder\nThen go to lib folder open it\nAnd paste here \nYou will make this type path. E:\\jdk 8\\lib\\tools.jar\n\n"
] | [
-1
] | [
"ant",
"java",
"tools.jar"
] | stackoverflow_0005730815_ant_java_tools.jar.txt |
Q:
My Python Recursive Function is returning None
I made a function that is being called recursively, and the condition for it to keep being called is a user input.
The recursion is working but the final value of the variable is being returned as None.
I am a beginner at Python and i am trying to learn Functions and Recursion before going to Classes, OOP, Wrappers, etc.
Here is my code:
Main Py:
import funcoes_moeda
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
"1 - Aumentar Valor \n" \
"2 - Diminuir Valor \n" \
"3 - Dobrar Valor \n" \
"4 - Dividir Valor \n" \
"0 - Encerrar o Prorama"
)
valor = switch(valor)
print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))
Imported Functions:
def aumentar(valor):
quantia_aumentada = float(input('Insira a quantidade que voce deseja acrescentar: '))
valor += quantia_aumentada
return valor
def diminuir():
pass
def dobro():
pass
def metade():
pass
When i tried executing this, what i got was:
Insira o valor: 100.00
Escolha a funcao a ser aplicada no valor inserido:
1 - Aumentar Valor
2 - Diminuir Valor
3 - Dobrar Valor
4 - Dividir Valor
0 - Encerrar o Prorama
Escolha uma opcao... (0 para encerrar) : 1
Insira a quantidade que voce deseja acrescentar: 100.00
Valor aumentado: 200.0
Escolha uma opcao... (0 para encerrar) : 1
Insira a quantidade que voce deseja acrescentar: 100.00
Valor aumentado: 300.0
Escolha uma opcao... (0 para encerrar) : 0
Funcao foi aplicada. O valor final ficou: None
For a test case, you can use:
Chose 100.00, option 1 (2 times is enough), increment 100.00 each call.
Expected output: Current value = 300.00 (Because 100 + 100 + 100)
But i got None at the last print...
Please. What am i doing wrong??? :(
Thank you for all the help.
PS: I tried going through the following answers, but i was not able to solve this problem because the explanation was for the problems in the question, and i found it was a litle different than mine..
1 > Recursive function returning none - Dint understand.
2 > python recursive function returning none instead of string - This is treating a CSV file.
A:
The problem is that when the case variable is equal to 0, the return valor statement is being executed within the switch() function, but this function is being called recursively so the value of valor is not being returned to the caller.
To fix this, you can add another return statement at the end of the switch() function that returns the value of valor when case is 0. This will ensure that the value of valor is returned to the caller, even when the switch() function is being called recursively.
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
# Return the value of valor when case is 0
return valor
A:
When returning a value the recursion is braking and the value returns to the previous call of the function. If you want to return the value to the first call, you can return the value every time you call switch:
import funcoes_moeda
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
return switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
"1 - Aumentar Valor \n" \
"2 - Diminuir Valor \n" \
"3 - Dobrar Valor \n" \
"4 - Dividir Valor \n" \
"0 - Encerrar o Prorama"
)
valor = switch(valor)
print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))
A:
Two issues:
The return at the end of the function 'switch' should be at the end of the function and not part of the 'else' case. Because if you select '1' you will change the value of 'valor', but after changing the value you exit the function withou returning a value.
The returned value of the recursive call to 'switch' in the code section of 'if case == 1:' is not saved and therefore lost.
If you only correct the first point above you will get changed values only from the top call to 'switch', but all changes from the recursive calls will get lost.
The solution proposed by thebjorn solves both above listed issues. But treating the issues one by one, might be easier to understand.
| My Python Recursive Function is returning None | I made a function that is being called recursively, and the condition for it to keep being called is a user input.
The recursion is working but the final value of the variable is being returned as None.
I am a beginner at Python and i am trying to learn Functions and Recursion before going to Classes, OOP, Wrappers, etc.
Here is my code:
Main Py:
import funcoes_moeda
def switch(valor):
case = int(input('Escolha uma opcao... (0 para encerrar) : '))
if case == 1:
valor = funcoes_moeda.aumentar(valor)
print('Valor aumentado: {}'.format(valor))
switch(valor)
elif case == 2:
pass
elif case == 3:
pass
elif case == 4:
pass
else:
return valor
valor = float(input('Insira o valor: '))
print("Escolha a funcao a ser aplicada no valor inserido: \n" \
"1 - Aumentar Valor \n" \
"2 - Diminuir Valor \n" \
"3 - Dobrar Valor \n" \
"4 - Dividir Valor \n" \
"0 - Encerrar o Prorama"
)
valor = switch(valor)
print('Funcao foi aplicada. O valor final ficou: {}'.format(valor))
Imported Functions:
def aumentar(valor):
quantia_aumentada = float(input('Insira a quantidade que voce deseja acrescentar: '))
valor += quantia_aumentada
return valor
def diminuir():
pass
def dobro():
pass
def metade():
pass
When i tried executing this, what i got was:
Insira o valor: 100.00
Escolha a funcao a ser aplicada no valor inserido:
1 - Aumentar Valor
2 - Diminuir Valor
3 - Dobrar Valor
4 - Dividir Valor
0 - Encerrar o Prorama
Escolha uma opcao... (0 para encerrar) : 1
Insira a quantidade que voce deseja acrescentar: 100.00
Valor aumentado: 200.0
Escolha uma opcao... (0 para encerrar) : 1
Insira a quantidade que voce deseja acrescentar: 100.00
Valor aumentado: 300.0
Escolha uma opcao... (0 para encerrar) : 0
Funcao foi aplicada. O valor final ficou: None
For a test case, you can use:
Chose 100.00, option 1 (2 times is enough), increment 100.00 each call.
Expected output: Current value = 300.00 (Because 100 + 100 + 100)
But i got None at the last print...
Please. What am i doing wrong??? :(
Thank you for all the help.
PS: I tried going through the following answers, but i was not able to solve this problem because the explanation was for the problems in the question, and i found it was a litle different than mine..
1 > Recursive function returning none - Dint understand.
2 > python recursive function returning none instead of string - This is treating a CSV file.
| [
"The problem is that when the case variable is equal to 0, the return valor statement is being executed within the switch() function, but this function is being called recursively so the value of valor is not being returned to the caller.\nTo fix this, you can add another return statement at the end of the switch() function that returns the value of valor when case is 0. This will ensure that the value of valor is returned to the caller, even when the switch() function is being called recursively.\ndef switch(valor):\n case = int(input('Escolha uma opcao... (0 para encerrar) : '))\n if case == 1:\n valor = funcoes_moeda.aumentar(valor)\n print('Valor aumentado: {}'.format(valor))\n switch(valor)\n\n elif case == 2:\n pass\n elif case == 3:\n pass\n elif case == 4:\n pass\n else:\n return valor\n\n # Return the value of valor when case is 0\n return valor\n\n",
"When returning a value the recursion is braking and the value returns to the previous call of the function. If you want to return the value to the first call, you can return the value every time you call switch:\nimport funcoes_moeda\n\ndef switch(valor):\n case = int(input('Escolha uma opcao... (0 para encerrar) : '))\n if case == 1:\n valor = funcoes_moeda.aumentar(valor)\n print('Valor aumentado: {}'.format(valor))\n return switch(valor)\n\n elif case == 2:\n pass\n elif case == 3:\n pass\n elif case == 4:\n pass\n else:\n return valor\n\nvalor = float(input('Insira o valor: '))\nprint(\"Escolha a funcao a ser aplicada no valor inserido: \\n\" \\\n \"1 - Aumentar Valor \\n\" \\\n \"2 - Diminuir Valor \\n\" \\\n \"3 - Dobrar Valor \\n\" \\\n \"4 - Dividir Valor \\n\" \\\n \"0 - Encerrar o Prorama\"\n )\n\nvalor = switch(valor)\n\nprint('Funcao foi aplicada. O valor final ficou: {}'.format(valor))\n\n",
"Two issues:\n\nThe return at the end of the function 'switch' should be at the end of the function and not part of the 'else' case. Because if you select '1' you will change the value of 'valor', but after changing the value you exit the function withou returning a value.\nThe returned value of the recursive call to 'switch' in the code section of 'if case == 1:' is not saved and therefore lost.\n\nIf you only correct the first point above you will get changed values only from the top call to 'switch', but all changes from the recursive calls will get lost.\nThe solution proposed by thebjorn solves both above listed issues. But treating the issues one by one, might be easier to understand.\n"
] | [
1,
0,
0
] | [] | [] | [
"function",
"python",
"python_3.x",
"recursion"
] | stackoverflow_0074671577_function_python_python_3.x_recursion.txt |
Q:
Generate sha256 with OpenSSL and C++
I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post at Generate SHA hash in C++ using OpenSSL library, but I'm looking to specifically create sha256.
UPDATE:
Seems to be a problem with the include paths. It can't find any OpenSSL functions even though I included
#include "openssl/sha.h"
and I included the paths in my build
-I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto
A:
Here's how I did it:
void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
void sha256_string(char *string, char outputBuffer[65])
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(hash, &sha256);
int i = 0;
for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
}
outputBuffer[64] = 0;
}
int sha256_file(char *path, char outputBuffer[65])
{
FILE *file = fopen(path, "rb");
if(!file) return -534;
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
const int bufSize = 32768;
unsigned char *buffer = malloc(bufSize);
int bytesRead = 0;
if(!buffer) return ENOMEM;
while((bytesRead = fread(buffer, 1, bufSize, file)))
{
SHA256_Update(&sha256, buffer, bytesRead);
}
SHA256_Final(hash, &sha256);
sha256_hash_string(hash, outputBuffer);
fclose(file);
free(buffer);
return 0;
}
It's called like this:
static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);
A:
std based
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
#include <openssl/sha.h>
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
int main() {
cout << sha256("1234567890_1") << endl;
cout << sha256("1234567890_2") << endl;
cout << sha256("1234567890_3") << endl;
cout << sha256("1234567890_4") << endl;
return 0;
}
A:
Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>
bool computeHash(const std::string& unhashed, std::string& hashed)
{
bool success = false;
EVP_MD_CTX* context = EVP_MD_CTX_new();
if(context != NULL)
{
if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
{
if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
{
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int lengthOfHash = 0;
if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
{
std::stringstream ss;
for(unsigned int i = 0; i < lengthOfHash; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
hashed = ss.str();
success = true;
}
}
}
EVP_MD_CTX_free(context);
}
return success;
}
int main(int, char**)
{
std::string pw1 = "password1", pw1hashed;
std::string pw2 = "password2", pw2hashed;
std::string pw3 = "password3", pw3hashed;
std::string pw4 = "password4", pw4hashed;
hashPassword(pw1, pw1hashed);
hashPassword(pw2, pw2hashed);
hashPassword(pw3, pw3hashed);
hashPassword(pw4, pw4hashed);
std::cout << pw1hashed << std::endl;
std::cout << pw2hashed << std::endl;
std::cout << pw3hashed << std::endl;
std::cout << pw4hashed << std::endl;
return 0;
}
The advantage of this higher level interface is that you simply need to swap out the EVP_sha256() call with another digest's function, e.g. EVP_sha512(), to use a different digest. So it adds some flexibility.
A:
A more "C++"ish version
#include <iostream>
#include <sstream>
#include "openssl/sha.h"
using namespace std;
string to_hex(unsigned char s) {
stringstream ss;
ss << hex << (int) s;
return ss.str();
}
string sha256(string line) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, line.c_str(), line.length());
SHA256_Final(hash, &sha256);
string output = "";
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
output += to_hex(hash[i]);
}
return output;
}
int main() {
cout << sha256("hello, world") << endl;
return 0;
}
A:
Here's the function I personally use - I simply derived it from the function I used for sha-1 hashing:
char *str2sha256( const char *str, int length ) {
int n;
SHA256_CTX c;
unsigned char digest[ SHA256_DIGEST_LENGTH ];
char *out = (char*) malloc( 33 );
SHA256_Init( &c );
while ( length > 0 ) {
if ( length > 512 ) SHA256_Update( &c, str, 512 );
else SHA256_Update( &c, str, length );
length -= 512;
str += 512;
}
SHA256_Final ( digest, &c );
for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )
snprintf( &( out[ n*2 ] ), 16*2, "%02x", (unsigned int) digest[ n ] );
return out;
}
A:
If you want to compute the sha256 hash of a file...
auto sha256 = [](std::string fname,
std::vector<unsigned char>& hash) -> bool {
std::unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX *)>
evpCtx(EVP_MD_CTX_new(), EVP_MD_CTX_free);
EVP_DigestInit_ex(evpCtx.get(), EVP_sha256(), nullptr);
constexpr size_t buffer_size { 1 << 12 };
std::vector<char> buffer(buffer_size,'\0');
std::ifstream fp(fname, std::ios::binary);
if (!fp.is_open()) {
std::cerr << "Unable to open '" << fname << "'!\n";
return false;
}
while (fp.good()) {
fp.read(buffer.data(), buffer_size);
EVP_DigestUpdate (evpCtx.get(), buffer.data(), fp.gcount());
}
fp.close();
hash.resize(SHA256_DIGEST_LENGTH);
std::fill(hash.begin(), hash.end(), 0);
unsigned int len;
EVP_DigestFinal_ex (evpCtx.get(), hash.data(), &len);
return true;
};
...
std::vector<unsigned char> hash;
sha256("/etc/profile", hash);
std::stringstream out;
for (size_t i = 0; i < hash.size(); i++)
out << std::setfill('0') << std::setw(2)
<< std::hex << int(hash[i]);
std::string hashStr = out.str();
std::cout << hashStr << std::endl;
...
a3fe9f414586c0d3cacbe3b6920a09d8718e503bca22e23fef882203bf765065
| Generate sha256 with OpenSSL and C++ | I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post at Generate SHA hash in C++ using OpenSSL library, but I'm looking to specifically create sha256.
UPDATE:
Seems to be a problem with the include paths. It can't find any OpenSSL functions even though I included
#include "openssl/sha.h"
and I included the paths in my build
-I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto
| [
"Here's how I did it:\nvoid sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])\n{\n int i = 0;\n\n for(i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n sprintf(outputBuffer + (i * 2), \"%02x\", hash[i]);\n }\n\n outputBuffer[64] = 0;\n}\n\n\nvoid sha256_string(char *string, char outputBuffer[65])\n{\n unsigned char hash[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n SHA256_Update(&sha256, string, strlen(string));\n SHA256_Final(hash, &sha256);\n int i = 0;\n for(i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n sprintf(outputBuffer + (i * 2), \"%02x\", hash[i]);\n }\n outputBuffer[64] = 0;\n}\n\nint sha256_file(char *path, char outputBuffer[65])\n{\n FILE *file = fopen(path, \"rb\");\n if(!file) return -534;\n\n unsigned char hash[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n const int bufSize = 32768;\n unsigned char *buffer = malloc(bufSize);\n int bytesRead = 0;\n if(!buffer) return ENOMEM;\n while((bytesRead = fread(buffer, 1, bufSize, file)))\n {\n SHA256_Update(&sha256, buffer, bytesRead);\n }\n SHA256_Final(hash, &sha256);\n\n sha256_hash_string(hash, outputBuffer);\n fclose(file);\n free(buffer);\n return 0;\n}\n\nIt's called like this:\nstatic unsigned char buffer[65];\nsha256(\"string\", buffer);\nprintf(\"%s\\n\", buffer);\n\n",
"std based\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\n#include <openssl/sha.h>\nstring sha256(const string str)\n{\n unsigned char hash[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n SHA256_Update(&sha256, str.c_str(), str.size());\n SHA256_Final(hash, &sha256);\n stringstream ss;\n for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n ss << hex << setw(2) << setfill('0') << (int)hash[i];\n }\n return ss.str();\n}\n\nint main() {\n cout << sha256(\"1234567890_1\") << endl;\n cout << sha256(\"1234567890_2\") << endl;\n cout << sha256(\"1234567890_3\") << endl;\n cout << sha256(\"1234567890_4\") << endl;\n return 0;\n}\n\n",
"Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <openssl/evp.h>\n\nbool computeHash(const std::string& unhashed, std::string& hashed)\n{\n bool success = false;\n\n EVP_MD_CTX* context = EVP_MD_CTX_new();\n\n if(context != NULL)\n {\n if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))\n {\n if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))\n {\n unsigned char hash[EVP_MAX_MD_SIZE];\n unsigned int lengthOfHash = 0;\n\n if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))\n {\n std::stringstream ss;\n for(unsigned int i = 0; i < lengthOfHash; ++i)\n {\n ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];\n }\n\n hashed = ss.str();\n success = true;\n }\n }\n }\n\n EVP_MD_CTX_free(context);\n }\n\n return success;\n}\n\nint main(int, char**)\n{\n std::string pw1 = \"password1\", pw1hashed;\n std::string pw2 = \"password2\", pw2hashed;\n std::string pw3 = \"password3\", pw3hashed;\n std::string pw4 = \"password4\", pw4hashed;\n\n hashPassword(pw1, pw1hashed);\n hashPassword(pw2, pw2hashed);\n hashPassword(pw3, pw3hashed);\n hashPassword(pw4, pw4hashed);\n\n std::cout << pw1hashed << std::endl;\n std::cout << pw2hashed << std::endl;\n std::cout << pw3hashed << std::endl;\n std::cout << pw4hashed << std::endl;\n\n return 0;\n}\n\nThe advantage of this higher level interface is that you simply need to swap out the EVP_sha256() call with another digest's function, e.g. EVP_sha512(), to use a different digest. So it adds some flexibility.\n",
"A more \"C++\"ish version\n#include <iostream>\n#include <sstream>\n\n#include \"openssl/sha.h\"\n\nusing namespace std;\n\nstring to_hex(unsigned char s) {\n stringstream ss;\n ss << hex << (int) s;\n return ss.str();\n} \n\nstring sha256(string line) { \n unsigned char hash[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n SHA256_Update(&sha256, line.c_str(), line.length());\n SHA256_Final(hash, &sha256);\n\n string output = \"\"; \n for(int i = 0; i < SHA256_DIGEST_LENGTH; i++) {\n output += to_hex(hash[i]);\n }\n return output;\n}\n\nint main() {\n cout << sha256(\"hello, world\") << endl;\n\n return 0;\n}\n\n",
"Here's the function I personally use - I simply derived it from the function I used for sha-1 hashing:\nchar *str2sha256( const char *str, int length ) {\n int n;\n SHA256_CTX c;\n unsigned char digest[ SHA256_DIGEST_LENGTH ];\n char *out = (char*) malloc( 33 );\n\n SHA256_Init( &c );\n\n while ( length > 0 ) {\n if ( length > 512 ) SHA256_Update( &c, str, 512 );\n else SHA256_Update( &c, str, length );\n\n length -= 512;\n str += 512;\n }\n\n SHA256_Final ( digest, &c );\n\n for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )\n snprintf( &( out[ n*2 ] ), 16*2, \"%02x\", (unsigned int) digest[ n ] );\n\n return out;\n}\n\n",
"If you want to compute the sha256 hash of a file...\nauto sha256 = [](std::string fname, \n std::vector<unsigned char>& hash) -> bool {\n std::unique_ptr<EVP_MD_CTX, void (*)(EVP_MD_CTX *)>\n evpCtx(EVP_MD_CTX_new(), EVP_MD_CTX_free);\n EVP_DigestInit_ex(evpCtx.get(), EVP_sha256(), nullptr);\n\n constexpr size_t buffer_size { 1 << 12 };\n std::vector<char> buffer(buffer_size,'\\0');\n\n std::ifstream fp(fname, std::ios::binary);\n if (!fp.is_open()) {\n std::cerr << \"Unable to open '\" << fname << \"'!\\n\";\n return false;\n }\n while (fp.good()) {\n fp.read(buffer.data(), buffer_size);\n EVP_DigestUpdate (evpCtx.get(), buffer.data(), fp.gcount());\n }\n fp.close();\n\n hash.resize(SHA256_DIGEST_LENGTH);\n std::fill(hash.begin(), hash.end(), 0);\n unsigned int len;\n EVP_DigestFinal_ex (evpCtx.get(), hash.data(), &len);\n\n return true;\n};\n\n...\n\nstd::vector<unsigned char> hash;\nsha256(\"/etc/profile\", hash);\nstd::stringstream out;\nfor (size_t i = 0; i < hash.size(); i++)\n out << std::setfill('0') << std::setw(2) \n << std::hex << int(hash[i]);\nstd::string hashStr = out.str();\nstd::cout << hashStr << std::endl;\n...\na3fe9f414586c0d3cacbe3b6920a09d8718e503bca22e23fef882203bf765065\n\n"
] | [
79,
68,
32,
1,
1,
0
] | [
"I think that you only have to replace SHA1 function with SHA256 function with tatk code from link in Your post\n"
] | [
-1
] | [
"c++",
"openssl",
"sha256",
"unix"
] | stackoverflow_0002262386_c++_openssl_sha256_unix.txt |
Q:
(Python) What is wrong in my code causing my program to crash index error
Program will run the first time through, but in the second loop it will sometimes crash. It was noted to me that it may be in regard to the toppers line, where a topper can be selected.
Error: "IndexError: list index out of range"
import random
toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']
def topper():
while True:
topper = input() #getting input
# random number between 1-3 for topper grab
randomTop = random.randint(1,4)
if topper.upper() == 'N' or topper.upper() == 'NO':
print('A clear glossy top coat it is!')
break
elif topper.upper() == 'Y' or topper.upper() == 'YES':
print('The topper you should use is ' + toppers[randomTop] + '.')
break
elif topper.upper() != ('N', 'NO', 'Y', 'YES') or topper.isalnum():
print('\nPlease enter a valid input. Y or N.')
continue
playloop()
As the program has a break to exit if the user would like, it is expected that the program can loop through endlessly until they are ready to quit. While the first loop works fine, but subsequent trials crash.
Any help is appreciated. :)
A:
toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']
randomTop = random.randint(1,4)
print('The topper you should use is ' + toppers[randomTop] + '.')
toppers is a list with four items. Python lists are indexed starting at zero, so the valid indexes are 0-3.
But you're picking a random number from 1 to 4. If you happen to pick 4, that is out of range. Use random.randint(0,3).
Or even better, use random.choice(toppers), so you don't have to worry about the index value at all.
| (Python) What is wrong in my code causing my program to crash index error | Program will run the first time through, but in the second loop it will sometimes crash. It was noted to me that it may be in regard to the toppers line, where a topper can be selected.
Error: "IndexError: list index out of range"
import random
toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']
def topper():
while True:
topper = input() #getting input
# random number between 1-3 for topper grab
randomTop = random.randint(1,4)
if topper.upper() == 'N' or topper.upper() == 'NO':
print('A clear glossy top coat it is!')
break
elif topper.upper() == 'Y' or topper.upper() == 'YES':
print('The topper you should use is ' + toppers[randomTop] + '.')
break
elif topper.upper() != ('N', 'NO', 'Y', 'YES') or topper.isalnum():
print('\nPlease enter a valid input. Y or N.')
continue
playloop()
As the program has a break to exit if the user would like, it is expected that the program can loop through endlessly until they are ready to quit. While the first loop works fine, but subsequent trials crash.
Any help is appreciated. :)
| [
"toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']\n\nrandomTop = random.randint(1,4)\nprint('The topper you should use is ' + toppers[randomTop] + '.')\n\ntoppers is a list with four items. Python lists are indexed starting at zero, so the valid indexes are 0-3.\nBut you're picking a random number from 1 to 4. If you happen to pick 4, that is out of range. Use random.randint(0,3).\nOr even better, use random.choice(toppers), so you don't have to worry about the index value at all.\n"
] | [
1
] | [] | [] | [
"index_error",
"python"
] | stackoverflow_0074671695_index_error_python.txt |
Q:
How do I make add the input parts into the loop like the menu?
The part of the code that ask for the length of the list and then the actual numbers the users want to use needs to be looped into the program like the menu is looped in. So that once it runs and the program is fulfilled it can loop again. However, the program needs to completely end once the number -1000 is entered or option C from the menu is entered. When I try I keep getting errors. Can someone help, please?
I tried to move that statement into the loop, I tried to call it in the while loop, but when I do that it either prints the statement twice or just gives an error.
numbersEntered = []
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit Game")
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
for x in range(lengthNumbers):
data=int(input())
numbersEntered.append(data)
if (data == -1000):
break
while numbersEntered[-1] != -1000:
menu()
Options=str(input(f"Please select either option A,B,or C:")).upper()
if Options == 'A':
print("The smallest number is:", min(numbersEntered))
elif Options == 'B':
print("The largest number is:", max(numbersEntered) )
# check for 'C' input from user to break out of the while loop
elif Options == 'C':
break
print('Quit Game')
A:
See comments in line.
import sys # will be used to exit the game.
numbersEntered = [] # Accumulate the numbers provided by the user
# Since I see you are familiar with functions, use a function to end
def quit_game():
print('Quit Game')
sys.exit()
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit Game")
# Get the starting number of number to process.
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
while True:
for x in range(lengthNumbers):
data = int(input())
numbersEntered.append(data)
if data == -1000:
quit_game()
# Once all numbers are entered provide the user a choice:
# display the smallest or largest of the numbers or exit.
menu()
Options = str(input(f"Please select either option A,B,or C:")).upper()
if Options == 'A':
print("The smallest number is:", min(numbersEntered))
elif Options == 'B':
print("The largest number is:", max(numbersEntered))
# check for 'C' input from user to break out of the while loop
elif Options == 'C':
quit_game()
# Allow the user to process another set.
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
# print('Quit Game') Moved to the function
| How do I make add the input parts into the loop like the menu? | The part of the code that ask for the length of the list and then the actual numbers the users want to use needs to be looped into the program like the menu is looped in. So that once it runs and the program is fulfilled it can loop again. However, the program needs to completely end once the number -1000 is entered or option C from the menu is entered. When I try I keep getting errors. Can someone help, please?
I tried to move that statement into the loop, I tried to call it in the while loop, but when I do that it either prints the statement twice or just gives an error.
numbersEntered = []
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit Game")
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
for x in range(lengthNumbers):
data=int(input())
numbersEntered.append(data)
if (data == -1000):
break
while numbersEntered[-1] != -1000:
menu()
Options=str(input(f"Please select either option A,B,or C:")).upper()
if Options == 'A':
print("The smallest number is:", min(numbersEntered))
elif Options == 'B':
print("The largest number is:", max(numbersEntered) )
# check for 'C' input from user to break out of the while loop
elif Options == 'C':
break
print('Quit Game')
| [
"See comments in line.\nimport sys # will be used to exit the game.\n\nnumbersEntered = [] # Accumulate the numbers provided by the user\n\n\n# Since I see you are familiar with functions, use a function to end\n\ndef quit_game():\n print('Quit Game')\n sys.exit()\n\n\ndef menu():\n print(\"[A] Smallest\")\n print(\"[B] Largest\")\n print(\"[C] Quit Game\")\n\n# Get the starting number of number to process.\nlengthNumbers = int(input(\"Please enter the length of your list/array:\"))\nprint(\"Please enter your numbers individually:\")\n\nwhile True:\n for x in range(lengthNumbers):\n data = int(input())\n numbersEntered.append(data)\n if data == -1000:\n quit_game()\n # Once all numbers are entered provide the user a choice:\n # display the smallest or largest of the numbers or exit.\n menu()\n Options = str(input(f\"Please select either option A,B,or C:\")).upper()\n if Options == 'A':\n print(\"The smallest number is:\", min(numbersEntered))\n elif Options == 'B':\n print(\"The largest number is:\", max(numbersEntered))\n # check for 'C' input from user to break out of the while loop\n elif Options == 'C':\n quit_game()\n # Allow the user to process another set.\n lengthNumbers = int(input(\"Please enter the length of your list/array:\"))\n print(\"Please enter your numbers individually:\")\n# print('Quit Game') Moved to the function\n\n"
] | [
0
] | [] | [] | [
"arrays",
"nested_loops",
"python",
"while_loop"
] | stackoverflow_0074671052_arrays_nested_loops_python_while_loop.txt |
Q:
Does Postgres provide an XA compliant resource manager?
I would like to know if it is possible to use Postgres as a database backend with transaction monitors like Oracle Tuxedo or Microfocus Enterprise server on Linux.
This can be possible if postgres provides an XA compilant ressource manager...
I have searched on postgres website but couldn't find any relevant information about such support.
Thanks in advance.
A:
psqlODBC provides an XA resource manager.
A:
Enduro/X Middleware (almost clone to Tuxedo) ships with PostgreSQL XA driver for libpq and ecpg apis. Sample usage can be seen under https://github.com/endurox-dev/endurox/tree/master/atmitest/test067_postgres
| Does Postgres provide an XA compliant resource manager? | I would like to know if it is possible to use Postgres as a database backend with transaction monitors like Oracle Tuxedo or Microfocus Enterprise server on Linux.
This can be possible if postgres provides an XA compilant ressource manager...
I have searched on postgres website but couldn't find any relevant information about such support.
Thanks in advance.
| [
"psqlODBC provides an XA resource manager.\n",
"Enduro/X Middleware (almost clone to Tuxedo) ships with PostgreSQL XA driver for libpq and ecpg apis. Sample usage can be seen under https://github.com/endurox-dev/endurox/tree/master/atmitest/test067_postgres\n"
] | [
2,
0
] | [] | [] | [
"microfocus",
"postgresql",
"tuxedo",
"xa"
] | stackoverflow_0045361228_microfocus_postgresql_tuxedo_xa.txt |
Q:
How to use Typescript Compiler API to resolve type references?
Suppose I have the following interfaces:
interface Person {
name: string;
}
interface Attendee {
person: Person;
id: number;
}
I have already figured out how to use the compiler API to extract string representations of every property's type, e.g.:
{
Attendee: {
person: "Person",
id: "number"
}
}
Here's how I do it: https://github.com/jlkiri/tsx-ray/blob/master/src/index.ts.
It's a combination of typeToString and getTypeOfSymbolAtLocation of the Type Checker.
However I would like to resolve types likes Person to their definition so that I get:
{
Attendee: {
person: {
name: "string";
},
id: "number"
}
}
Is there API I can use to easily do this, or do I have to implement the logic myself?
A:
Check ts-morph. I recently discovered it and it looks promising.
Here is a minimal code that can do what you want:
import {ClassDeclaration, Project} from 'ts-morph';
const project = new Project({);
project.addSourceFilesAtPaths("src/**/*.ts");
const allSourceFiles = project.getSourceFiles();
allSourceFiles.forEach(sourceFile => {
const classes = sourceFile.getClasses();
classes.forEach(cls => {
console.log(`class ${cls.getName()} {`);
const properties = cls.getProperties();
properties.forEach(prop => {
const type = prop.getType();
if(type.isClassOrInterface()) {
const typeSymbol = type.getSymbol();
console.log(` ${prop.getName()} :
${typeSymbol?.getName()} {`);
const clsDeclaration = typeSymbol?.getDeclarations()[0] as ClassDeclaration;
const members = clsDeclaration.getMembers();
members.forEach(m => {
console.log(` ${m.getText()}`);
});
console.log(` }`);
} else {
console.log(` ${prop.getName()} : ${type.getText()}`);
}
});
console.log(`}`);
});
})
For the following two files:
// ./src/property.ts
class Category {
description: string;
id: number;
}
export default Category;
// ./src/product.ts
import Category from './category';
class Product {
name: string;
price: number;
category: Category;
}
export default Product;
you will get the following printout:
class Category {
description : string
id : number
}
class Product {
name : string
price : number
category : Category {
description: string;
id: number;
}
}
| How to use Typescript Compiler API to resolve type references? | Suppose I have the following interfaces:
interface Person {
name: string;
}
interface Attendee {
person: Person;
id: number;
}
I have already figured out how to use the compiler API to extract string representations of every property's type, e.g.:
{
Attendee: {
person: "Person",
id: "number"
}
}
Here's how I do it: https://github.com/jlkiri/tsx-ray/blob/master/src/index.ts.
It's a combination of typeToString and getTypeOfSymbolAtLocation of the Type Checker.
However I would like to resolve types likes Person to their definition so that I get:
{
Attendee: {
person: {
name: "string";
},
id: "number"
}
}
Is there API I can use to easily do this, or do I have to implement the logic myself?
| [
"Check ts-morph. I recently discovered it and it looks promising.\nHere is a minimal code that can do what you want:\nimport {ClassDeclaration, Project} from 'ts-morph';\n\nconst project = new Project({);\nproject.addSourceFilesAtPaths(\"src/**/*.ts\");\nconst allSourceFiles = project.getSourceFiles();\n\nallSourceFiles.forEach(sourceFile => {\n const classes = sourceFile.getClasses();\n classes.forEach(cls => {\n console.log(`class ${cls.getName()} {`);\n const properties = cls.getProperties();\n properties.forEach(prop => {\n const type = prop.getType();\n if(type.isClassOrInterface()) {\n const typeSymbol = type.getSymbol();\n console.log(` ${prop.getName()} : \n ${typeSymbol?.getName()} {`);\n const clsDeclaration = typeSymbol?.getDeclarations()[0] as ClassDeclaration;\n const members = clsDeclaration.getMembers();\n members.forEach(m => {\n console.log(` ${m.getText()}`);\n });\n console.log(` }`);\n } else {\n console.log(` ${prop.getName()} : ${type.getText()}`);\n }\n });\n console.log(`}`);\n });\n})\n\nFor the following two files:\n// ./src/property.ts\nclass Category {\n description: string;\n id: number;\n}\nexport default Category;\n\n// ./src/product.ts\nimport Category from './category';\nclass Product {\n name: string;\n price: number;\n category: Category;\n}\nexport default Product;\n\nyou will get the following printout:\nclass Category {\n description : string\n id : number\n}\nclass Product {\n name : string\n price : number\n category : Category {\n description: string;\n id: number;\n }\n}\n\n"
] | [
0
] | [] | [] | [
"javascript",
"typescript",
"typescript_compiler_api"
] | stackoverflow_0060912124_javascript_typescript_typescript_compiler_api.txt |
Q:
Dealing with duplicated rows labeled to different classes in a multi label multiclass problem
Say im working on a multiclass classification problem, I have rows of emails and I want to build a classifier that classifies into different classes i.e. [personal emails, work emails, spam, bills]. What happens if i have rows that are duplicates but they have different labels? (i.e. row 1 and 4). My first reflex would be to remove those records, but what if my dataset contains a lot of those duplicated rows? Is there a better way to deal with this?
id
number of images?
number of words
Label
1
4
3
Spam
2
8
5
Personal
3
2
9
work
4
4
3
Bills
5
5
9
Personal
I initially removed those rows, but then my model does not perform as well on testing data, because that removed too many rows.
A:
It sounds like you're running into a common issue with machine learning where the distribution of your training data is not representative of the distribution of the data you want your model to make predictions on. In this case, it seems like you have duplicated rows with different labels in your training data, but not in your testing data. This can cause your model to perform poorly on the testing data.
One possible solution to this problem is to try to balance your training data by undersampling the majority classes or oversampling the minority classes. This will help ensure that your training data has a more balanced distribution of labels, which may improve the performance of your model on the testing data.
Another possible solution is to use a different evaluation metric that is less sensitive to class imbalance. For example, instead of using accuracy as your evaluation metric, you could use precision, recall, or F1 score, which take into account the number of true positives, true negatives, false positives, and false negatives. This can help you better evaluate the performance of your model on imbalanced data.
Ultimately, the best approach will depend on the specific details of your problem and the goals of your model. It's always a good idea to try multiple approaches and see which one works best for your particular problem.
| Dealing with duplicated rows labeled to different classes in a multi label multiclass problem | Say im working on a multiclass classification problem, I have rows of emails and I want to build a classifier that classifies into different classes i.e. [personal emails, work emails, spam, bills]. What happens if i have rows that are duplicates but they have different labels? (i.e. row 1 and 4). My first reflex would be to remove those records, but what if my dataset contains a lot of those duplicated rows? Is there a better way to deal with this?
id
number of images?
number of words
Label
1
4
3
Spam
2
8
5
Personal
3
2
9
work
4
4
3
Bills
5
5
9
Personal
I initially removed those rows, but then my model does not perform as well on testing data, because that removed too many rows.
| [
"It sounds like you're running into a common issue with machine learning where the distribution of your training data is not representative of the distribution of the data you want your model to make predictions on. In this case, it seems like you have duplicated rows with different labels in your training data, but not in your testing data. This can cause your model to perform poorly on the testing data.\nOne possible solution to this problem is to try to balance your training data by undersampling the majority classes or oversampling the minority classes. This will help ensure that your training data has a more balanced distribution of labels, which may improve the performance of your model on the testing data.\nAnother possible solution is to use a different evaluation metric that is less sensitive to class imbalance. For example, instead of using accuracy as your evaluation metric, you could use precision, recall, or F1 score, which take into account the number of true positives, true negatives, false positives, and false negatives. This can help you better evaluate the performance of your model on imbalanced data.\nUltimately, the best approach will depend on the specific details of your problem and the goals of your model. It's always a good idea to try multiple approaches and see which one works best for your particular problem.\n"
] | [
0
] | [] | [] | [
"classification",
"machine_learning",
"multiclass_classification",
"multilabel_classification",
"theory"
] | stackoverflow_0074669386_classification_machine_learning_multiclass_classification_multilabel_classification_theory.txt |
Q:
How can I receive data that someone is sending me through a HTTP GET request (data encoded in the path or query string parameters)
I will be receiving data shared via "a HTTP (or HTTPS) GET request" every five minutes, so I am developing a flask server to 'listen' for this data. I understand from trawling google that this is an uncommon way to share data, and I haven't been able to find documentation on how to ingest this data. Any nudges would be very much appreciated.
For example, I am asking person to point the webhook data at https://example.com/webhook.
Here is an example of the string I am expecting to receive:
'https://example.com/webhook?Date_Event=2013-12-31T15:21:32Z&DeviceID=Item1&Variable=11.1'
As I will be receiving this every five minutes, I deploy a flask server associated with that url. I'm confused as to how to accept this string and assign it to my 'receivedstring' variable so that I can process. Thank you!
from flask import Flask, request, abort # For deploying the web server
app = Flask(__name__) # Step 1 - Initiate flask app
@app.route('/webhook', methods=['GET'])
def webhook():
if request.method == 'GET':
receivedstring = #response?
...
A:
Here is one way to accept the string and assign it to the receivedstring variable in your Flask server:
from flask import Flask, request, abort
app = Flask(__name__)
@app.route('/webhook', methods=['GET'])
def webhook():
if request.method == 'GET':
receivedstring = request.args.get('Date_Event')
# You can now process the received string as needed.
# For example, you can print it to the console:
print(receivedstring)
# You can also access the other query parameters in the same way:
device_id = request.args.get('DeviceID')
variable = request.args.get('Variable')
print(device_id, variable)
# Return a response to the client if needed
return "OK"
if __name__ == '__main__':
app.run()
In this code, the request.args.get() method is used to retrieve the query parameters from the request URL. This method takes the name of the query parameter (e.g. "Date_Event") as its argument and returns the corresponding value (e.g. "2013-12-31T15:21:32Z").
If you want to retrieve all query parameters at once, you can use the request.args property, which is a dictionary-like object containing all the query parameters and their values. For example:
@app.route('/webhook', methods=['GET'])
def webhook():
if request.method == 'GET':
# Get all query parameters as a dictionary
query_params = request.args
# You can now process the query parameters as needed
# For example, you can print them to the console:
print(query_params)
# Return a response to the client if needed
return "OK"
I hope this helps! Let me know if you have any other questions.
| How can I receive data that someone is sending me through a HTTP GET request (data encoded in the path or query string parameters) | I will be receiving data shared via "a HTTP (or HTTPS) GET request" every five minutes, so I am developing a flask server to 'listen' for this data. I understand from trawling google that this is an uncommon way to share data, and I haven't been able to find documentation on how to ingest this data. Any nudges would be very much appreciated.
For example, I am asking person to point the webhook data at https://example.com/webhook.
Here is an example of the string I am expecting to receive:
'https://example.com/webhook?Date_Event=2013-12-31T15:21:32Z&DeviceID=Item1&Variable=11.1'
As I will be receiving this every five minutes, I deploy a flask server associated with that url. I'm confused as to how to accept this string and assign it to my 'receivedstring' variable so that I can process. Thank you!
from flask import Flask, request, abort # For deploying the web server
app = Flask(__name__) # Step 1 - Initiate flask app
@app.route('/webhook', methods=['GET'])
def webhook():
if request.method == 'GET':
receivedstring = #response?
...
| [
"Here is one way to accept the string and assign it to the receivedstring variable in your Flask server:\nfrom flask import Flask, request, abort\n\napp = Flask(__name__)\n\[email protected]('/webhook', methods=['GET'])\ndef webhook():\n if request.method == 'GET':\n receivedstring = request.args.get('Date_Event')\n # You can now process the received string as needed.\n # For example, you can print it to the console:\n print(receivedstring)\n # You can also access the other query parameters in the same way:\n device_id = request.args.get('DeviceID')\n variable = request.args.get('Variable')\n print(device_id, variable)\n # Return a response to the client if needed\n return \"OK\"\n\nif __name__ == '__main__':\n app.run()\n\nIn this code, the request.args.get() method is used to retrieve the query parameters from the request URL. This method takes the name of the query parameter (e.g. \"Date_Event\") as its argument and returns the corresponding value (e.g. \"2013-12-31T15:21:32Z\").\nIf you want to retrieve all query parameters at once, you can use the request.args property, which is a dictionary-like object containing all the query parameters and their values. For example:\[email protected]('/webhook', methods=['GET'])\ndef webhook():\n if request.method == 'GET':\n # Get all query parameters as a dictionary\n query_params = request.args\n # You can now process the query parameters as needed\n # For example, you can print them to the console:\n print(query_params)\n # Return a response to the client if needed\n return \"OK\"\n\nI hope this helps! Let me know if you have any other questions.\n"
] | [
1
] | [] | [] | [
"flask",
"python",
"python_requests"
] | stackoverflow_0074671667_flask_python_python_requests.txt |
Q:
How to write a LINQ to dataGridView in C# Windows Forms
I've got stuck with developing a LINQ search in dataGridView. On the form I dragged button, bindingSource dataGridView and comboBox. When I started programming button I've catched the unlogical action from C#. When I write else if block then button doesn't work, if I write else block, it works. How is it possible
Seacrhing criterias:
-The most expensive item in the list
-The cheapest item in the list
Item which presents in collection
I've connected bindingSource to the dataGridView object
Here is a code:
public partial class Form1: Form
{
public List<ProductClass> Product {get; set;}
public Form1()
{
InitializeComponent();
Product = new List<ProductClass>
{
new Product("BigMac", 300.0, 4000, "In collection"),
//....... there is 19 more objects
};
productBindingSource.DataSource = Product;
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString() == "The cheapest item")
{
var query = Product.OrderBy(x=>x.Price);
var minimum = query.First(); // Taking the first element from the list
productBindingSource.DataSource = minimum;
}
// This else if block is ignored, instead of it works block else
else if(comboBox1.SelectedItem.ToString() == "The most expensive item)
{
var query = Product.OrderBy(x=>x.Price);
var maximum = query.Last(); // taking the last element from the list
productBindingSource.DataSource = maximum;
}
// This block works when I choose from comboBox or Item in Collection or The most expensive item criteria
else
{
var query = from pr in Product where pr.CollectionStatus == "In collection" select pr;
productBindingSource.DataSource = query;
}
}
I can't find out what is wrong here :(
Also when I wrote something like that:
else
{
if(//....)
{
//....
}
else
{
//....
}
}
It crashes me all so the LINQ doesnt work completely :(
Any help with the code template is appreciated. Thanks in advance
A:
One big issue is that you query the DataSource and then set the very same DataSource to the result of the query productBindingSource.DataSource = minimum. The first query has 20 items (you say) but then what? The query returns the minimum (or the maximum) product and then the DataSource has only that one product to choose from next time instead of 20.
Your plan is OK to have the DataGridView display the query result...
public partial class MainForm : Form
{
public MainForm() => InitializeComponent();
enum QueryType{All, Min, Max, }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
dataGridView.DataSource = DataSource;
dataGridView.AllowUserToAddRows = false;
// Format columns
DataSource.Add(new Product("Template"));
dataGridView.Columns[nameof(Product.Description)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
var priceColStyle = dataGridView.Columns[nameof(Product.Price)].DefaultCellStyle;
priceColStyle.Format = "F2";
priceColStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
priceColStyle.Padding = new Padding(0, 0, 10, 0);
DataSource.Clear();
comboBox.Items.AddRange(Enum.GetNames(typeof(QueryType)));
comboBox.SelectedIndexChanged += onCBSelectedIndexChanged;
comboBox.SelectedIndex = 0;
}
}
BindingList<Product> DataSource { get; } = new BindingList<Product>();
BUT when you perform a query, it needs to be on some other collection of products and not the circular reference to the DataSource itself.
private void onCBSelectedIndexChanged(object sender, EventArgs e)
{
DataSource.Clear();
switch (Enum.Parse(typeof(QueryType), comboBox.Text))
{
case QueryType.All:
foreach (var product in ProductDatabase) DataSource.Add(product);
break;
case QueryType.Min:
DataSource.Add(ProductDatabase.OrderBy(_=>_.Price).First());
break;
case QueryType.Max:
DataSource.Clear();
DataSource.Add(ProductDatabase.OrderByDescending(_ => _.Price).First());
break;
default:
break;
}
dataGridView.ClearSelection();
}
WHERE ProductDatabase is a collection of products similar to the mock database created here:
public Product[] ProductDatabase { get; } = new Product[]
{
new Product ("Sponge"),
new Product ("Kite"),
new Product ("Card"),
new Product ("Hat"),
new Product ("Potato"),
new Product ("Shoes"),
new Product ("Cactus"),
new Product ("Whistle"),
new Product ("Paper"),
new Product ("Glass"),
new Product ("Crayon"),
new Product ("Feather"),
new Product ("Vegetables"),
new Product ("Rake"),
new Product ("Rice"),
new Product ("Bucket"),
new Product ("Yarn "),
new Product ("Salt"),
new Product ("Flowers"),
new Product ("Flour"),
};
And WHERE:
public class Product
{
static Random _rando = new Random(1);
public Product(string description) => Description = description;
public string Description { get; }
public decimal Price { get; } = (decimal)_rando.NextDouble() * 10;
}
Summary, if you stop overwriting your original "database" with the query result, then subsequent queries should have no issues running.
| How to write a LINQ to dataGridView in C# Windows Forms | I've got stuck with developing a LINQ search in dataGridView. On the form I dragged button, bindingSource dataGridView and comboBox. When I started programming button I've catched the unlogical action from C#. When I write else if block then button doesn't work, if I write else block, it works. How is it possible
Seacrhing criterias:
-The most expensive item in the list
-The cheapest item in the list
Item which presents in collection
I've connected bindingSource to the dataGridView object
Here is a code:
public partial class Form1: Form
{
public List<ProductClass> Product {get; set;}
public Form1()
{
InitializeComponent();
Product = new List<ProductClass>
{
new Product("BigMac", 300.0, 4000, "In collection"),
//....... there is 19 more objects
};
productBindingSource.DataSource = Product;
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
if(comboBox1.SelectedItem.ToString() == "The cheapest item")
{
var query = Product.OrderBy(x=>x.Price);
var minimum = query.First(); // Taking the first element from the list
productBindingSource.DataSource = minimum;
}
// This else if block is ignored, instead of it works block else
else if(comboBox1.SelectedItem.ToString() == "The most expensive item)
{
var query = Product.OrderBy(x=>x.Price);
var maximum = query.Last(); // taking the last element from the list
productBindingSource.DataSource = maximum;
}
// This block works when I choose from comboBox or Item in Collection or The most expensive item criteria
else
{
var query = from pr in Product where pr.CollectionStatus == "In collection" select pr;
productBindingSource.DataSource = query;
}
}
I can't find out what is wrong here :(
Also when I wrote something like that:
else
{
if(//....)
{
//....
}
else
{
//....
}
}
It crashes me all so the LINQ doesnt work completely :(
Any help with the code template is appreciated. Thanks in advance
| [
"One big issue is that you query the DataSource and then set the very same DataSource to the result of the query productBindingSource.DataSource = minimum. The first query has 20 items (you say) but then what? The query returns the minimum (or the maximum) product and then the DataSource has only that one product to choose from next time instead of 20.\nYour plan is OK to have the DataGridView display the query result...\npublic partial class MainForm : Form\n{\n public MainForm() => InitializeComponent();\n enum QueryType{All, Min, Max, }\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n dataGridView.DataSource = DataSource;\n dataGridView.AllowUserToAddRows = false;\n\n // Format columns\n DataSource.Add(new Product(\"Template\"));\n dataGridView.Columns[nameof(Product.Description)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;\n var priceColStyle = dataGridView.Columns[nameof(Product.Price)].DefaultCellStyle;\n priceColStyle.Format = \"F2\";\n priceColStyle.Alignment = DataGridViewContentAlignment.MiddleRight;\n priceColStyle.Padding = new Padding(0, 0, 10, 0);\n DataSource.Clear();\n\n comboBox.Items.AddRange(Enum.GetNames(typeof(QueryType)));\n comboBox.SelectedIndexChanged += onCBSelectedIndexChanged;\n comboBox.SelectedIndex = 0;\n }\n}\nBindingList<Product> DataSource { get; } = new BindingList<Product>();\n\nBUT when you perform a query, it needs to be on some other collection of products and not the circular reference to the DataSource itself.\nprivate void onCBSelectedIndexChanged(object sender, EventArgs e)\n{\n DataSource.Clear();\n switch (Enum.Parse(typeof(QueryType), comboBox.Text))\n {\n case QueryType.All:\n foreach (var product in ProductDatabase) DataSource.Add(product);\n break;\n case QueryType.Min:\n DataSource.Add(ProductDatabase.OrderBy(_=>_.Price).First());\n break;\n case QueryType.Max:\n DataSource.Clear();\n DataSource.Add(ProductDatabase.OrderByDescending(_ => _.Price).First());\n break;\n default:\n break;\n }\n dataGridView.ClearSelection();\n}\n\nWHERE ProductDatabase is a collection of products similar to the mock database created here:\npublic Product[] ProductDatabase { get; } = new Product[]\n{\n new Product (\"Sponge\"),\n new Product (\"Kite\"),\n new Product (\"Card\"),\n new Product (\"Hat\"),\n new Product (\"Potato\"),\n new Product (\"Shoes\"),\n new Product (\"Cactus\"),\n new Product (\"Whistle\"),\n new Product (\"Paper\"),\n new Product (\"Glass\"),\n new Product (\"Crayon\"),\n new Product (\"Feather\"),\n new Product (\"Vegetables\"),\n new Product (\"Rake\"),\n new Product (\"Rice\"),\n new Product (\"Bucket\"),\n new Product (\"Yarn \"),\n new Product (\"Salt\"),\n new Product (\"Flowers\"),\n new Product (\"Flour\"),\n};\n\nAnd WHERE:\npublic class Product\n{\n static Random _rando = new Random(1);\n public Product(string description) => Description = description;\n public string Description { get; }\n public decimal Price { get; } = (decimal)_rando.NextDouble() * 10;\n}\n\nSummary, if you stop overwriting your original \"database\" with the query result, then subsequent queries should have no issues running.\n\n"
] | [
0
] | [] | [] | [
"c#",
"datagridview",
"linq",
"winforms"
] | stackoverflow_0074670051_c#_datagridview_linq_winforms.txt |
Q:
HTML5 rich-text inside textarea
I heard that the new HTML5 will add rich text capability to textareas (it will make them more flexible), so you can do stuff like code syntax highlighting editors without very nasty javascript (like creating iframes and stuff).
Is this true? Are there browsers with support for it yet? And where can I find some API?
A:
Whitout jQuery
If what you are looking for are NO-jquery tools (pure HTML/CSS + basic JS) as us, then some of the best options found (in 2016) are:
wysihtml5
Squire
ckeditor
widgEditor
Nevertheless, those in the list above all convert the element (textarea) into an iframe, so they weren't exactly what we were searching for, finally we found this one which respects the original element (divs or so, but if you use textarea it does creates an additional div), allowing full straightforward JS WebApp development:
nicedit
We hope this helps you too!
A:
Are you looking for Aloha Editor?
It's using the new contenteditable attribute to add a WYSIWYG editor to any div you choose.
Look at the demos.
A:
I believe what you are referring to is the new contentEditable attribute. This is not a textarea, but rather an element attribute. This is good for allowing changes to content.
Try http://html5demos.com/contenteditable
Notice that your browser likely doesn't give you the toolbar with bold, italics, etc. Yet chrome will let you select text and use CTR-B, CTR-I, etc. Things are still being ironed out with this.
Basically, it's a work in progress and your best bet for browser compatability is using a wysiwyg editer like tinymce et al.
A:
Where have you heard that?
Looking at W3Schools > HTML5 > textarea I can't see anything that hints this is true.
Edit: added more links due to comments of people who dislike w3schools
Even tho it's essentially the same thing at this point, here's the link to w3.org for wiki textarea, as well as the spec for textarea. Also, here's the document with differences of html 4 and 5 as of march 29, 2012
A:
10 years 3 months ago the question was asked:HTML5 rich-text inside textarea.
I hope this link is along that line of possible solution.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content
Has a nice a nice example of a RT Editor using editable content.
There are some warnings.. and issues noted at the top of the page.
It is a good example still.
The example runs in: Chrome Version 104.0.5112.102 (Official Build) (64-bit).
A:
You can use Quill instead of TextArea: https://quilljs.com/docs/quickstart/
<!-- Include stylesheet -->
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<!-- Create the editor container -->
<div id="editor">
<p>Hello World!</p>
<p>Some initial <strong>bold</strong> text</p>
<p><br></p>
</div>
<!-- Include the Quill library -->
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<!-- Initialize Quill editor -->
<script>
var quill = new Quill('#editor', {
theme: 'snow'
});
</script>
| HTML5 rich-text inside textarea | I heard that the new HTML5 will add rich text capability to textareas (it will make them more flexible), so you can do stuff like code syntax highlighting editors without very nasty javascript (like creating iframes and stuff).
Is this true? Are there browsers with support for it yet? And where can I find some API?
| [
"Whitout jQuery\nIf what you are looking for are NO-jquery tools (pure HTML/CSS + basic JS) as us, then some of the best options found (in 2016) are:\n\nwysihtml5\nSquire\nckeditor\nwidgEditor\n\nNevertheless, those in the list above all convert the element (textarea) into an iframe, so they weren't exactly what we were searching for, finally we found this one which respects the original element (divs or so, but if you use textarea it does creates an additional div), allowing full straightforward JS WebApp development:\n\nnicedit\n\nWe hope this helps you too!\n",
"Are you looking for Aloha Editor?\nIt's using the new contenteditable attribute to add a WYSIWYG editor to any div you choose.\nLook at the demos.\n",
"I believe what you are referring to is the new contentEditable attribute. This is not a textarea, but rather an element attribute. This is good for allowing changes to content.\nTry http://html5demos.com/contenteditable\nNotice that your browser likely doesn't give you the toolbar with bold, italics, etc. Yet chrome will let you select text and use CTR-B, CTR-I, etc. Things are still being ironed out with this.\nBasically, it's a work in progress and your best bet for browser compatability is using a wysiwyg editer like tinymce et al.\n",
"Where have you heard that? \nLooking at W3Schools > HTML5 > textarea I can't see anything that hints this is true.\nEdit: added more links due to comments of people who dislike w3schools\nEven tho it's essentially the same thing at this point, here's the link to w3.org for wiki textarea, as well as the spec for textarea. Also, here's the document with differences of html 4 and 5 as of march 29, 2012\n",
"10 years 3 months ago the question was asked:HTML5 rich-text inside textarea.\nI hope this link is along that line of possible solution.\nhttps://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content\nHas a nice a nice example of a RT Editor using editable content.\nThere are some warnings.. and issues noted at the top of the page.\nIt is a good example still.\nThe example runs in: Chrome Version 104.0.5112.102 (Official Build) (64-bit).\n",
"You can use Quill instead of TextArea: https://quilljs.com/docs/quickstart/\n<!-- Include stylesheet -->\n<link href=\"https://cdn.quilljs.com/1.3.6/quill.snow.css\" rel=\"stylesheet\">\n\n<!-- Create the editor container -->\n<div id=\"editor\">\n <p>Hello World!</p>\n <p>Some initial <strong>bold</strong> text</p>\n <p><br></p>\n</div>\n\n<!-- Include the Quill library -->\n<script src=\"https://cdn.quilljs.com/1.3.6/quill.js\"></script>\n\n<!-- Initialize Quill editor -->\n<script>\n var quill = new Quill('#editor', {\n theme: 'snow'\n });\n</script>\n\n"
] | [
12,
7,
4,
3,
1,
0
] | [] | [] | [
"html",
"javascript",
"rich_text_editor",
"syntax_highlighting",
"textarea"
] | stackoverflow_0010404312_html_javascript_rich_text_editor_syntax_highlighting_textarea.txt |
Q:
How to clear Navigation in Xamarin/MAUI?
I have the following app structure:
Main Page : Choose Login Type A or B
if the user choses login type A then navigate to > Page A1 Credentials for A type
if the user choses login type B then navigate to > Page B1 Credentials for B type
if Login is successfull for page A1 navigate to > Page A2
if Login is successfull for page B1 navigate to > Page B2
Page A1 --- Login Successful ---> Page A2
/
/
/
Page 1 \
\
\
Page B1 --- Login Successful ---> Page B2
If the user is in Page A1 or B1, I would like to allow him to go back to page 1 if he wants. However if the user logs in either using type 1 or 2 and reaches either A2 or B2, he shouldn't be allowed to go back.
Here is my code :
Before going to pages A2 or B2 I run. (This code executes in pages A1, B1) :
public static void RemoveAllPagesFromNavigation(INavigation Navigation)
{
var existingPages = Navigation.NavigationStack.ToList();
foreach (var page in existingPages)
{
if (page != null)
{
Navigation.RemovePage(page);
}
}
}
RemoveAllPagesFromNavigation(this.Navigation);
await Navigation.PushAsync(new PageA2()); // Or PageB2
But the function RemoveAllPagesFromNavigation raises an exception saying that the first element of the NavigationStack is null;
I added a condition to skip the case where the first page is null, the function runs but the end user is still able to go back to page Page 1.
Does anyone know how to prevent user from going back to the pages 1, A1 or B2 ?
Thanks.
A:
Because you don't want user to be able to go back, use
Navigation.GoToAsync
instead of
Navigation.PushAsync
EXPLANATION:
"AppShell navigation" only uses Navigation stack when it has to.
I suspect you'll find that foreach (var page in existingPages) does not list ANY non-null pages; there is nothing on the stack.
AppShell is remembering one "current" page elsewhere. (Internally? I'm not sure.) GoToAsync will make your new page the current page.
FYI ALTERNATIVE:
There is an alternative navigation paradigm, NavigationPage that lacks appshell features such as "Routes". Advantage is simple, direct, programmatic control over the navigation stack. (Without the subtleties that AppShell introduces. One of which you have encountered.)
Consider using NavigationPage during the login sequence, only going to AppShell once user is in your main content. (Or omit AppShell completely, just use NavigationPage for your app.)
To do so, in App.xaml.cs, replace:
MainPage = new AppShell();
with:
MainPage = new NavigationPage();.
Then use NavigationPage features to show first login page, etc. Don't use anything from that AppShell navigation doc I linked earlier.
If after login success, you want to use AppShell navigation, do:
Application.Current.MainPage = new AppShell();.
THIRD ALTERNATIVE:
Do Application.Current.MainPage = new MyNextFascinatingPage(); to step through the login sequence. Thus there is nowhere for user to go back to, during these steps. (If you want them to go back, you do so explicitly, by creating a new copy of earlier page.)
After login success, do:
Application.Current.MainPage = new AppShell();.
A:
When you successful navigate to Page A2 or Page B2, you will have 3 pages in the NavigationStack, so remove first 2 pages which is (Page 1 and (Page A1 or Page B1)) then the Page A2 or Page B2 will be the root page.
| How to clear Navigation in Xamarin/MAUI? | I have the following app structure:
Main Page : Choose Login Type A or B
if the user choses login type A then navigate to > Page A1 Credentials for A type
if the user choses login type B then navigate to > Page B1 Credentials for B type
if Login is successfull for page A1 navigate to > Page A2
if Login is successfull for page B1 navigate to > Page B2
Page A1 --- Login Successful ---> Page A2
/
/
/
Page 1 \
\
\
Page B1 --- Login Successful ---> Page B2
If the user is in Page A1 or B1, I would like to allow him to go back to page 1 if he wants. However if the user logs in either using type 1 or 2 and reaches either A2 or B2, he shouldn't be allowed to go back.
Here is my code :
Before going to pages A2 or B2 I run. (This code executes in pages A1, B1) :
public static void RemoveAllPagesFromNavigation(INavigation Navigation)
{
var existingPages = Navigation.NavigationStack.ToList();
foreach (var page in existingPages)
{
if (page != null)
{
Navigation.RemovePage(page);
}
}
}
RemoveAllPagesFromNavigation(this.Navigation);
await Navigation.PushAsync(new PageA2()); // Or PageB2
But the function RemoveAllPagesFromNavigation raises an exception saying that the first element of the NavigationStack is null;
I added a condition to skip the case where the first page is null, the function runs but the end user is still able to go back to page Page 1.
Does anyone know how to prevent user from going back to the pages 1, A1 or B2 ?
Thanks.
| [
"Because you don't want user to be able to go back, use\nNavigation.GoToAsync\ninstead of\nNavigation.PushAsync\nEXPLANATION:\n\"AppShell navigation\" only uses Navigation stack when it has to.\nI suspect you'll find that foreach (var page in existingPages) does not list ANY non-null pages; there is nothing on the stack.\nAppShell is remembering one \"current\" page elsewhere. (Internally? I'm not sure.) GoToAsync will make your new page the current page.\n\nFYI ALTERNATIVE:\nThere is an alternative navigation paradigm, NavigationPage that lacks appshell features such as \"Routes\". Advantage is simple, direct, programmatic control over the navigation stack. (Without the subtleties that AppShell introduces. One of which you have encountered.)\nConsider using NavigationPage during the login sequence, only going to AppShell once user is in your main content. (Or omit AppShell completely, just use NavigationPage for your app.)\nTo do so, in App.xaml.cs, replace:\nMainPage = new AppShell();\nwith:\nMainPage = new NavigationPage();.\nThen use NavigationPage features to show first login page, etc. Don't use anything from that AppShell navigation doc I linked earlier.\nIf after login success, you want to use AppShell navigation, do:\nApplication.Current.MainPage = new AppShell();.\n\nTHIRD ALTERNATIVE:\nDo Application.Current.MainPage = new MyNextFascinatingPage(); to step through the login sequence. Thus there is nowhere for user to go back to, during these steps. (If you want them to go back, you do so explicitly, by creating a new copy of earlier page.)\nAfter login success, do:\nApplication.Current.MainPage = new AppShell();.\n",
"When you successful navigate to Page A2 or Page B2, you will have 3 pages in the NavigationStack, so remove first 2 pages which is (Page 1 and (Page A1 or Page B1)) then the Page A2 or Page B2 will be the root page.\n"
] | [
1,
0
] | [
"you can use\npublic Main()\n {\n NavigationPage.SetHasNavigationBar(this, false);\n NavigationPage.SetHasBackButton(this, false);\n InitializeComponent();\n }\n\non the page that you want user not be able to back from.\n"
] | [
-1
] | [
"maui",
"xamarin"
] | stackoverflow_0073094429_maui_xamarin.txt |
Q:
Change the mouse cursor on mouse over to anchor-like style
If I hover the mouse over a div the mouse cursor will be changed to the cursor like that in HTML anchor.
How can I do this?
A:
Assuming your div has an id="myDiv", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):
CSS to Add
#myDiv
{
cursor: pointer;
}
You can simply add the cursor style to your div's HTML like this:
<div style="cursor: pointer">
</div>
EDIT:
If you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)
$('.myClass').css('cursor', 'pointer');
A:
If you want to do this in jQuery instead of CSS, you basically follow the same process.
Assuming you have some <div id="target"></div>, you can use the following code:
$("#target").hover(function() {
$(this).css('cursor','pointer');
}, function() {
$(this).css('cursor','auto');
});
and that should do it.
A:
You actually don't need jQuery, just CSS. For example, here's some HTML:
<div class="special"></div>
And here's the CSS:
.special
{
cursor: pointer;
}
A:
This will
#myDiv
{
cursor: pointer;
}
A:
I think :hover was missing in above answers. So following would do the needful.(if css was required)
#myDiv:hover
{
cursor: pointer;
}
A:
As of 2022, JQuery can be safely replaced with vanilla JS. Here's how you would change the style of the div. Let's assume that div has id="myDiv", then:
const myDivElem = document.querySelector("#myDiv");
myDiv.style.cursor = "pointer";
where the argument of querySelector can be any CSS selector.
| Change the mouse cursor on mouse over to anchor-like style | If I hover the mouse over a div the mouse cursor will be changed to the cursor like that in HTML anchor.
How can I do this?
| [
"Assuming your div has an id=\"myDiv\", add the following to your CSS. The cursor: pointer specifies that the cursor should be the same hand icon that is use for anchors (hyperlinks):\nCSS to Add\n#myDiv\n{\n cursor: pointer;\n}\n\nYou can simply add the cursor style to your div's HTML like this:\n<div style=\"cursor: pointer\">\n\n</div>\n\nEDIT:\nIf you are determined to use jQuery for this, then add the following line to your $(document).ready() or body onload: (replace myClass with whatever class all of your divs share)\n$('.myClass').css('cursor', 'pointer');\n\n",
"If you want to do this in jQuery instead of CSS, you basically follow the same process.\nAssuming you have some <div id=\"target\"></div>, you can use the following code:\n$(\"#target\").hover(function() {\n $(this).css('cursor','pointer');\n}, function() {\n $(this).css('cursor','auto');\n});\n\nand that should do it.\n",
"You actually don't need jQuery, just CSS. For example, here's some HTML:\n<div class=\"special\"></div>\n\nAnd here's the CSS:\n.special\n{\n cursor: pointer;\n}\n\n",
"This will\n#myDiv\n{\n cursor: pointer;\n}\n\n",
"I think :hover was missing in above answers. So following would do the needful.(if css was required)\n#myDiv:hover\n{\n cursor: pointer;\n}\n\n",
"As of 2022, JQuery can be safely replaced with vanilla JS. Here's how you would change the style of the div. Let's assume that div has id=\"myDiv\", then:\nconst myDivElem = document.querySelector(\"#myDiv\");\nmyDiv.style.cursor = \"pointer\";\n\nwhere the argument of querySelector can be any CSS selector.\n"
] | [
246,
24,
11,
6,
1,
0
] | [] | [] | [
"javascript",
"mouse"
] | stackoverflow_0007185044_javascript_mouse.txt |
Q:
Adding an "Identify Original .csv" column in R-Markdown
I am trying to create a combined dataset from about 117 other csv files in R-Markdown. I managed to combine them into a single document using the following functions:
setwd() dataFiles <- lapply(Sys.glob("data*.csv", read.csv) dataFilesCombined <- data.table::rbindlist(datafiles)
However, I would like to add a column to the end "dataFilesCombined" that contains information about what original .csv file the data values came from. Does anyone have a suggestion for how I can do this?
I've tried looking for an answer elsewhere on the web, but I can't find anything that would function well with the Sys.glob method.
A:
I created a small reprex using five dataframes, but it should work with 117. Before you combine the dataframes in your list into one big dataframe, you need to assign each dataframe its own identifier that signals which .csv file it came from. The easiest way to do this is just use whatever the .csv file was called.
library(data.table)
# there's a folder called "reprex" in my Documents that contains
# five dataframes that look like this
testdata <- structure(list(x1 = 3:5, x2 = c(4L, 2L, 5L), x3 = c(1L, 1L, 2L)), class = "data.frame", row.names = c(NA, -3L))
testdata
#> x1 x2 x3
#> 1 3 4 1
#> 2 4 2 1
#> 3 5 5 2
# make path
path <- "~/Documents/reprex"
# get names of the dataframes, put into character vector
filelist <- list.files(path = path,
pattern =" *.csv",
full.names = TRUE)
# put all dataframes into a list
lst <- lapply(filelist,
utils::read.csv,
header = TRUE,
stringsAsFactors = FALSE)
# make a name for every dataframe, based on filelist
names(lst) <- filelist
namelist <- fs::path_file(filelist)
namelist <- unlist(lapply(namelist,
sub,
pattern = ".csv",
replacement = ""),
use.names = FALSE)
print(namelist)
#> [1] "data1" "data2" "data3" "data4" "data5"
# give every dataframe in the list an ID variable,
# which is actually the original name of the .csv file
lst <- mapply(cbind, lst, "listID" = namelist, SIMPLIFY = FALSE)
# combine
dataFilesCombined <- data.table::rbindlist(lst)
head(dataFilesCombined)
#> x1 x2 x3 listID
#> 1: 3 4 1 data1
#> 2: 4 2 1 data1
#> 3: 5 5 2 data1
#> 4: 3 4 1 data2
#> 5: 4 2 1 data2
#> 6: 5 5 2 data2
| Adding an "Identify Original .csv" column in R-Markdown | I am trying to create a combined dataset from about 117 other csv files in R-Markdown. I managed to combine them into a single document using the following functions:
setwd() dataFiles <- lapply(Sys.glob("data*.csv", read.csv) dataFilesCombined <- data.table::rbindlist(datafiles)
However, I would like to add a column to the end "dataFilesCombined" that contains information about what original .csv file the data values came from. Does anyone have a suggestion for how I can do this?
I've tried looking for an answer elsewhere on the web, but I can't find anything that would function well with the Sys.glob method.
| [
"I created a small reprex using five dataframes, but it should work with 117. Before you combine the dataframes in your list into one big dataframe, you need to assign each dataframe its own identifier that signals which .csv file it came from. The easiest way to do this is just use whatever the .csv file was called.\nlibrary(data.table)\n\n# there's a folder called \"reprex\" in my Documents that contains \n# five dataframes that look like this\ntestdata <- structure(list(x1 = 3:5, x2 = c(4L, 2L, 5L), x3 = c(1L, 1L, 2L)), class = \"data.frame\", row.names = c(NA, -3L))\ntestdata\n#> x1 x2 x3\n#> 1 3 4 1\n#> 2 4 2 1\n#> 3 5 5 2\n\n# make path\npath <- \"~/Documents/reprex\"\n\n# get names of the dataframes, put into character vector\nfilelist <- list.files(path = path,\n pattern =\" *.csv\",\n full.names = TRUE)\n\n# put all dataframes into a list\nlst <- lapply(filelist,\n utils::read.csv,\n header = TRUE,\n stringsAsFactors = FALSE)\n\n# make a name for every dataframe, based on filelist\nnames(lst) <- filelist\nnamelist <- fs::path_file(filelist)\nnamelist <- unlist(lapply(namelist,\n sub,\n pattern = \".csv\",\n replacement = \"\"),\n use.names = FALSE)\nprint(namelist)\n#> [1] \"data1\" \"data2\" \"data3\" \"data4\" \"data5\"\n\n# give every dataframe in the list an ID variable,\n# which is actually the original name of the .csv file\nlst <- mapply(cbind, lst, \"listID\" = namelist, SIMPLIFY = FALSE)\n\n# combine\ndataFilesCombined <- data.table::rbindlist(lst)\nhead(dataFilesCombined)\n#> x1 x2 x3 listID\n#> 1: 3 4 1 data1\n#> 2: 4 2 1 data1\n#> 3: 5 5 2 data1\n#> 4: 3 4 1 data2\n#> 5: 4 2 1 data2\n#> 6: 5 5 2 data2\n\n"
] | [
1
] | [] | [] | [
"r",
"r_markdown"
] | stackoverflow_0074671514_r_r_markdown.txt |
Q:
Project Folder already exists and is not empty- Error in netbeans
I'm using NetBeans 7.0.1 & when I try to create a JAVA APPLICATION, I get an error which is: "ProjectΒ FolderΒ alreadyΒ existsΒ andΒ isΒ notΒ empty" .
But the fact is that project folder doesn't exist, their is no folder of same name in the directory.
Any suggestions would be a great help.
Thanks in advance.
A:
Does the problem comes out when you try to create it, or what ?
Please not that your version is a bit old.
Make sure that it was always in the same directory as before .
I would restart my computer & try again.
If the situation persists I would upgrade to the latest version (7.2.1) and
check if the problem still persists or contact NetBeans.
A:
I my case (NetBeans 8.1 on Windows 7 x64) the reason was incorrect template file for main java class (C:\Users\_my_user_name_\AppData\Roaming\NetBeans\8.1\config\Templates\Classes\Main.java). You see, when tweaking with that file I left it filled with invalid code; a closing tag was missing, to be exact. As soon as I realized my mistake and corrected it, everything went back to normal and has been working perfectly ever since.
This is what I'd suggest:
Step 1: See if you can create a new project in a folder that doesn't exist yet. Suppose the IDE does make this new folder for you, starts filling it with files, then stops unexpectedly and says that 'Project folder already exists, etc'.
Step 2: Look inside the folder and try to locate the main class for your application (e.g., C:\My_Amazing_NetBeans_Projects\MyNiftyJavaApp\src\myniftyjavaapp\MyNiftyJavaApp.java)
Step 3: If the main class file does exist but is totally empty (0 bytes in length) it might mean that something prevents the IDE from filling it with automatically generated code (as happened to me because of the invalid main class template).
In short, try to locate exact point at which the IDE loses its head. As a last resort, consider reinstalling NetBeans. Admittedly, this solution is crude and inelegant but people all over the world report it usually helps...
A:
<#if package?? && package != "">
package ${package};
</#if>
/** @author ${user} */
public class ${name} {
public static void main(String[] args) {
}
}
It seems that the first three lines of code above are key to this problem. I changed my JAVA MAIN CLASS template and removed unwanted comments, but I also removed these first three lines of code. The first project created was ok, package was "default package".
When I tried to create the next project I got an error about a Project folder that already exists. I did uninstall/install NetBeans 8.2, changed template again in the same manner, and again second project fails to create.
Then I decided to change template line by line to see what is going on and guess what: the first three lines are necessary - new projects are created well and package is not default anymore!
A:
I changed my JAVA MAIN CLASS template and removed unwanted comments, but I also removed something important that i didn't noticed.
i uninstalled and reinstalled the NetBeans program and then i go to:
options/templates/java/java main class/
this is at the up rigth corner in net beans.
and then i selected the option that said "recover to default". then i just close and open the Netbeans again and whwen i tried to make a new project it worked.
basically you just need to recover to fefault the java main class that locates in templates options of java.
Im from mexico and my english is not so good but, I hope my answer can help some body.here is where you have to click
| Project Folder already exists and is not empty- Error in netbeans | I'm using NetBeans 7.0.1 & when I try to create a JAVA APPLICATION, I get an error which is: "ProjectΒ FolderΒ alreadyΒ existsΒ andΒ isΒ notΒ empty" .
But the fact is that project folder doesn't exist, their is no folder of same name in the directory.
Any suggestions would be a great help.
Thanks in advance.
| [
"Does the problem comes out when you try to create it, or what ?\nPlease not that your version is a bit old. \n\nMake sure that it was always in the same directory as before .\nI would restart my computer & try again.\nIf the situation persists I would upgrade to the latest version (7.2.1) and\ncheck if the problem still persists or contact NetBeans.\n\n",
"I my case (NetBeans 8.1 on Windows 7 x64) the reason was incorrect template file for main java class (C:\\Users\\_my_user_name_\\AppData\\Roaming\\NetBeans\\8.1\\config\\Templates\\Classes\\Main.java). You see, when tweaking with that file I left it filled with invalid code; a closing tag was missing, to be exact. As soon as I realized my mistake and corrected it, everything went back to normal and has been working perfectly ever since.\nThis is what I'd suggest:\nStep 1: See if you can create a new project in a folder that doesn't exist yet. Suppose the IDE does make this new folder for you, starts filling it with files, then stops unexpectedly and says that 'Project folder already exists, etc'.\nStep 2: Look inside the folder and try to locate the main class for your application (e.g., C:\\My_Amazing_NetBeans_Projects\\MyNiftyJavaApp\\src\\myniftyjavaapp\\MyNiftyJavaApp.java)\nStep 3: If the main class file does exist but is totally empty (0 bytes in length) it might mean that something prevents the IDE from filling it with automatically generated code (as happened to me because of the invalid main class template).\nIn short, try to locate exact point at which the IDE loses its head. As a last resort, consider reinstalling NetBeans. Admittedly, this solution is crude and inelegant but people all over the world report it usually helps...\n",
"<#if package?? && package != \"\"> \npackage ${package}; \n</#if> \n\n/** @author ${user} */\n\npublic class ${name} { \n\n public static void main(String[] args) { \n\n } \n}\n\nIt seems that the first three lines of code above are key to this problem. I changed my JAVA MAIN CLASS template and removed unwanted comments, but I also removed these first three lines of code. The first project created was ok, package was \"default package\". \nWhen I tried to create the next project I got an error about a Project folder that already exists. I did uninstall/install NetBeans 8.2, changed template again in the same manner, and again second project fails to create. \nThen I decided to change template line by line to see what is going on and guess what: the first three lines are necessary - new projects are created well and package is not default anymore!\n",
"I changed my JAVA MAIN CLASS template and removed unwanted comments, but I also removed something important that i didn't noticed.\ni uninstalled and reinstalled the NetBeans program and then i go to:\noptions/templates/java/java main class/\nthis is at the up rigth corner in net beans.\nand then i selected the option that said \"recover to default\". then i just close and open the Netbeans again and whwen i tried to make a new project it worked.\nbasically you just need to recover to fefault the java main class that locates in templates options of java.\nIm from mexico and my english is not so good but, I hope my answer can help some body.here is where you have to click\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"java",
"netbeans",
"netbeans_7"
] | stackoverflow_0014228973_java_netbeans_netbeans_7.txt |
Q:
how to make Parralel scroll in jetpack compose?
I am makeing a profile screen in jetpack compose
I want to make the Blue background behind the image scroll up when the image is scrolled up because it doesn't look good :)
This is what I need help with, see the gif to understand better.
how can I achieve what I want, that the blue background will scroll up also?
I tried moving the background box around the code,
out of the column at the head
out of the column at the TopBar
out of the column at the ProfileSection
but it didn't work because the column rearrange the objects so that they are ontop of each other and I just want it from behind
source code
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.politi_cal.R
@Composable
fun CelebProfileScreen() {
BlackBackgroundSquare()
Column(modifier = Modifier.fillMaxSize()) {
LazyColumn(content = {
item {
TopBar()
Spacer(modifier = Modifier.height(60.dp))
ProfileSection(
name = "Amit Segal",
company = "N12 news channel",
)
// voting bar
VotingBar(
leftyPercent = 10, rightyPercent = 90
)
// lazy column for more info
MoreInfo("Amit Segal is a journalist and a news anchor. He is the host of the N12 news channel. He is a very popular journalist. Amit Yitzchak Segal[1] (born Biz in Nisan 5, 1982, April 10, 1982) is an Israeli journalist, radio and television personality. Serves as the political commentator of the news company and a political columnist in the \"Yediot Aharonot\" newspaper. One of the most influential journalists in Israel[2]. Presents Meet the Press on Channel 12 together with Ben Caspit.")
}
})
}
}
@Composable
fun MoreInfo(information_param: String, modifier: Modifier = Modifier) {
Column(modifier = modifier.padding(start = 26.dp, end = 26.dp)) {
Text(
text = "More information",
color = Color.Black,
fontSize = 36.sp,
fontWeight = FontWeight.Bold
)
Text(
text = information_param,
color = Color.Black,
fontSize = 24.sp,
fontWeight = FontWeight.Normal,
maxLines = 10,
overflow = TextOverflow.Ellipsis
)
}
}
@Composable
fun VotingBar(
modifier: Modifier = Modifier, leftyPercent: Int, rightyPercent: Int
) {
var leftyPercentWeight: Float = (leftyPercent / 10).toFloat()
var rightyPercentWeight: Float = (rightyPercent / 10).toFloat()
val shape = RoundedCornerShape(32.dp)
Column(
Modifier.padding(start = 16.dp, end = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = modifier
.fillMaxWidth()
.height(32.dp)
.background(Color.White)
.clip(shape)
.border(1.dp, Color.Black, shape)
) {
Column(
// add rounded corners to the left side
modifier = Modifier
.background(Color(0xFFA60321))
.weight(rightyPercentWeight)
.clip(CircleShape)
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
}
Column(
modifier = Modifier
.background(Color(0xFF03588C))
.fillMaxHeight(leftyPercentWeight)
.weight(1f)
.clip(CircleShape),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
// add rounded corners to the right side
) {
}
}
// second row
// stack over flow https://stackoverflow.com/questions/74619069/what-is-the-attribute-of-the-moddifier-that-i-need-to-change-to-make-the-corners?noredirect=1#comment131712293_74619069
Column(
Modifier.padding(start = 46.dp, end = 46.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.background(Color.White),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Row {
Box(
modifier = Modifier
.size(30.dp)
.clip(CircleShape)
.background(Color(0xFFA60321))
)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = "Right $rightyPercent%",
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
Row() {
Box(
modifier = Modifier
.size(30.dp)
.clip(CircleShape)
.background(Color(0xFF03588C))
)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = "Left $leftyPercent%", fontSize = 20.sp, fontWeight = FontWeight.Bold
)
}
}
}
}
}
@Composable
fun BlackBackgroundSquare() {
Box(
// modifier fill only half the screen
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
// insert background color as hex
.background(Color(0xFF2C3E50))
)
}
@Composable
fun TopBar(
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = modifier.fillMaxWidth()
) {
Text(
text = "Profile",
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 40.sp,
color = Color.White
)
}
}
@Composable
fun ProfileSection(
name: String, company: String, modifier: Modifier = Modifier
) {
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
RoundImage(
image = painterResource(id = R.drawable.profile_pic), modifier = Modifier.size(250.dp)
)
Text(
text = name,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 40.sp,
color = Color.Black
)
Text(
text = company,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
color = Color.Black
)
}
}
@Composable
fun RoundImage(
image: Painter, modifier: Modifier = Modifier
) {
Image(
painter = image,
contentDescription = "Profile image",
modifier = modifier
.aspectRatio(1f, matchHeightConstraintsFirst = true)
.border(
width = 6.dp, color = Color.White, shape = CircleShape
)
.padding(3.dp)
.clip(CircleShape)
)
}
A:
Add a state to LazyColumn, then use state.firstVisibleItemIndex to detect when first item is not visible. Use a DisposableEffect to detect index by index to prevent lag. When first idx is consumed, hide your upper bar. Could use a viewmodel to save first index. Then show action bar if first item is visible again.
DisposableEffect(key1 = listState.firstVisibleItemIndex) {
onDispose {
viewModel
.setFirstVisibleItemIdx(listState.firstVisibleItemIndex)
}
}
On enter get the index from viewmodel and scroll. If no value, just show as normal.
LaunchedEffect(viewModel.firstVisibleItemIdx) {
listState.scrollToItem(viewModel.firstVisibleItemIdx.value ?: 0)
}
| how to make Parralel scroll in jetpack compose? | I am makeing a profile screen in jetpack compose
I want to make the Blue background behind the image scroll up when the image is scrolled up because it doesn't look good :)
This is what I need help with, see the gif to understand better.
how can I achieve what I want, that the blue background will scroll up also?
I tried moving the background box around the code,
out of the column at the head
out of the column at the TopBar
out of the column at the ProfileSection
but it didn't work because the column rearrange the objects so that they are ontop of each other and I just want it from behind
source code
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.politi_cal.R
@Composable
fun CelebProfileScreen() {
BlackBackgroundSquare()
Column(modifier = Modifier.fillMaxSize()) {
LazyColumn(content = {
item {
TopBar()
Spacer(modifier = Modifier.height(60.dp))
ProfileSection(
name = "Amit Segal",
company = "N12 news channel",
)
// voting bar
VotingBar(
leftyPercent = 10, rightyPercent = 90
)
// lazy column for more info
MoreInfo("Amit Segal is a journalist and a news anchor. He is the host of the N12 news channel. He is a very popular journalist. Amit Yitzchak Segal[1] (born Biz in Nisan 5, 1982, April 10, 1982) is an Israeli journalist, radio and television personality. Serves as the political commentator of the news company and a political columnist in the \"Yediot Aharonot\" newspaper. One of the most influential journalists in Israel[2]. Presents Meet the Press on Channel 12 together with Ben Caspit.")
}
})
}
}
@Composable
fun MoreInfo(information_param: String, modifier: Modifier = Modifier) {
Column(modifier = modifier.padding(start = 26.dp, end = 26.dp)) {
Text(
text = "More information",
color = Color.Black,
fontSize = 36.sp,
fontWeight = FontWeight.Bold
)
Text(
text = information_param,
color = Color.Black,
fontSize = 24.sp,
fontWeight = FontWeight.Normal,
maxLines = 10,
overflow = TextOverflow.Ellipsis
)
}
}
@Composable
fun VotingBar(
modifier: Modifier = Modifier, leftyPercent: Int, rightyPercent: Int
) {
var leftyPercentWeight: Float = (leftyPercent / 10).toFloat()
var rightyPercentWeight: Float = (rightyPercent / 10).toFloat()
val shape = RoundedCornerShape(32.dp)
Column(
Modifier.padding(start = 16.dp, end = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = modifier
.fillMaxWidth()
.height(32.dp)
.background(Color.White)
.clip(shape)
.border(1.dp, Color.Black, shape)
) {
Column(
// add rounded corners to the left side
modifier = Modifier
.background(Color(0xFFA60321))
.weight(rightyPercentWeight)
.clip(CircleShape)
.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
}
Column(
modifier = Modifier
.background(Color(0xFF03588C))
.fillMaxHeight(leftyPercentWeight)
.weight(1f)
.clip(CircleShape),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
// add rounded corners to the right side
) {
}
}
// second row
// stack over flow https://stackoverflow.com/questions/74619069/what-is-the-attribute-of-the-moddifier-that-i-need-to-change-to-make-the-corners?noredirect=1#comment131712293_74619069
Column(
Modifier.padding(start = 46.dp, end = 46.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.background(Color.White),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
) {
Row {
Box(
modifier = Modifier
.size(30.dp)
.clip(CircleShape)
.background(Color(0xFFA60321))
)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = "Right $rightyPercent%",
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
Row() {
Box(
modifier = Modifier
.size(30.dp)
.clip(CircleShape)
.background(Color(0xFF03588C))
)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = "Left $leftyPercent%", fontSize = 20.sp, fontWeight = FontWeight.Bold
)
}
}
}
}
}
@Composable
fun BlackBackgroundSquare() {
Box(
// modifier fill only half the screen
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
// insert background color as hex
.background(Color(0xFF2C3E50))
)
}
@Composable
fun TopBar(
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = modifier.fillMaxWidth()
) {
Text(
text = "Profile",
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 40.sp,
color = Color.White
)
}
}
@Composable
fun ProfileSection(
name: String, company: String, modifier: Modifier = Modifier
) {
Column(
modifier = modifier.fillMaxWidth(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
RoundImage(
image = painterResource(id = R.drawable.profile_pic), modifier = Modifier.size(250.dp)
)
Text(
text = name,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 40.sp,
color = Color.Black
)
Text(
text = company,
overflow = TextOverflow.Ellipsis,
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
color = Color.Black
)
}
}
@Composable
fun RoundImage(
image: Painter, modifier: Modifier = Modifier
) {
Image(
painter = image,
contentDescription = "Profile image",
modifier = modifier
.aspectRatio(1f, matchHeightConstraintsFirst = true)
.border(
width = 6.dp, color = Color.White, shape = CircleShape
)
.padding(3.dp)
.clip(CircleShape)
)
}
| [
"Add a state to LazyColumn, then use state.firstVisibleItemIndex to detect when first item is not visible. Use a DisposableEffect to detect index by index to prevent lag. When first idx is consumed, hide your upper bar. Could use a viewmodel to save first index. Then show action bar if first item is visible again.\n DisposableEffect(key1 = listState.firstVisibleItemIndex) {\n onDispose { \n viewModel\n .setFirstVisibleItemIdx(listState.firstVisibleItemIndex)\n }\n }\n\nOn enter get the index from viewmodel and scroll. If no value, just show as normal.\n LaunchedEffect(viewModel.firstVisibleItemIdx) {\n listState.scrollToItem(viewModel.firstVisibleItemIdx.value ?: 0)\n }\n\n"
] | [
1
] | [] | [] | [
"android_compose_textfield",
"android_jetpack",
"android_jetpack_compose",
"jetpack",
"kotlin"
] | stackoverflow_0074668225_android_compose_textfield_android_jetpack_android_jetpack_compose_jetpack_kotlin.txt |
Q:
Excel: TEXTJOIN from a range if conditions are met
I've encountered a problem in Excel that I don't know how to approach solving.
There are two tables in the image above.
Table 1 is a list of gifts exchanged between individuals, with the giver and the receiver identified. (I'm using "gifts" and "people" to make it easier to discuss here. In reality these are pieces of equipment exchanging control signals. This table can be hundreds of rows long.)
Table 2, columns E and F, is a list of unique person-pairs (irrespective of giver and receiver). I have already written formulas to search columns A and B and return only unique pairs in E and F. Now, for each unique pair, I need to return all of the gifts exchanged between the two individuals in column G (I have manually entered what column G should contain with a working formula.
I'm not even sure where to begin with this problem. Column G3's formula should have something like the following in it:
=and(or(B3=$E$3,C3=$E$3),or(B3=$F$3,C3=$F$3)),A3,"")
But then, the cell needs to search the entire range B:B and C:C and TEXTJOIN every A:A in which the conditions are met.
I am fine using VBA for a solution (even then, I'm not sure where to begin), but would prefer not; the data will be imported into another piece of software and that software can't execute VBA code.
Can anyone point me in the right direction?
Thanks for your help.
A:
Use FILTER
=TEXTJOIN(", ",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),""))
A:
This is just an extension of @ScottCraner's answer, to generate the array version, that doesn't require to have as input Person 1 and Person 2 columns.
In cell E1 you can put the following formula:
= LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,
rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),
sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),
idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),
gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(", ",TRUE,
FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),
VSTACK({"Person 1","Person 2","Items Exchanged"}, HSTACK(pb, pa, gifts))
)
and here is the output:
Notice this solution preserves the order of the expected output of the question.
Explanation
LET function is used for easy reading and composition. The first step is to identify unique pairs of [Giver, Receivers] regardless of the order. Each column is identified as g and r respectively.
The name ux, is used to identify unique values from both columns g, r as follows:
UNIQUE(TOCOL(B2:C9,,TRUE))
it returns:
Sam
Sally
Henry
Mike
We use the third input argument of TOCOL to append by columns instead of by rows.
The names rMatch and gMatch identify index positions that match unique names (ux). Here the intermediate result for both columns:
gMatch rMatch
2 1
1 2
3 2
4 3
3 1
2 1
2 3
1 3
We need to eliminate duplicated pairs. If we sort each row in ascending order by column:
gMatch rMatch
1 2
1 2
2 3
3 4
1 3
1 2
2 3
1 3
then if we concatenate both numbers on each row, we are able to identify duplicated pairs. The above steps are accomplished via sorted name:
BYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))
It is important to set the optional input argument [by_col] to TRUE in SORT function to ensure we want to sort by column each row. The result is an array that on each row has concatenated columns of above sorted values.
The name idx, has only the index positions of unique pairs:
XMATCH(UNIQUE(sorted), sorted)
Note: If the ux values don't appear in both columns then gMatch or rMatch will have some #N/A values. This would mean in the input data not all pair combination are present, maybe it is an indication some data clean-up is required first in your real problem. If not, then we can exclude such cases as follow: FILTER(idx, ISNUMBER(idx)) and name it idExcl for example and use idExcl in pa, pb definitions.
Now pa, pb have the unique pairs values from g and r. The name gifts uses the logic from @ScottCraner's answer, but using MAP to have an array result, so the is no need to drag-down the formula.
Finally, we put all together to generate the expected result via VSTACK and HSTACK functions.
| Excel: TEXTJOIN from a range if conditions are met | I've encountered a problem in Excel that I don't know how to approach solving.
There are two tables in the image above.
Table 1 is a list of gifts exchanged between individuals, with the giver and the receiver identified. (I'm using "gifts" and "people" to make it easier to discuss here. In reality these are pieces of equipment exchanging control signals. This table can be hundreds of rows long.)
Table 2, columns E and F, is a list of unique person-pairs (irrespective of giver and receiver). I have already written formulas to search columns A and B and return only unique pairs in E and F. Now, for each unique pair, I need to return all of the gifts exchanged between the two individuals in column G (I have manually entered what column G should contain with a working formula.
I'm not even sure where to begin with this problem. Column G3's formula should have something like the following in it:
=and(or(B3=$E$3,C3=$E$3),or(B3=$F$3,C3=$F$3)),A3,"")
But then, the cell needs to search the entire range B:B and C:C and TEXTJOIN every A:A in which the conditions are met.
I am fine using VBA for a solution (even then, I'm not sure where to begin), but would prefer not; the data will be imported into another piece of software and that software can't execute VBA code.
Can anyone point me in the right direction?
Thanks for your help.
| [
"Use FILTER\n=TEXTJOIN(\", \",TRUE,FILTER(A:A,((B:B=$E$3)+(C:C=$E$3))*((B:B=$F$3)+(C:C=$F$3)),\"\"))\n\n",
"This is just an extension of @ScottCraner's answer, to generate the array version, that doesn't require to have as input Person 1 and Person 2 columns.\nIn cell E1 you can put the following formula:\n= LET(ux, UNIQUE(TOCOL(B2:C9,,TRUE)), r, B2:B9, g, C2:C9, items, A2:A9,\n rMatch, XMATCH(r, ux), gMatch, XMATCH(g, ux),\n sorted, BYROW(HSTACK(gMatch, rMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE)))),\n idx, XMATCH(UNIQUE(sorted), sorted), pa, INDEX(g, idx), pb, INDEX(r, idx),\n gifts, MAP(pa, pb, LAMBDA(a,b, TEXTJOIN(\", \",TRUE,\n FILTER(items, ((g=a) + (r=a)) * ((g=b) + (r=b)))))),\n VSTACK({\"Person 1\",\"Person 2\",\"Items Exchanged\"}, HSTACK(pb, pa, gifts))\n)\n\nand here is the output:\n\nNotice this solution preserves the order of the expected output of the question.\nExplanation\nLET function is used for easy reading and composition. The first step is to identify unique pairs of [Giver, Receivers] regardless of the order. Each column is identified as g and r respectively.\nThe name ux, is used to identify unique values from both columns g, r as follows:\nUNIQUE(TOCOL(B2:C9,,TRUE))\n\nit returns:\nSam\nSally\nHenry\nMike\n\nWe use the third input argument of TOCOL to append by columns instead of by rows.\nThe names rMatch and gMatch identify index positions that match unique names (ux). Here the intermediate result for both columns:\ngMatch rMatch\n2 1\n1 2\n3 2\n4 3\n3 1\n2 1\n2 3\n1 3\n\nWe need to eliminate duplicated pairs. If we sort each row in ascending order by column:\ngMatch rMatch\n1 2\n1 2\n2 3\n3 4\n1 3\n1 2\n2 3\n1 3\n\nthen if we concatenate both numbers on each row, we are able to identify duplicated pairs. The above steps are accomplished via sorted name:\nBYROW(HSTACK(rMatch, gMatch), LAMBDA(r, CONCAT(SORT(r,,,TRUE))))\n\nIt is important to set the optional input argument [by_col] to TRUE in SORT function to ensure we want to sort by column each row. The result is an array that on each row has concatenated columns of above sorted values.\nThe name idx, has only the index positions of unique pairs:\nXMATCH(UNIQUE(sorted), sorted)\n\nNote: If the ux values don't appear in both columns then gMatch or rMatch will have some #N/A values. This would mean in the input data not all pair combination are present, maybe it is an indication some data clean-up is required first in your real problem. If not, then we can exclude such cases as follow: FILTER(idx, ISNUMBER(idx)) and name it idExcl for example and use idExcl in pa, pb definitions.\nNow pa, pb have the unique pairs values from g and r. The name gifts uses the logic from @ScottCraner's answer, but using MAP to have an array result, so the is no need to drag-down the formula.\nFinally, we put all together to generate the expected result via VSTACK and HSTACK functions.\n"
] | [
1,
0
] | [] | [] | [
"excel",
"excel_formula"
] | stackoverflow_0074658982_excel_excel_formula.txt |
Q:
Is it possible to alter timestamps from mongoose in a html page using CSS or some other method?
I have a mongoDB schema which contains timestamps on top of other user inputs from my little html page. When displaying a table of all the data, I want it to also show the exact date of when the entry was made. I am using timestamps for this.
I am using Node.js for all the routes, so here is the code which renders the table page in case that is of use:
router.get('/table', function(req, res) {
phones.find().then((phonesfound) => {
res.render('table', { 'phonelist': phonesfound, title: 'tablepage' });
})
}
Here is the code for my schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//data sent to DB and received from DB for table creation
var Schemaful = new Schema({
name: {
type: String,
required: true,
},
timeEducation: {
type: Number,
required: true,
"maximum": 1140
},
timeShopping: {
type: Number,
required: true,
"maximum": 1140
},
timeBrowsing: {
type: Number,
required: true,
"maximum": 1140
},
timeSocial: {
type: Number,
required: true,
"maximum": 1140
}, //add a date input
}, {
timestamps: true
});
var phone = mongoose.model('Phone', Schemaful); //initialize a model with a scheme you created. schema gives the layout while the model provides the functions for interacting the database
module.exports = phone;
This is then the page which displays a table of data from the DB:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>MTU Phone Usage Monitor</title>
<link rel="stylesheet" href="/stylesheets/styleTable.css"></link>
</head>
<body>
<div class="banner">
<div class="navbar">
<img src="\images\logo.png" class="logo">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/phone/create">New Entry</a></li>
<li><a href="/table">View Data</a></li>
<li><a href="/help">Help/About</a></li>
</ul>
</div>
<div class="content">
<form action="/phone/find" method="post">
<input type="text" name="name" placeholder="Search individual user">
</form>
</div>
<div class="table-wrapper">
<table class="tableData">
<caption>Phone Usage</caption>
<thead>
<tr>
<th>Name</th>
<th>Education Usage</th>
<th>Shopping Usage</th>
<th>Searching/Browsing usage</th>
<th>Social Media usage</th>
<th>Date and Time</th>
<th></th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < phonelist.length; i++) { %>
<tr>
<td>
<%= phonelist[i].name %>
</td>
<td>
<%= phonelist[i].timeEducation %>
</td>
<td>
<%= phonelist[i].timeShopping %>
</td>
<td>
<%= phonelist[i].timeBrowsing %>
</td>
<td>
<%= phonelist[i].timeSocial %>
</td>
<td>
<%= phonelist[i].createdAt %>
</td>
<td>
<div class="secret">
<form action="/phone/delete" method="post"> <input type="String" value="<%= phonelist[i].id%>" name="id" readonly><button type="Submit"><span></span>Delete</button></form>
<form action="/phone/update" method="post"> <input type="String" value="<%=phonelist[i].id%>" name="id" readonly><button type="Submit"><span></span>Update</button></form>
</div>
</td>
</tr>
<% } %>
</div>
</tbody>
<div class="avg"></div>
</body>
</html>
Everything displays perfectly as seen here.
But, the timestamp is pretty ugly. I would like it to only display the date without the time and timezone, etc.
Is it possible to do something like this? If so, how?
A:
To display only the date when an entry was made in your table, you can use the .toLocaleDateString() method on the createdAt property of each entry. This method returns the date in the format specified by the locale parameter passed to it.
To display the date in your table, you can modify your table cell in the table.ejs file like this:
<table class="tableData">
<caption>Phone Usage</caption>
<thead>
<tr>
<th>Name</th>
<th>Education Usage</th>
<th>Shopping Usage</th>
<th>Searching/Browsing usage</th>
<th>Social Media usage</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < phonelist.length; i++) { %>
<tr>
<td>
<%= phonelist[i].name %>
</td>
<td>
<%= phonelist[i].timeEducation %>
</td>
<td>
<%= phonelist[i].timeShopping %>
</td>
<td>
<%= phonelist[i].timeBrowsing %>
</td>
<td>
<%= phonelist[i].timeSocial %>
</td>
<td>
<%= phonelist[i].createdAt.toLocaleDateString() %>
</td>
<td>
<div class="secret">
<%= phonelist[i]._id %>
</div>
</td>
</tr>
<% } %>
</tbody>
</table>
In the code above, the .toLocaleDateString() method has been added to the createdAt property of each entry. This method returns the date in the default format of the user's locale.
After making these changes, only the date when each entry was made will be displayed in the table.
| Is it possible to alter timestamps from mongoose in a html page using CSS or some other method? | I have a mongoDB schema which contains timestamps on top of other user inputs from my little html page. When displaying a table of all the data, I want it to also show the exact date of when the entry was made. I am using timestamps for this.
I am using Node.js for all the routes, so here is the code which renders the table page in case that is of use:
router.get('/table', function(req, res) {
phones.find().then((phonesfound) => {
res.render('table', { 'phonelist': phonesfound, title: 'tablepage' });
})
}
Here is the code for my schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//data sent to DB and received from DB for table creation
var Schemaful = new Schema({
name: {
type: String,
required: true,
},
timeEducation: {
type: Number,
required: true,
"maximum": 1140
},
timeShopping: {
type: Number,
required: true,
"maximum": 1140
},
timeBrowsing: {
type: Number,
required: true,
"maximum": 1140
},
timeSocial: {
type: Number,
required: true,
"maximum": 1140
}, //add a date input
}, {
timestamps: true
});
var phone = mongoose.model('Phone', Schemaful); //initialize a model with a scheme you created. schema gives the layout while the model provides the functions for interacting the database
module.exports = phone;
This is then the page which displays a table of data from the DB:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>MTU Phone Usage Monitor</title>
<link rel="stylesheet" href="/stylesheets/styleTable.css"></link>
</head>
<body>
<div class="banner">
<div class="navbar">
<img src="\images\logo.png" class="logo">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/phone/create">New Entry</a></li>
<li><a href="/table">View Data</a></li>
<li><a href="/help">Help/About</a></li>
</ul>
</div>
<div class="content">
<form action="/phone/find" method="post">
<input type="text" name="name" placeholder="Search individual user">
</form>
</div>
<div class="table-wrapper">
<table class="tableData">
<caption>Phone Usage</caption>
<thead>
<tr>
<th>Name</th>
<th>Education Usage</th>
<th>Shopping Usage</th>
<th>Searching/Browsing usage</th>
<th>Social Media usage</th>
<th>Date and Time</th>
<th></th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < phonelist.length; i++) { %>
<tr>
<td>
<%= phonelist[i].name %>
</td>
<td>
<%= phonelist[i].timeEducation %>
</td>
<td>
<%= phonelist[i].timeShopping %>
</td>
<td>
<%= phonelist[i].timeBrowsing %>
</td>
<td>
<%= phonelist[i].timeSocial %>
</td>
<td>
<%= phonelist[i].createdAt %>
</td>
<td>
<div class="secret">
<form action="/phone/delete" method="post"> <input type="String" value="<%= phonelist[i].id%>" name="id" readonly><button type="Submit"><span></span>Delete</button></form>
<form action="/phone/update" method="post"> <input type="String" value="<%=phonelist[i].id%>" name="id" readonly><button type="Submit"><span></span>Update</button></form>
</div>
</td>
</tr>
<% } %>
</div>
</tbody>
<div class="avg"></div>
</body>
</html>
Everything displays perfectly as seen here.
But, the timestamp is pretty ugly. I would like it to only display the date without the time and timezone, etc.
Is it possible to do something like this? If so, how?
| [
"To display only the date when an entry was made in your table, you can use the .toLocaleDateString() method on the createdAt property of each entry. This method returns the date in the format specified by the locale parameter passed to it.\nTo display the date in your table, you can modify your table cell in the table.ejs file like this:\n<table class=\"tableData\">\n <caption>Phone Usage</caption>\n <thead>\n <tr>\n <th>Name</th>\n <th>Education Usage</th>\n <th>Shopping Usage</th>\n <th>Searching/Browsing usage</th>\n <th>Social Media usage</th>\n <th>Date</th>\n <th></th>\n </tr>\n </thead>\n\n <tbody>\n <% for(var i=0; i < phonelist.length; i++) { %>\n <tr>\n <td>\n <%= phonelist[i].name %>\n </td>\n <td>\n <%= phonelist[i].timeEducation %>\n </td>\n <td>\n <%= phonelist[i].timeShopping %>\n </td>\n <td>\n <%= phonelist[i].timeBrowsing %>\n </td>\n <td>\n <%= phonelist[i].timeSocial %>\n </td>\n <td>\n <%= phonelist[i].createdAt.toLocaleDateString() %>\n </td>\n <td>\n <div class=\"secret\">\n <%= phonelist[i]._id %>\n </div>\n </td>\n </tr>\n <% } %>\n </tbody>\n</table>\n\nIn the code above, the .toLocaleDateString() method has been added to the createdAt property of each entry. This method returns the date in the default format of the user's locale.\nAfter making these changes, only the date when each entry was made will be displayed in the table.\n"
] | [
0
] | [] | [] | [
"css",
"html",
"javascript",
"mongoose",
"node.js"
] | stackoverflow_0074671733_css_html_javascript_mongoose_node.js.txt |
Q:
powershell -replace only write file on changes
I'm doing some multiple regEX replacements in powershell on a large number of files and would like to only write the file if any replacements were actually made.
For example if I do:
($_ | Get-Content-Raw) -Replace 'MAKEUPS', 'Makeup' -Replace '_MAKEUP', 'Makeup' -Replace 'Make up', 'Makeup' -Replace 'Make-up', 'Makeup' -Replace '"SELF:/', '"' |
Out-File $_.FullName -encoding ASCII
I only want to write the file if it found anything to replace. Is this possible, maybe with a count or boolean operation?
I did think maybe to check the length of the string before and after but was hoping for a more elegant solution, so I thought I'd ask the experts!
A:
You could use the script block feature added in ps6 to set a variable when a replacement takes place, then return the replacement string.
$replaced = $false
$content = (Get-content -raw $file) -replace "(make-up|makeups|make up|...)", {
# $replaced = $true
Set-Variable replaced $true -Scope 1
return "Makeup"
} -replace "SELF:/", {
Set-Variable replaced $true -Scope 1
# $replaced = $true
return '"'
}
If ($replaced){
Set-content -path $file -value $content
}
In older versions of PowerShell, you might check the content length and if they're the same do a comparison... I wouldn't do a match to see if replacement is needed, that would be a lot more expensive...
$original = (Get-content -raw $file)
$content = ($original) -replace "(make-up|makeups|make up|...)", "Make up"
If (($original.length -ne $content.length) -or ($original -ne $content)) {
Set-content ...
}
A:
You can take advantage of the fact that PowerShell's -replace operator passes the input string through as-is if no replacements were performed:
# <# some Get-ChildItem command #> ... | ForEach-Object {
# Read the input file in full, as a single string.
$originalContent = $_ | Get-Content -Raw
# *Potentially* perform replacements, depending on whether the search patterns are found.
$potentiallyModifiedContent =
$originalContent -replace 'MAKEUPS', 'Makeup' -replace '_MAKEUP', 'Makeup' -replace 'Make up', 'Makeup' -replace 'Make-up', 'Makeup' -replace '"SELF:/', '"'
# Save, but only if modifications were made.
if (-not [object]::ReferenceEquals($originalContent, $potentiallyModifiedConent)) {
Set-Content -NoNewLine -Encoding Ascii -LiteralPath $_.FullName -Value $potentiallyModifiedConent
}
# }
[object]::ReferenceEquals() tests for reference equality, i.e. whether the two strings represent the exact same string instance, which makes the comparison very efficient (no need to look at the content of the strings).
Set-Content rather than Out-File is used to write the output file, which is preferable for performance reasons with input that is made up of strings already.
-NoNewLine is needed to prevent a trailing newline from getting appended to the output file.
| powershell -replace only write file on changes | I'm doing some multiple regEX replacements in powershell on a large number of files and would like to only write the file if any replacements were actually made.
For example if I do:
($_ | Get-Content-Raw) -Replace 'MAKEUPS', 'Makeup' -Replace '_MAKEUP', 'Makeup' -Replace 'Make up', 'Makeup' -Replace 'Make-up', 'Makeup' -Replace '"SELF:/', '"' |
Out-File $_.FullName -encoding ASCII
I only want to write the file if it found anything to replace. Is this possible, maybe with a count or boolean operation?
I did think maybe to check the length of the string before and after but was hoping for a more elegant solution, so I thought I'd ask the experts!
| [
"You could use the script block feature added in ps6 to set a variable when a replacement takes place, then return the replacement string.\n$replaced = $false\n$content = (Get-content -raw $file) -replace \"(make-up|makeups|make up|...)\", { \n # $replaced = $true\n Set-Variable replaced $true -Scope 1\n return \"Makeup\"\n} -replace \"SELF:/\", { \n Set-Variable replaced $true -Scope 1\n # $replaced = $true\n return '\"'\n}\n\nIf ($replaced){\n Set-content -path $file -value $content\n}\n\nIn older versions of PowerShell, you might check the content length and if they're the same do a comparison... I wouldn't do a match to see if replacement is needed, that would be a lot more expensive...\n$original = (Get-content -raw $file)\n$content = ($original) -replace \"(make-up|makeups|make up|...)\", \"Make up\"\n\nIf (($original.length -ne $content.length) -or ($original -ne $content)) {\n Set-content ...\n}\n\n",
"\nYou can take advantage of the fact that PowerShell's -replace operator passes the input string through as-is if no replacements were performed:\n# <# some Get-ChildItem command #> ... | ForEach-Object {\n\n # Read the input file in full, as a single string.\n $originalContent = $_ | Get-Content -Raw\n\n # *Potentially* perform replacements, depending on whether the search patterns are found.\n $potentiallyModifiedContent =\n $originalContent -replace 'MAKEUPS', 'Makeup' -replace '_MAKEUP', 'Makeup' -replace 'Make up', 'Makeup' -replace 'Make-up', 'Makeup' -replace '\"SELF:/', '\"'\n\n # Save, but only if modifications were made.\n if (-not [object]::ReferenceEquals($originalContent, $potentiallyModifiedConent)) {\n Set-Content -NoNewLine -Encoding Ascii -LiteralPath $_.FullName -Value $potentiallyModifiedConent\n }\n\n# }\n\n\n[object]::ReferenceEquals() tests for reference equality, i.e. whether the two strings represent the exact same string instance, which makes the comparison very efficient (no need to look at the content of the strings).\n\nSet-Content rather than Out-File is used to write the output file, which is preferable for performance reasons with input that is made up of strings already.\n\n-NoNewLine is needed to prevent a trailing newline from getting appended to the output file.\n\n\n\n"
] | [
1,
1
] | [] | [] | [
"powershell",
"regexp_replace"
] | stackoverflow_0074670572_powershell_regexp_replace.txt |
Q:
Bag of words process with comments data?
I have a training set "x" containing an array, where each list within the array refers to the words of a comment. So if I run:
len(x)"
returns 8000
In particular, I want to choose the common tokens in at least 1% of the comments and then count the number of times each of those tokens appears in each review and generate, for each review, a vector of numeric variables in which each position refers to each of those relevant or common tokens and indicates how many times that token appears in the comment in question.
Adjunto una muestra de x:
[['amazon',
'phone',
'serious',
'mind',
'blown',
'serious',
'enjoy',
'use',
'applic',
'full',
'blown',
'websit',
'allow',
'quick',
'track',
'packag',
'descript',
'say'],
['would',
'say',
'app',
'real',
'thing',
'show',
'ghost',
'said',
'quot',
'orang',
'quot',
'ware',
'orang',
'cloth',
'app',
'adiquit',
'would',
'recsmend',
'want',
'talk',
'ghost'],
['love',
'play',
'backgammonthi',
'game',
'offer',
'varieti',
'difficulti',
'make',
'perfect',
'beginn',
'season',
'player']]
Any help on how to save in a list the tokens that appear in at least 1% of the reviews?
A:
To create a list of tokens that appear in at least 1% of the reviews, you can use a dictionary to count the number of times each token appears in the training set, and then filter the dictionary to only include tokens that appear in at least 1% of the reviews.
Here's an example of how you could do this:
# First, create an empty dictionary to count the number of times each token appears
token_counts = {}
# Loop through each review in the training set
for review in x:
# Loop through each token in the review
for token in review:
# If the token is not already in the dictionary, add it with a count of 1
if token not in token_counts:
token_counts[token] = 1
# If the token is already in the dictionary, increment its count by 1
else:
token_counts[token] += 1
# Next, create a list of tokens that appear in at least 1% of the reviews
common_tokens = []
# Calculate the number of reviews in the training set
num_reviews = len(x)
# Loop through each token and its count in the dictionary
for token, count in token_counts.items():
# If the token appears in at least 1% of the reviews, add it to the list of common tokens
if count / num_reviews >= 0.01:
common_tokens.append(token)
# Finally, you can use the list of common tokens to generate a vector for each review, where each position in the vector indicates how many times the corresponding token appears in the review
for review in x:
# Create an empty vector with the same length as the list of common tokens
vector = [0] * len(common_tokens)
# Loop through each token in the review
for token in review:
# If the token is in the list of common tokens, increment the corresponding position in the vector
if token in common_tokens:
vector[common_tokens.index(token)] += 1
# At this point, the vector for the review will be a list of numeric variables, where each position indicates how many times the corresponding common token appears in the review
print(vector)
| Bag of words process with comments data? | I have a training set "x" containing an array, where each list within the array refers to the words of a comment. So if I run:
len(x)"
returns 8000
In particular, I want to choose the common tokens in at least 1% of the comments and then count the number of times each of those tokens appears in each review and generate, for each review, a vector of numeric variables in which each position refers to each of those relevant or common tokens and indicates how many times that token appears in the comment in question.
Adjunto una muestra de x:
[['amazon',
'phone',
'serious',
'mind',
'blown',
'serious',
'enjoy',
'use',
'applic',
'full',
'blown',
'websit',
'allow',
'quick',
'track',
'packag',
'descript',
'say'],
['would',
'say',
'app',
'real',
'thing',
'show',
'ghost',
'said',
'quot',
'orang',
'quot',
'ware',
'orang',
'cloth',
'app',
'adiquit',
'would',
'recsmend',
'want',
'talk',
'ghost'],
['love',
'play',
'backgammonthi',
'game',
'offer',
'varieti',
'difficulti',
'make',
'perfect',
'beginn',
'season',
'player']]
Any help on how to save in a list the tokens that appear in at least 1% of the reviews?
| [
"To create a list of tokens that appear in at least 1% of the reviews, you can use a dictionary to count the number of times each token appears in the training set, and then filter the dictionary to only include tokens that appear in at least 1% of the reviews.\nHere's an example of how you could do this:\n# First, create an empty dictionary to count the number of times each token appears\ntoken_counts = {}\n\n# Loop through each review in the training set\nfor review in x:\n # Loop through each token in the review\n for token in review:\n # If the token is not already in the dictionary, add it with a count of 1\n if token not in token_counts:\n token_counts[token] = 1\n # If the token is already in the dictionary, increment its count by 1\n else:\n token_counts[token] += 1\n\n# Next, create a list of tokens that appear in at least 1% of the reviews\ncommon_tokens = []\n\n# Calculate the number of reviews in the training set\nnum_reviews = len(x)\n\n# Loop through each token and its count in the dictionary\nfor token, count in token_counts.items():\n # If the token appears in at least 1% of the reviews, add it to the list of common tokens\n if count / num_reviews >= 0.01:\n common_tokens.append(token)\n\n# Finally, you can use the list of common tokens to generate a vector for each review, where each position in the vector indicates how many times the corresponding token appears in the review\nfor review in x:\n # Create an empty vector with the same length as the list of common tokens\n vector = [0] * len(common_tokens)\n # Loop through each token in the review\n for token in review:\n # If the token is in the list of common tokens, increment the corresponding position in the vector\n if token in common_tokens:\n vector[common_tokens.index(token)] += 1\n # At this point, the vector for the review will be a list of numeric variables, where each position indicates how many times the corresponding common token appears in the review\n print(vector)\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074671742_python.txt |
Q:
r - Filtering rows by consecutive overlapping time intervals
I got the following dataframe:
Sensor Event Start.Time End.Time
1 1 Alert 05/01/2022 03:50:00 05/01/2022 04:10:00
2 1 Alarm 05/01/2022 03:55:00 05/01/2022 04:03:00
3 2 Alert 05/01/2022 03:56:00 05/01/2022 04:00:00
4 2 Alarm 06/02/2022 12:31:00 06/02/2022 12:54:00
5 1 Alert 14/01/2022 22:44:00 15/01/2022 00:40:00
6 1 Alarm 14/01/2022 22:36:00 15/01/2022 00:15:00
7 2 Alert 06/02/2022 12:25:00 06/02/2022 13:01:00
8 4 Alarm 05/03/2022 15:00:00 05/03/2022 15:30:00
9 3 Alert 07/04/2022 16:25:00 07/04/2022 16:38:00
10 3 Alarm 07/04/2022 16:27:00 07/04/2022 16:40:00
11 4 Alert 08/05/2022 19:00:00 08/05/2022 19:33:00
12 4 Alarm 08/05/2022 19:12:00 08/05/2022 19:21:00
13 1 Alarm 14/01/2022 22:46:00 15/01/2022 00:12:00
14 2 Alert 11/06/2022 19:00:00 11/06/2022 20:34:00
15 2 Alarm 11/06/2022 19:21:00 11/06/2022 20:12:00
from this code:
st <- c(20220105035000,20220105035500,20220105035600,20220206123100,20220114224400,20220114223600,20220206122500,
20220305150000,20220407162500,20220407162700,20220508190000,20220508191200,20220114224600,20220611190000,
20220611192100)
et <-c(20220105041000,20220105040300,20220105040000,20220206125400,20220115004000,20220115001500,
20220206130100,20220305153000,2020407163800,20220407164000,20220508193300,
20220508192100,20220115001200,20220611203400,20220611201200)
df <- data.frame(Sensor=c(1,1,2,2,1,1,2,4,3,3,4,4,1,2,2),
Event=c("Alert","Alarm","Alert","Alarm","Alert","Alarm","Alert","Alarm",
"Alert","Alarm","Alert","Alarm","Alarm","Alert","Alarm"),
Start.time=c(ymd_hms(st)),
End.time=c(ymd_hms(et)))
I need to drop all the "Alert rows" whose time intervals include their chronological consecutive (previous/following) "Alarm rows" time intervals. This check must be performed grouping by Sensor.
In other words the outcome should be something like this:
Sensor Event Start.Time End.Time
2 1 Alarm 05/01/2022 03:55:00 05/01/2022 04:03:00
3 2 Alert 05/01/2022 03:56:00 05/01/2022 04:00:00
4 2 Alarm 06/02/2022 12:31:00 06/02/2022 12:54:00
5 1 Alert 14/01/2022 22:44:00 15/01/2022 00:40:00
6 1 Alarm 14/01/2022 22:36:00 15/01/2022 00:15:00
8 4 Alarm 05/03/2022 15:00:00 05/03/2022 15:30:00
9 3 Alert 07/04/2022 16:25:00 07/04/2022 16:38:00
10 3 Alarm 07/04/2022 16:27:00 07/04/2022 16:40:00
11 4 Alert 08/05/2022 19:00:00 08/05/2022 19:33:00
13 1 Alarm 14/01/2022 22:46:00 15/01/2022 00:12:00
15 2 Alarm 11/06/2022 19:21:00 11/06/2022 20:12:00
Thank you in advance!
A:
I did not achieved your expected output, but got a partial result that might help you
library(dplyr)
df %>%
group_by(Sensor) %>%
filter(
!(Event == "Alert" & (End.time > lead(Start.time) ) )
)
# A tibble: 11 x 4
# Groups: Sensor [4]
Sensor Event Start.time End.time
<dbl> <chr> <dttm> <dttm>
1 1 Alarm 2022-01-05 03:55:00 2022-01-05 04:03:00
2 2 Alert 2022-01-05 03:56:00 2022-01-05 04:00:00
3 2 Alarm 2022-02-06 12:31:00 2022-02-06 12:54:00
4 1 Alarm 2022-01-14 22:36:00 2022-01-15 00:15:00
5 2 Alert 2022-02-06 12:25:00 2022-02-06 13:01:00
6 4 Alarm 2022-03-05 15:00:00 2022-03-05 15:30:00
7 3 Alert 2022-04-07 16:25:00 0202-04-07 16:38:00
8 3 Alarm 2022-04-07 16:27:00 2022-04-07 16:40:00
9 4 Alarm 2022-05-08 19:12:00 2022-05-08 19:21:00
10 1 Alarm 2022-01-14 22:46:00 2022-01-15 00:12:00
11 2 Alarm 2022-06-11 19:21:00 2022-06-11 20:12:00
| r - Filtering rows by consecutive overlapping time intervals | I got the following dataframe:
Sensor Event Start.Time End.Time
1 1 Alert 05/01/2022 03:50:00 05/01/2022 04:10:00
2 1 Alarm 05/01/2022 03:55:00 05/01/2022 04:03:00
3 2 Alert 05/01/2022 03:56:00 05/01/2022 04:00:00
4 2 Alarm 06/02/2022 12:31:00 06/02/2022 12:54:00
5 1 Alert 14/01/2022 22:44:00 15/01/2022 00:40:00
6 1 Alarm 14/01/2022 22:36:00 15/01/2022 00:15:00
7 2 Alert 06/02/2022 12:25:00 06/02/2022 13:01:00
8 4 Alarm 05/03/2022 15:00:00 05/03/2022 15:30:00
9 3 Alert 07/04/2022 16:25:00 07/04/2022 16:38:00
10 3 Alarm 07/04/2022 16:27:00 07/04/2022 16:40:00
11 4 Alert 08/05/2022 19:00:00 08/05/2022 19:33:00
12 4 Alarm 08/05/2022 19:12:00 08/05/2022 19:21:00
13 1 Alarm 14/01/2022 22:46:00 15/01/2022 00:12:00
14 2 Alert 11/06/2022 19:00:00 11/06/2022 20:34:00
15 2 Alarm 11/06/2022 19:21:00 11/06/2022 20:12:00
from this code:
st <- c(20220105035000,20220105035500,20220105035600,20220206123100,20220114224400,20220114223600,20220206122500,
20220305150000,20220407162500,20220407162700,20220508190000,20220508191200,20220114224600,20220611190000,
20220611192100)
et <-c(20220105041000,20220105040300,20220105040000,20220206125400,20220115004000,20220115001500,
20220206130100,20220305153000,2020407163800,20220407164000,20220508193300,
20220508192100,20220115001200,20220611203400,20220611201200)
df <- data.frame(Sensor=c(1,1,2,2,1,1,2,4,3,3,4,4,1,2,2),
Event=c("Alert","Alarm","Alert","Alarm","Alert","Alarm","Alert","Alarm",
"Alert","Alarm","Alert","Alarm","Alarm","Alert","Alarm"),
Start.time=c(ymd_hms(st)),
End.time=c(ymd_hms(et)))
I need to drop all the "Alert rows" whose time intervals include their chronological consecutive (previous/following) "Alarm rows" time intervals. This check must be performed grouping by Sensor.
In other words the outcome should be something like this:
Sensor Event Start.Time End.Time
2 1 Alarm 05/01/2022 03:55:00 05/01/2022 04:03:00
3 2 Alert 05/01/2022 03:56:00 05/01/2022 04:00:00
4 2 Alarm 06/02/2022 12:31:00 06/02/2022 12:54:00
5 1 Alert 14/01/2022 22:44:00 15/01/2022 00:40:00
6 1 Alarm 14/01/2022 22:36:00 15/01/2022 00:15:00
8 4 Alarm 05/03/2022 15:00:00 05/03/2022 15:30:00
9 3 Alert 07/04/2022 16:25:00 07/04/2022 16:38:00
10 3 Alarm 07/04/2022 16:27:00 07/04/2022 16:40:00
11 4 Alert 08/05/2022 19:00:00 08/05/2022 19:33:00
13 1 Alarm 14/01/2022 22:46:00 15/01/2022 00:12:00
15 2 Alarm 11/06/2022 19:21:00 11/06/2022 20:12:00
Thank you in advance!
| [
"I did not achieved your expected output, but got a partial result that might help you\nlibrary(dplyr)\n\ndf %>% \n group_by(Sensor) %>% \n filter(\n !(Event == \"Alert\" & (End.time > lead(Start.time) ) )\n )\n\n# A tibble: 11 x 4\n# Groups: Sensor [4]\n Sensor Event Start.time End.time \n <dbl> <chr> <dttm> <dttm> \n 1 1 Alarm 2022-01-05 03:55:00 2022-01-05 04:03:00\n 2 2 Alert 2022-01-05 03:56:00 2022-01-05 04:00:00\n 3 2 Alarm 2022-02-06 12:31:00 2022-02-06 12:54:00\n 4 1 Alarm 2022-01-14 22:36:00 2022-01-15 00:15:00\n 5 2 Alert 2022-02-06 12:25:00 2022-02-06 13:01:00\n 6 4 Alarm 2022-03-05 15:00:00 2022-03-05 15:30:00\n 7 3 Alert 2022-04-07 16:25:00 0202-04-07 16:38:00\n 8 3 Alarm 2022-04-07 16:27:00 2022-04-07 16:40:00\n 9 4 Alarm 2022-05-08 19:12:00 2022-05-08 19:21:00\n10 1 Alarm 2022-01-14 22:46:00 2022-01-15 00:12:00\n11 2 Alarm 2022-06-11 19:21:00 2022-06-11 20:12:00\n\n"
] | [
1
] | [] | [] | [
"datetime",
"filtering",
"lubridate",
"overlap",
"r"
] | stackoverflow_0074671383_datetime_filtering_lubridate_overlap_r.txt |
Q:
how to write a function that uses the fivenum() to do a 5N summary of a vector and produces a histogram of the data with ggplot
Please write a function to calculate the 5N summary and produces a histogram of the data
with ggplot. HINT: Youβll have to convert the vector into a data frame/tibble.
and I am allowed to use the fivenum()
I tried doin the following:
z <- rnorm(1000)
fivenum(z)
for(z) {
tibble (z)
}
but I am stuck at the tibble, how do I covert the vector to tibble?
A:
library(dplyr)
z <- rnorm(1000)
df <- tibble(z = z)
df %>%
summarise(fivenum(z))
| how to write a function that uses the fivenum() to do a 5N summary of a vector and produces a histogram of the data with ggplot | Please write a function to calculate the 5N summary and produces a histogram of the data
with ggplot. HINT: Youβll have to convert the vector into a data frame/tibble.
and I am allowed to use the fivenum()
I tried doin the following:
z <- rnorm(1000)
fivenum(z)
for(z) {
tibble (z)
}
but I am stuck at the tibble, how do I covert the vector to tibble?
| [
"library(dplyr)\n\nz <- rnorm(1000)\n\ndf <- tibble(z = z)\n\ndf %>% \n summarise(fivenum(z))\n\n"
] | [
0
] | [] | [] | [
"function",
"r",
"tibble"
] | stackoverflow_0074671768_function_r_tibble.txt |
Q:
How to loop through this query using Jsoup?
I want to loop through the news table and get the title and rating of each row. I tried different options, but I canβt understand why the select method receives all the options at once.
I need to get each news block in a loop.
I used this way to get table link:
Elements elements = document.select("#hnmain > tbody > tr:nth-child(3) > td > table");
This query doesn't work in a loop because it gets all the elements at once. I need to get the elements sequentially. So that I can do like this:
List list = new ArrayList<>();
for (Element element: elements){
String title = element...
String rating = element...
list.add(title);
list.add(rating);
}
Sample data from html:
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr class="athing" id="33582264">
<td align="right" valign="top" class="title"><span class="rank">1.</span></td>
<td valign="top" class="votelinks">
<center>
<a id="up_33582264" href="vote?id=33582264&how=up&goto=front%3Fday%3D2022-11-13">
<div class="votearrow" title="upvote"></div></a>
</center></td>
<td class="title"><span class="titleline"><a href="https://upbase.io/">Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.</a><span class="sitebit comhead"> (<a href="from?site=upbase.io"><span class="sitestr">upbase.io</span></a>)</span></span></td>
</tr>
<tr>
<td colspan="2"></td>
<td class="subtext"><span class="subline"> <span class="score" id="score_33582264">632 points</span> by <a href="user?id=tonypham" class="hnuser">tonypham</a> <span class="age" title="2022-11-13T12:00:06"><a href="item?id=33582264">20 days ago</a></span> <span id="unv_33582264"></span> | <a href="hide?id=33582264&goto=front%3Fday%3D2022-11-13">hide</a> | <a href="item?id=33582264">456 comments</a> </span></td>
</tr>
<tr class="spacer" style="height:5px"></tr>
<tr class="athing" id="33584941">
<td align="right" valign="top" class="title"><span class="rank">2.</span></td>
<td valign="top" class="votelinks">
<center>
<a id="up_33584941" href="vote?id=33584941&how=up&goto=front%3Fday%3D2022-11-13">
<div class="votearrow" title="upvote"></div></a>
</center></td>
<td class="title"><span class="titleline"><a href="https://fathy.fr/html2svg">Forking Chrome to turn HTML into SVG</a><span class="sitebit comhead"> (<a href="from?site=fathy.fr"><span class="sitestr">fathy.fr</span></a>)</span></span></td>
</tr>
A:
Here is an example of how you can loop through the news table using Jsoup:
// First, select the table with the news
Elements elements = document.select("#hnmain > tbody > tr:nth-child(3) > td > table");
// Then, loop through the table
for (Element element: elements){
// For each news item, select the title and rating
String title = element.select(".title a").text();
String rating = element.select(".subtext .score").text();
// Print the title and rating of each news item
System.out.println("Title: " + title);
System.out.println("Rating: " + rating);
}
This code should print the title and rating of each news item in the table.
For example, for the first news item in the sample data, it would print:
Title: Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.
Rating: 632 points
A:
if I understand your question I think this code will work for you
Document doc = Jsoup.parse("<table border=\"0\" id=\"hnmain\" cellpadding=\"0\" cellspacing=\"0\"> <tbody> <tr class=\"athing\" id=\"33582264\"> <td align=\"right\" valign=\"top\" class=\"title\"><span class=\"rank\">1.</span></td> <td valign=\"top\" class=\"votelinks\"> <center> <a id=\"up_33582264\" href=\"vote?id=33582264&how=up&goto=front%3Fday%3D2022-11-13\"> <div class=\"votearrow\" title=\"upvote\"></div></a> </center></td> <td class=\"title\"><span class=\"titleline\"><a href=\"https://upbase.io/\">Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.</a><span class=\"sitebit comhead\"> (<a href=\"from?site=upbase.io\"><span class=\"sitestr\">upbase.io</span></a>)</span></span></td> </tr> <tr> <td colspan=\"2\"></td> <td class=\"subtext\"><span class=\"subline\"> <span class=\"score\" id=\"score_33582264\">632 points</span> by <a href=\"user?id=tonypham\" class=\"hnuser\">tonypham</a> <span class=\"age\" title=\"2022-11-13T12:00:06\"><a href=\"item?id=33582264\">20 days ago</a></span> <span id=\"unv_33582264\"></span> | <a href=\"hide?id=33582264&goto=front%3Fday%3D2022-11-13\">hide</a> | <a href=\"item?id=33582264\">456 comments</a> </span></td> </tr> <tr class=\"spacer\" style=\"height:5px\"></tr> <tr class=\"athing\" id=\"33584941\"> <td align=\"right\" valign=\"top\" class=\"title\"><span class=\"rank\">2.</span></td> <td valign=\"top\" class=\"votelinks\"> <center> <a id=\"up_33584941\" href=\"vote?id=33584941&how=up&goto=front%3Fday%3D2022-11-13\"> <div class=\"votearrow\" title=\"upvote\"></div></a> </center></td> <td class=\"title\"><span class=\"titleline\"><a href=\"https://fathy.fr/html2svg\">Forking Chrome to turn HTML into SVG</a><span class=\"sitebit comhead\"> (<a href=\"from?site=fathy.fr\"><span class=\"sitestr\">fathy.fr</span></a>)</span></span></td> </tr>");
Elements elements = doc.select("#hnmain .athing");
for (Element element : elements) {
String title = element.select(".title").text();
String rank = element.select(".rank").text();
System.out.println(title + " -- "+rank);
}
| How to loop through this query using Jsoup? | I want to loop through the news table and get the title and rating of each row. I tried different options, but I canβt understand why the select method receives all the options at once.
I need to get each news block in a loop.
I used this way to get table link:
Elements elements = document.select("#hnmain > tbody > tr:nth-child(3) > td > table");
This query doesn't work in a loop because it gets all the elements at once. I need to get the elements sequentially. So that I can do like this:
List list = new ArrayList<>();
for (Element element: elements){
String title = element...
String rating = element...
list.add(title);
list.add(rating);
}
Sample data from html:
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr class="athing" id="33582264">
<td align="right" valign="top" class="title"><span class="rank">1.</span></td>
<td valign="top" class="votelinks">
<center>
<a id="up_33582264" href="vote?id=33582264&how=up&goto=front%3Fday%3D2022-11-13">
<div class="votearrow" title="upvote"></div></a>
</center></td>
<td class="title"><span class="titleline"><a href="https://upbase.io/">Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.</a><span class="sitebit comhead"> (<a href="from?site=upbase.io"><span class="sitestr">upbase.io</span></a>)</span></span></td>
</tr>
<tr>
<td colspan="2"></td>
<td class="subtext"><span class="subline"> <span class="score" id="score_33582264">632 points</span> by <a href="user?id=tonypham" class="hnuser">tonypham</a> <span class="age" title="2022-11-13T12:00:06"><a href="item?id=33582264">20 days ago</a></span> <span id="unv_33582264"></span> | <a href="hide?id=33582264&goto=front%3Fday%3D2022-11-13">hide</a> | <a href="item?id=33582264">456 comments</a> </span></td>
</tr>
<tr class="spacer" style="height:5px"></tr>
<tr class="athing" id="33584941">
<td align="right" valign="top" class="title"><span class="rank">2.</span></td>
<td valign="top" class="votelinks">
<center>
<a id="up_33584941" href="vote?id=33584941&how=up&goto=front%3Fday%3D2022-11-13">
<div class="votearrow" title="upvote"></div></a>
</center></td>
<td class="title"><span class="titleline"><a href="https://fathy.fr/html2svg">Forking Chrome to turn HTML into SVG</a><span class="sitebit comhead"> (<a href="from?site=fathy.fr"><span class="sitestr">fathy.fr</span></a>)</span></span></td>
</tr>
| [
"Here is an example of how you can loop through the news table using Jsoup:\n// First, select the table with the news\nElements elements = document.select(\"#hnmain > tbody > tr:nth-child(3) > td > table\");\n\n// Then, loop through the table\nfor (Element element: elements){\n// For each news item, select the title and rating\nString title = element.select(\".title a\").text();\nString rating = element.select(\".subtext .score\").text();\n// Print the title and rating of each news item\nSystem.out.println(\"Title: \" + title);\nSystem.out.println(\"Rating: \" + rating);\n}\n\nThis code should print the title and rating of each news item in the table.\nFor example, for the first news item in the sample data, it would print:\nTitle: Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.\nRating: 632 points\n",
"if I understand your question I think this code will work for you\nDocument doc = Jsoup.parse(\"<table border=\\\"0\\\" id=\\\"hnmain\\\" cellpadding=\\\"0\\\" cellspacing=\\\"0\\\"> <tbody> <tr class=\\\"athing\\\" id=\\\"33582264\\\"> <td align=\\\"right\\\" valign=\\\"top\\\" class=\\\"title\\\"><span class=\\\"rank\\\">1.</span></td> <td valign=\\\"top\\\" class=\\\"votelinks\\\"> <center> <a id=\\\"up_33582264\\\" href=\\\"vote?id=33582264&how=up&goto=front%3Fday%3D2022-11-13\\\"> <div class=\\\"votearrow\\\" title=\\\"upvote\\\"></div></a> </center></td> <td class=\\\"title\\\"><span class=\\\"titleline\\\"><a href=\\\"https://upbase.io/\\\">Show HN: I built my own PM tool after trying Trello, Asana, ClickUp, etc.</a><span class=\\\"sitebit comhead\\\"> (<a href=\\\"from?site=upbase.io\\\"><span class=\\\"sitestr\\\">upbase.io</span></a>)</span></span></td> </tr> <tr> <td colspan=\\\"2\\\"></td> <td class=\\\"subtext\\\"><span class=\\\"subline\\\"> <span class=\\\"score\\\" id=\\\"score_33582264\\\">632 points</span> by <a href=\\\"user?id=tonypham\\\" class=\\\"hnuser\\\">tonypham</a> <span class=\\\"age\\\" title=\\\"2022-11-13T12:00:06\\\"><a href=\\\"item?id=33582264\\\">20 days ago</a></span> <span id=\\\"unv_33582264\\\"></span> | <a href=\\\"hide?id=33582264&goto=front%3Fday%3D2022-11-13\\\">hide</a> | <a href=\\\"item?id=33582264\\\">456 comments</a> </span></td> </tr> <tr class=\\\"spacer\\\" style=\\\"height:5px\\\"></tr> <tr class=\\\"athing\\\" id=\\\"33584941\\\"> <td align=\\\"right\\\" valign=\\\"top\\\" class=\\\"title\\\"><span class=\\\"rank\\\">2.</span></td> <td valign=\\\"top\\\" class=\\\"votelinks\\\"> <center> <a id=\\\"up_33584941\\\" href=\\\"vote?id=33584941&how=up&goto=front%3Fday%3D2022-11-13\\\"> <div class=\\\"votearrow\\\" title=\\\"upvote\\\"></div></a> </center></td> <td class=\\\"title\\\"><span class=\\\"titleline\\\"><a href=\\\"https://fathy.fr/html2svg\\\">Forking Chrome to turn HTML into SVG</a><span class=\\\"sitebit comhead\\\"> (<a href=\\\"from?site=fathy.fr\\\"><span class=\\\"sitestr\\\">fathy.fr</span></a>)</span></span></td> </tr>\");\n Elements elements = doc.select(\"#hnmain .athing\");\n for (Element element : elements) {\n String title = element.select(\".title\").text();\n String rank = element.select(\".rank\").text();\n \n System.out.println(title + \" -- \"+rank);\n }\n\n"
] | [
0,
0
] | [] | [] | [
"java",
"jsoup",
"loops",
"parsing"
] | stackoverflow_0074671630_java_jsoup_loops_parsing.txt |
Q:
Before UPDATE Trigger PL/SQL
I have the following tables:
Battles - Name is PK
Name
B_date
Battle1
01-JAN-1989
Battle2
23-AUG-1996
Consequences - (Ship, Battle) is UK and Battle is FK to Battles
Ship
Battle
Result
ShipX
Battle1
unharmed
ShipX
Battle2
unharmed
I have to create a trigger that stops the updating of Result column to 'destroyed' if the ship participated in a battle that took place after the current battle. For example, I shouldn't be able to update the result to 'destroyed' in the row (ShipX, Battle1) in table Consequences, because ShipX also participated in Battle2 which took place after Battle1.
In order to check if ShipX has participated in other battles that took place after the current battle I created the following function:
CREATE OR REPLACE FUNCTION check_date_func (p_ship IN VARCHAR, p_battle IN VARCHAR) RETURN BOOLEAN IS
CURSOR battles_curs IS
SELECT c.ship, b.name, b.b_date FROM battles b JOIN consequences c ON (b.name = c.battle);
TYPE t_battles IS TABLE OF battles_curs%ROWTYPE INDEX BY BINARY_INTEGER;
battles_tab t_battles;
v_index BINARY_INTEGER := 0;
v_date DATE;
v_flag BOOLEAN;
BEGIN
SELECT b_date INTO v_date FROM battles b JOIN consequences c ON (b.name = c.battle) WHERE battle = p_battle AND ship = p_ship;
FOR record IN battles_curs LOOP
v_index := v_index + 1;
batalii_tab(v_index).ship := record.ship;
batalii_tab(v_index).name := record.name;
batalii_tab(v_index).b_date := record.b_date;
END LOOP;
FOR i IN battles_tab.FIRST..battles_tab.LAST LOOP
IF battles_tab(i).ship = p_ship AND battles_tab(i).name = p_battle AND battles_tab(i).b_date > v_date THEN
v_flag := TRUE;
RETURN v_flag;
ELSE
v_flag := FALSE;
RETURN v_flag;
END IF;
END LOOP;
END check_date_func;
The function runs with no errors.
After that I created the trigger where I call the function. I created a compound trigger in order to avoid the mutating table error.
CREATE OR REPLACE TRIGGER update_result_trigg
FOR UPDATE OF result ON consequences COMPOUND TRIGGER
TYPE t_consequences IS TABLE OF consequences%ROWTYPE INDEX BY BINARY_INTEGER;
consequences_tab t_consequences;
v_index BINARY_INTEGER := 0;
AFTER EACH ROW IS
BEGIN
v_index := v_index + 1;
consecinte_tab(v_index).ship := :NEW.ship;
consecinte_tab(v_index).battle := :NEW.battle;
consecinte_tab(v_index).result := :NEW.result;
END AFTER EACH ROW;
AFTER STATEMENT IS
BEGIN
FOR i IN consequences_tab.First..consequences_tab.LAST LOOP
IF check_date_func(:OLD.ship, :OLD.battle) = FALSE AND :NEW.result = 'destroyed' THEN
UPDATE consequences
SET result= :OLD.result
WHERE :OLD.ship= :NEW.ship AND :OLD.battle = :NEW.battle;
RAISE_APPLICATION_ERROR(-20500, 'Nu poti actualiza!');
END IF;
END LOOP;
END AFTER STATEMENT;
END;
The only problem is that I can't use :OLD and :NEW in AFTER STATEMENT. How can I fix this?
A:
You can use:
CREATE OR REPLACE TRIGGER update_result_trigg
FOR UPDATE OF result ON consequences
COMPOUND TRIGGER
TYPE t_consequences IS TABLE OF consequences%ROWTYPE;
v_cons t_consequences := t_consequences();
AFTER EACH ROW IS
BEGIN
IF :NEW.result = 'destroyed' THEN
v_cons.EXTEND;
v_cons(v_cons.COUNT).ship := :NEW.ship;
v_cons(v_cons.COUNT).battle := :NEW.battle;
v_cons(v_cons.COUNT).result := :NEW.result;
END IF;
END AFTER EACH ROW;
AFTER STATEMENT IS
v_rn PLS_INTEGER;
BEGIN
FOR i IN 1 .. v_cons.COUNT LOOP
SELECT rn
INTO v_rn
FROM (
SELECT c.battle,
ROW_NUMBER() OVER (ORDER BY b.b_date DESC) AS rn
FROM consequences c
INNER JOIN battles b
ON (c.battle = b.name)
WHERE c.ship = v_cons(i).ship
) c
WHERE battle = v_cons(i).battle;
IF v_rn > 1 THEN
RAISE_APPLICATION_ERROR(-20500, 'Nu poti actualiza!');
END IF;
END LOOP;
END AFTER STATEMENT;
END;
/
Which if you try:
UPDATE consequences
SET result = 'destroyed'
WHERE ship = 'ShipX'
AND battle = 'Battle1';
Then the output is:
ORA-20500: Nu poti actualiza!
ORA-06512: at "FIDDLE_XOXAMEWVYHYVRZLDYCFN.UPDATE_RESULT_TRIGG", line 30
ORA-04088: error during execution of trigger 'FIDDLE_XOXAMEWVYHYVRZLDYCFN.UPDATE_RESULT_TRIGG'
and because an exception was raised then the transaction is rolled back (you do not need to manually try to reset the values).
But if you use:
UPDATE consequences
SET result = 'destroyed'
WHERE ship = 'ShipX'
AND battle = 'Battle2';
Then the row is updated.
fiddle
| Before UPDATE Trigger PL/SQL | I have the following tables:
Battles - Name is PK
Name
B_date
Battle1
01-JAN-1989
Battle2
23-AUG-1996
Consequences - (Ship, Battle) is UK and Battle is FK to Battles
Ship
Battle
Result
ShipX
Battle1
unharmed
ShipX
Battle2
unharmed
I have to create a trigger that stops the updating of Result column to 'destroyed' if the ship participated in a battle that took place after the current battle. For example, I shouldn't be able to update the result to 'destroyed' in the row (ShipX, Battle1) in table Consequences, because ShipX also participated in Battle2 which took place after Battle1.
In order to check if ShipX has participated in other battles that took place after the current battle I created the following function:
CREATE OR REPLACE FUNCTION check_date_func (p_ship IN VARCHAR, p_battle IN VARCHAR) RETURN BOOLEAN IS
CURSOR battles_curs IS
SELECT c.ship, b.name, b.b_date FROM battles b JOIN consequences c ON (b.name = c.battle);
TYPE t_battles IS TABLE OF battles_curs%ROWTYPE INDEX BY BINARY_INTEGER;
battles_tab t_battles;
v_index BINARY_INTEGER := 0;
v_date DATE;
v_flag BOOLEAN;
BEGIN
SELECT b_date INTO v_date FROM battles b JOIN consequences c ON (b.name = c.battle) WHERE battle = p_battle AND ship = p_ship;
FOR record IN battles_curs LOOP
v_index := v_index + 1;
batalii_tab(v_index).ship := record.ship;
batalii_tab(v_index).name := record.name;
batalii_tab(v_index).b_date := record.b_date;
END LOOP;
FOR i IN battles_tab.FIRST..battles_tab.LAST LOOP
IF battles_tab(i).ship = p_ship AND battles_tab(i).name = p_battle AND battles_tab(i).b_date > v_date THEN
v_flag := TRUE;
RETURN v_flag;
ELSE
v_flag := FALSE;
RETURN v_flag;
END IF;
END LOOP;
END check_date_func;
The function runs with no errors.
After that I created the trigger where I call the function. I created a compound trigger in order to avoid the mutating table error.
CREATE OR REPLACE TRIGGER update_result_trigg
FOR UPDATE OF result ON consequences COMPOUND TRIGGER
TYPE t_consequences IS TABLE OF consequences%ROWTYPE INDEX BY BINARY_INTEGER;
consequences_tab t_consequences;
v_index BINARY_INTEGER := 0;
AFTER EACH ROW IS
BEGIN
v_index := v_index + 1;
consecinte_tab(v_index).ship := :NEW.ship;
consecinte_tab(v_index).battle := :NEW.battle;
consecinte_tab(v_index).result := :NEW.result;
END AFTER EACH ROW;
AFTER STATEMENT IS
BEGIN
FOR i IN consequences_tab.First..consequences_tab.LAST LOOP
IF check_date_func(:OLD.ship, :OLD.battle) = FALSE AND :NEW.result = 'destroyed' THEN
UPDATE consequences
SET result= :OLD.result
WHERE :OLD.ship= :NEW.ship AND :OLD.battle = :NEW.battle;
RAISE_APPLICATION_ERROR(-20500, 'Nu poti actualiza!');
END IF;
END LOOP;
END AFTER STATEMENT;
END;
The only problem is that I can't use :OLD and :NEW in AFTER STATEMENT. How can I fix this?
| [
"You can use:\nCREATE OR REPLACE TRIGGER update_result_trigg\n FOR UPDATE OF result ON consequences\nCOMPOUND TRIGGER\n TYPE t_consequences IS TABLE OF consequences%ROWTYPE;\n v_cons t_consequences := t_consequences();\nAFTER EACH ROW IS\nBEGIN\n IF :NEW.result = 'destroyed' THEN\n v_cons.EXTEND;\n v_cons(v_cons.COUNT).ship := :NEW.ship;\n v_cons(v_cons.COUNT).battle := :NEW.battle;\n v_cons(v_cons.COUNT).result := :NEW.result;\n END IF;\nEND AFTER EACH ROW;\nAFTER STATEMENT IS\n v_rn PLS_INTEGER;\nBEGIN\n FOR i IN 1 .. v_cons.COUNT LOOP\n SELECT rn\n INTO v_rn\n FROM (\n SELECT c.battle,\n ROW_NUMBER() OVER (ORDER BY b.b_date DESC) AS rn\n FROM consequences c\n INNER JOIN battles b\n ON (c.battle = b.name)\n WHERE c.ship = v_cons(i).ship\n ) c\n WHERE battle = v_cons(i).battle;\n \n IF v_rn > 1 THEN\n RAISE_APPLICATION_ERROR(-20500, 'Nu poti actualiza!');\n END IF;\n END LOOP;\nEND AFTER STATEMENT;\nEND;\n/\n\nWhich if you try:\nUPDATE consequences\nSET result = 'destroyed'\nWHERE ship = 'ShipX'\nAND battle = 'Battle1';\n\nThen the output is:\n\nORA-20500: Nu poti actualiza!\nORA-06512: at \"FIDDLE_XOXAMEWVYHYVRZLDYCFN.UPDATE_RESULT_TRIGG\", line 30\nORA-04088: error during execution of trigger 'FIDDLE_XOXAMEWVYHYVRZLDYCFN.UPDATE_RESULT_TRIGG'\n\n\nand because an exception was raised then the transaction is rolled back (you do not need to manually try to reset the values).\nBut if you use:\nUPDATE consequences\nSET result = 'destroyed'\nWHERE ship = 'ShipX'\nAND battle = 'Battle2';\n\nThen the row is updated.\nfiddle\n"
] | [
0
] | [] | [] | [
"oracle",
"plsql",
"triggers"
] | stackoverflow_0074671157_oracle_plsql_triggers.txt |
Q:
Blazor Server Dependency Injection Issue
I'm rather new to Blazor, but I am currently trying to get access to some classes from within a class library that I've created and deployed as a Nuget package. As background, the Nuget package is an Api library, which allows me to talk to a webservice (I don't know if this is relevant or not). However, every time I go to the page where I'm testing, the page never loads and instead I left looking at the browser loading circle until I navigate away or close the application. During my testing here, it seems like it's the @inject call of my interface into the Blazor component which is causing the issue as when I remove it and try to load the page normally, the page does so.
So to demonstrate what I have setup, here is where I've added the Singletons to the DI:
builder.Services.AddSingleton<IApiConfigHelper, ApiConfigHelper>();
builder.Services.AddSingleton<IApiHelper, ApiHelper>();
builder.Services.AddSingleton<ISystemEndpoint, SystemEndpoint>();
Then on the blazor page, I have the following declarations at the top of my page:
@using Library.Endpoints
@using Library.Models
@page "/"
@inject ISystemEndpoint _systemEndpoint
Now I am leaning towards is this something to do with the Nuget package and using it with DI. I have tested the library away from this project (In a console application) and can confirm it's working as it should.
I have also created a local class library as a test to, to see if I could inject a data access class into the page and I can confirm that this works without an issue, which suggests to me that DI is working, just not with my Nuget package.
I did have a look into CORS, given that the Nuget package is accessing an external domain, and setup the following simple CORS policy in the app:
builder.Services.AddCors(policy =>
{
policy.AddPolicy("OpenCorsPolicy", opt =>
opt.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
Which is added to the app after the AddRouting call like so:
app.UseCors("OpenCorsPolicy");
However again, this wasn't the solution so if anyone is able to point me in the right direction with where I may be going wrong with this or offer any advice, I would be most grateful.
EDIT 1 - Provides details @mason queried
Regarding SystemEndpoint, the constructor is being injected with 2 things, as below:
public SystemEndpoint(IApiHelper apiHelper, IOptions<UriConfigModel> uriOptions)
{
_apiHelper = apiHelper;
_uriOptions = uriOptions.Value;
}
My Nuget Library is dependant on the following:
Azure.Identity
Azure.Security.KeyVault.Secrets
Microsoft.AspNet.WebApi.Client
Microsoft.Extensisons.Options.ConfigurationExtensions
EDIT 2 - Doing some further testing with this I have added a simple Endpoint class to my Nuget library, which returns a string with a basic message, as well as returning the values of the 2 UriConfig properties as below. I added this test to 1) sanity check that my DI was working correctly, and 2) check the values that are being assigned from appsettings to my UriConfig Object.
public class TestEndpoint : ITestEndpoint
{
private readonly IOptions<UriConfigModel> _uriConfig;
public TestEndpoint(IOptions<UriConfigModel> uriConfig)
{
_uriConfig = uriConfig;
}
public string TestMethod()
{
return $"You have successfully called the test method\n\n{_uriConfig.Value.Release} / {_uriConfig.Value.Version}";
}
}
However when adding in the dependency of IApiHelper into the Ctor, the method then breaks and fails to load the page. Looking into ApiHeloer, the Ctor has a dependency being injected into it of IApiConfigHelper. Looking at the implementation, the Ctor of ApiConfigHelper is setting up the values and parameters of the HttpClient that should make the REST calls to the external Api.
Now I believe what is breaking the code at this point is a call I'm making to Azure Key Vault, via REST, to pull out the secret values to connect to the Api. The call to KeyVault is being orchestrated via the following method, making use of the Azure.Security.KeyVault.Secrets Nuget Package, however I assume that at the heart of it, it's making a REST call to Azure on my behalf:
private async Task<KeyVaultSecret> GetKeyVaultValue(string secretName = "")
{
try
{
if (_secretClient is not null)
{
var result = await _secretClient.GetSecretAsync(secretName);
return result.Value;
}
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
catch (Azure.RequestFailedException rfe)
{
Console.WriteLine(rfe.Message);
}
return new(secretName, "");
}
So that's where I stand with this at the moment. I still believe it could be down to CORS, as it seems to be falling over when making a call to an external service / domain, but I still can say 100%. As a closing thought, could it be something as simple as when I call call the above method, it's not being awaited????
A:
So after persisting with this it seems like the reason it was failing was down to "awaiting" the call to Azure KeyVault, which was happening indirectly via the constructor of ApiConfigHelper. The resulting method for getting KeyVault value is now:
private KeyVaultSecret GetKeyVaultValue(string secretName = "")
{
try
{
if (_secretClient is not null)
{
var result = _secretClient.GetSecret(secretName);
if (result is not null)
{
return result.Value;
}
}
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
catch (Azure.RequestFailedException rfe)
{
Console.WriteLine(rfe.Message);
}
return new(secretName, "");
}
I am now able to successfully make calls to my library and return values from the Api it interacts with.
I can also confirm that this IS NOT a CORS issue. Once I saw that removing the await was working, I then removed the CORS policy declarations from the service and the app in my Blazor's start-up code and everything continued to work without an issue.
As a final note, I must stress that this is only seems an issue when using the library with Blazor (possibly webApi projects) as I am able to use the library, awaiting the Azure call just fine in a console application.
| Blazor Server Dependency Injection Issue | I'm rather new to Blazor, but I am currently trying to get access to some classes from within a class library that I've created and deployed as a Nuget package. As background, the Nuget package is an Api library, which allows me to talk to a webservice (I don't know if this is relevant or not). However, every time I go to the page where I'm testing, the page never loads and instead I left looking at the browser loading circle until I navigate away or close the application. During my testing here, it seems like it's the @inject call of my interface into the Blazor component which is causing the issue as when I remove it and try to load the page normally, the page does so.
So to demonstrate what I have setup, here is where I've added the Singletons to the DI:
builder.Services.AddSingleton<IApiConfigHelper, ApiConfigHelper>();
builder.Services.AddSingleton<IApiHelper, ApiHelper>();
builder.Services.AddSingleton<ISystemEndpoint, SystemEndpoint>();
Then on the blazor page, I have the following declarations at the top of my page:
@using Library.Endpoints
@using Library.Models
@page "/"
@inject ISystemEndpoint _systemEndpoint
Now I am leaning towards is this something to do with the Nuget package and using it with DI. I have tested the library away from this project (In a console application) and can confirm it's working as it should.
I have also created a local class library as a test to, to see if I could inject a data access class into the page and I can confirm that this works without an issue, which suggests to me that DI is working, just not with my Nuget package.
I did have a look into CORS, given that the Nuget package is accessing an external domain, and setup the following simple CORS policy in the app:
builder.Services.AddCors(policy =>
{
policy.AddPolicy("OpenCorsPolicy", opt =>
opt.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});
Which is added to the app after the AddRouting call like so:
app.UseCors("OpenCorsPolicy");
However again, this wasn't the solution so if anyone is able to point me in the right direction with where I may be going wrong with this or offer any advice, I would be most grateful.
EDIT 1 - Provides details @mason queried
Regarding SystemEndpoint, the constructor is being injected with 2 things, as below:
public SystemEndpoint(IApiHelper apiHelper, IOptions<UriConfigModel> uriOptions)
{
_apiHelper = apiHelper;
_uriOptions = uriOptions.Value;
}
My Nuget Library is dependant on the following:
Azure.Identity
Azure.Security.KeyVault.Secrets
Microsoft.AspNet.WebApi.Client
Microsoft.Extensisons.Options.ConfigurationExtensions
EDIT 2 - Doing some further testing with this I have added a simple Endpoint class to my Nuget library, which returns a string with a basic message, as well as returning the values of the 2 UriConfig properties as below. I added this test to 1) sanity check that my DI was working correctly, and 2) check the values that are being assigned from appsettings to my UriConfig Object.
public class TestEndpoint : ITestEndpoint
{
private readonly IOptions<UriConfigModel> _uriConfig;
public TestEndpoint(IOptions<UriConfigModel> uriConfig)
{
_uriConfig = uriConfig;
}
public string TestMethod()
{
return $"You have successfully called the test method\n\n{_uriConfig.Value.Release} / {_uriConfig.Value.Version}";
}
}
However when adding in the dependency of IApiHelper into the Ctor, the method then breaks and fails to load the page. Looking into ApiHeloer, the Ctor has a dependency being injected into it of IApiConfigHelper. Looking at the implementation, the Ctor of ApiConfigHelper is setting up the values and parameters of the HttpClient that should make the REST calls to the external Api.
Now I believe what is breaking the code at this point is a call I'm making to Azure Key Vault, via REST, to pull out the secret values to connect to the Api. The call to KeyVault is being orchestrated via the following method, making use of the Azure.Security.KeyVault.Secrets Nuget Package, however I assume that at the heart of it, it's making a REST call to Azure on my behalf:
private async Task<KeyVaultSecret> GetKeyVaultValue(string secretName = "")
{
try
{
if (_secretClient is not null)
{
var result = await _secretClient.GetSecretAsync(secretName);
return result.Value;
}
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
}
catch (Azure.RequestFailedException rfe)
{
Console.WriteLine(rfe.Message);
}
return new(secretName, "");
}
So that's where I stand with this at the moment. I still believe it could be down to CORS, as it seems to be falling over when making a call to an external service / domain, but I still can say 100%. As a closing thought, could it be something as simple as when I call call the above method, it's not being awaited????
| [
"So after persisting with this it seems like the reason it was failing was down to \"awaiting\" the call to Azure KeyVault, which was happening indirectly via the constructor of ApiConfigHelper. The resulting method for getting KeyVault value is now:\nprivate KeyVaultSecret GetKeyVaultValue(string secretName = \"\")\n{\n try\n {\n if (_secretClient is not null)\n {\n var result = _secretClient.GetSecret(secretName);\n if (result is not null)\n {\n return result.Value;\n }\n }\n }\n catch (ArgumentException ae)\n {\n Console.WriteLine(ae.Message);\n }\n catch (Azure.RequestFailedException rfe)\n {\n Console.WriteLine(rfe.Message);\n }\n\n return new(secretName, \"\");\n}\n\nI am now able to successfully make calls to my library and return values from the Api it interacts with.\nI can also confirm that this IS NOT a CORS issue. Once I saw that removing the await was working, I then removed the CORS policy declarations from the service and the app in my Blazor's start-up code and everything continued to work without an issue.\nAs a final note, I must stress that this is only seems an issue when using the library with Blazor (possibly webApi projects) as I am able to use the library, awaiting the Azure call just fine in a console application.\n"
] | [
0
] | [] | [] | [
"blazor_server_side",
"dependency_injection",
"nuget_package"
] | stackoverflow_0074665753_blazor_server_side_dependency_injection_nuget_package.txt |
Q:
Value of of counter parameter not incrementing when an EventCallback is invoked
I have run into a strange problem which presevnts the value of a counter incrementing when the value is accessed as a paremeter via a component instance. The code should hopefully help describe the problem:
Index.razor
<MyComponent @ref="MyComponent1" Test=1 OnChange="OnChange"></MyComponent>
Index.razor.cs
namespace MyApp.Web.Pages.Transactions
{
public partial class List : ComponentBase
{
private MyComponent MyComponent1 { get; set; } = default!;
public void OnChange()
{
System.Console.WriteLine(MonthPicker1.Test);
}
}
}
MyComponent.razor
<button @onclick="@(() => OnClick()">press me</button>
MyComponent.razor.cs
namespace Accounting.Web.Components.MonthPicker
{
public partial class MonthPicker
{
[Parameter]
public EventCallback OnChange { get; set; } = default!;
[Parameter]
public int Test { get; set; } = 1;
private void OnClick(NavigationDirection direction)
{
Test++;
OnMonthPickerChange.InvokeAsync();
}
}
}
When the OnClick event is called in the child component, the value is Test should be incremented each time, but it always outputs the value 2 when the value is accessed through the component instance reference in index.razor.cs by invoking on the OnChange event callback. So it seems the value is increased only once.
If I remove the callback in MyComponent.razor.cs, then the value of Test will increment indefinitely as it should.
Why is the act of invoking the callback preventing Test from incereasing beyond the value of 2?
---- EDIT -----
Not long after posting the question it occurred to me that somehow the value of test is being reset so I remove passing the parameter through the component tag as follows:
<MyComponent @ref="MyComponent1" OnChange="OnChange"></MyComponent>
Notice the removal "Test=1" from the above tag. When doing this the value of Test is incremented indefinitely as expected.
So now the question, is what can I do to allow a default for value for Test to be passed as the parameter without having it reset when I invoke the callback?
A:
As you've identified, each time an event is raised the parameters are passed back down.
Try this:
namespace Accounting.Web.Components.MonthPicker
{
public partial class MonthPicker
{
[Parameter]
public EventCallback OnChange { get; set; } = default!;
[Parameter]
public int InitialValue { get; set; }
public int Test { get; private set; }
bool _initialised = false;
protected override void OnParametersSet()
{
if (!_initialised)
{
Test = InitialValue;
_initialized = true;
}
}
private void OnClick(NavigationDirection direction)
{
Test++;
OnChange.InvokeAsync();
}
}
}
And then set InitialValue Parameter from parent.
| Value of of counter parameter not incrementing when an EventCallback is invoked | I have run into a strange problem which presevnts the value of a counter incrementing when the value is accessed as a paremeter via a component instance. The code should hopefully help describe the problem:
Index.razor
<MyComponent @ref="MyComponent1" Test=1 OnChange="OnChange"></MyComponent>
Index.razor.cs
namespace MyApp.Web.Pages.Transactions
{
public partial class List : ComponentBase
{
private MyComponent MyComponent1 { get; set; } = default!;
public void OnChange()
{
System.Console.WriteLine(MonthPicker1.Test);
}
}
}
MyComponent.razor
<button @onclick="@(() => OnClick()">press me</button>
MyComponent.razor.cs
namespace Accounting.Web.Components.MonthPicker
{
public partial class MonthPicker
{
[Parameter]
public EventCallback OnChange { get; set; } = default!;
[Parameter]
public int Test { get; set; } = 1;
private void OnClick(NavigationDirection direction)
{
Test++;
OnMonthPickerChange.InvokeAsync();
}
}
}
When the OnClick event is called in the child component, the value is Test should be incremented each time, but it always outputs the value 2 when the value is accessed through the component instance reference in index.razor.cs by invoking on the OnChange event callback. So it seems the value is increased only once.
If I remove the callback in MyComponent.razor.cs, then the value of Test will increment indefinitely as it should.
Why is the act of invoking the callback preventing Test from incereasing beyond the value of 2?
---- EDIT -----
Not long after posting the question it occurred to me that somehow the value of test is being reset so I remove passing the parameter through the component tag as follows:
<MyComponent @ref="MyComponent1" OnChange="OnChange"></MyComponent>
Notice the removal "Test=1" from the above tag. When doing this the value of Test is incremented indefinitely as expected.
So now the question, is what can I do to allow a default for value for Test to be passed as the parameter without having it reset when I invoke the callback?
| [
"As you've identified, each time an event is raised the parameters are passed back down.\nTry this:\nnamespace Accounting.Web.Components.MonthPicker\n{\n public partial class MonthPicker\n {\n [Parameter]\n public EventCallback OnChange { get; set; } = default!;\n \n [Parameter]\n public int InitialValue { get; set; }\n\n public int Test { get; private set; }\n \n bool _initialised = false;\n\n protected override void OnParametersSet()\n {\n if (!_initialised)\n {\n Test = InitialValue;\n\n _initialized = true;\n }\n }\n \n private void OnClick(NavigationDirection direction)\n {\n Test++;\n OnChange.InvokeAsync();\n }\n }\n}\n\nAnd then set InitialValue Parameter from parent.\n"
] | [
1
] | [] | [] | [
"asp.net_blazor",
"blazor",
"blazor_server_side",
"blazor_webassembly",
"c#"
] | stackoverflow_0074671088_asp.net_blazor_blazor_blazor_server_side_blazor_webassembly_c#.txt |
Q:
How to inherit using declarations from base class
I declare types within class Config, pass this to base class Parent so Child can access.
The idea is each Child (there are many) won't have to keep declaring it's own using declarations, because they are already in Parent.
However, this doesn't compile. Child cannot see Parent::Type.
Is it possible to achieve this somehow?
template<class CONFIG>
struct Parent
{
using Type = typename CONFIG::Type;
// Plus a lot more types....
};
template<class CONFIG>
struct Child : public Parent<CONFIG>
{
void x(Type p){} // Compiler error. Cannot see Parent::Type
};
struct Config
{
using Type = int;
// Plus a lot more types....
};
int main()
{
Child<Config> c;
return 0;
}
A:
These are automatically inherited, but not visible. The reason these are not visible is, template base class is not considered during name lookup. It's not specific to types, same occurs with member variables. If you want them to be accessible, you need to bring them in scope:
struct Child : public Parent<CONFIG>
{
using Base = Parent<Config>;
using typename Base::Type;
void x(Type p){} // Compiler error. Cannot see Parent::Type
};
| How to inherit using declarations from base class | I declare types within class Config, pass this to base class Parent so Child can access.
The idea is each Child (there are many) won't have to keep declaring it's own using declarations, because they are already in Parent.
However, this doesn't compile. Child cannot see Parent::Type.
Is it possible to achieve this somehow?
template<class CONFIG>
struct Parent
{
using Type = typename CONFIG::Type;
// Plus a lot more types....
};
template<class CONFIG>
struct Child : public Parent<CONFIG>
{
void x(Type p){} // Compiler error. Cannot see Parent::Type
};
struct Config
{
using Type = int;
// Plus a lot more types....
};
int main()
{
Child<Config> c;
return 0;
}
| [
"These are automatically inherited, but not visible. The reason these are not visible is, template base class is not considered during name lookup. It's not specific to types, same occurs with member variables. If you want them to be accessible, you need to bring them in scope:\nstruct Child : public Parent<CONFIG>\n{\n using Base = Parent<Config>;\n using typename Base::Type;\n void x(Type p){} // Compiler error. Cannot see Parent::Type\n};\n\n"
] | [
1
] | [] | [] | [
"c++",
"crtp",
"templates",
"using"
] | stackoverflow_0074671783_c++_crtp_templates_using.txt |
Q:
FileNotFoundError: [Errno 2] No such file or directory: '1.pdf'
So I was making a PDF Merger using Python as I found it to be a good project for a beginner like me. I started off with using PyPDF4 and after all the hard work (not that hard) had been done I ran the program only to be greeted by "FileNotFoundError: [Errno 2] No such file or directory: '1.pdf'".
First question up, it DID find the filename that is in the specified directory and it does exist there. How did it find its name but still say it doesn't exist? Second Question, How do I get rid of this :<
I Use the # thingy to keep the code clean, don't mind if I do!
# <------Import Modules-------->
from PyPDF4 import PdfFileMerger
from os import listdir
# <-----------Misc------------->
filedirinput = input("Please enter a directory destination: ")
pdf = (".pdf")
# <-----Merge our Files------------------
manager = PdfFileMerger()# <------------| PdfFileMerger is now "manager" so that Karens can call it anytime XD
for files in listdir(filedirinput):# <--| For all the files in our Input Directory
if files.endswith(pdf):# <-------| Check if file ends with .pdf and move to next step
manager.append(files)# <--------| Merge all our files in the Directory using Manager (PdfFileMerger)
# <--------Output Time YE!!!--------->
outputname = input("Please enter your desired filename: ")
manager.write(outputname + pdf)
# <-----------Misc------------->
print(f"{outputname + pdf} was generated in {filedirinput}")
# NOTE This part is in development and you currently CANNOT mail somebody
# ALSO, I might turn all of this into a Tkinter GUI program :)
print("Do you want to email this to someone: Y/N")
yn = input("> ")
if yn == "N":
print("Thank You for Using PyDF Merger :)")
print("Made By NightMX!")
Me getting a Error: https://imgur.com/a/sXGpq7R
Have a Good Day!,
A:
You have to pass complete(absolute) path along with file name to manager.append(files) at line#12. The directory you got at Ln#6 is used to retrieve the list of files, however you have not used this while appending the files at Ln#12
A:
@venkat is correct in his answer. manager.append(files) does not contain the full path, and therefore cannot merge the files.
For your example, try
for files in listdir(filedirinput):
if files.endswith(pdf):
manager.append(filedirinput + str("\\") + files)
outputname = input("Please enter your desired filename: ")
merger.write(filedirinput + str("\\") + new_filename)
merger.close()
| FileNotFoundError: [Errno 2] No such file or directory: '1.pdf' | So I was making a PDF Merger using Python as I found it to be a good project for a beginner like me. I started off with using PyPDF4 and after all the hard work (not that hard) had been done I ran the program only to be greeted by "FileNotFoundError: [Errno 2] No such file or directory: '1.pdf'".
First question up, it DID find the filename that is in the specified directory and it does exist there. How did it find its name but still say it doesn't exist? Second Question, How do I get rid of this :<
I Use the # thingy to keep the code clean, don't mind if I do!
# <------Import Modules-------->
from PyPDF4 import PdfFileMerger
from os import listdir
# <-----------Misc------------->
filedirinput = input("Please enter a directory destination: ")
pdf = (".pdf")
# <-----Merge our Files------------------
manager = PdfFileMerger()# <------------| PdfFileMerger is now "manager" so that Karens can call it anytime XD
for files in listdir(filedirinput):# <--| For all the files in our Input Directory
if files.endswith(pdf):# <-------| Check if file ends with .pdf and move to next step
manager.append(files)# <--------| Merge all our files in the Directory using Manager (PdfFileMerger)
# <--------Output Time YE!!!--------->
outputname = input("Please enter your desired filename: ")
manager.write(outputname + pdf)
# <-----------Misc------------->
print(f"{outputname + pdf} was generated in {filedirinput}")
# NOTE This part is in development and you currently CANNOT mail somebody
# ALSO, I might turn all of this into a Tkinter GUI program :)
print("Do you want to email this to someone: Y/N")
yn = input("> ")
if yn == "N":
print("Thank You for Using PyDF Merger :)")
print("Made By NightMX!")
Me getting a Error: https://imgur.com/a/sXGpq7R
Have a Good Day!,
| [
"You have to pass complete(absolute) path along with file name to manager.append(files) at line#12. The directory you got at Ln#6 is used to retrieve the list of files, however you have not used this while appending the files at Ln#12\n",
"@venkat is correct in his answer. manager.append(files) does not contain the full path, and therefore cannot merge the files.\nFor your example, try\nfor files in listdir(filedirinput):\n if files.endswith(pdf):\n manager.append(filedirinput + str(\"\\\\\") + files)\n\noutputname = input(\"Please enter your desired filename: \")\nmerger.write(filedirinput + str(\"\\\\\") + new_filename)\nmerger.close()\n\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0067101966_python.txt |
Q:
Flowbite and Turbo Rails 7 with import map
Please help me, how to use Flowbite and Turbo Rails 7 with import map?
I use Flowbite v.1.5.3 as here https://flowbite.com/docs/getting-started/rails/
and tailwindcss
I found it https://github.com/themesberg/flowbite/issues/88 and i change "DOMContentLoaded" on "turbo:load" in dist/flowbite.js and in vendor/javascript/flowbite.js, but it's not work for me, my scripts work only if reload page
A:
Maybe a little bit later, but I did this
Go to app/javascript/application.js and add the following code.
import "flowbite"
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false
It is not my solution, but I works!.
| Flowbite and Turbo Rails 7 with import map | Please help me, how to use Flowbite and Turbo Rails 7 with import map?
I use Flowbite v.1.5.3 as here https://flowbite.com/docs/getting-started/rails/
and tailwindcss
I found it https://github.com/themesberg/flowbite/issues/88 and i change "DOMContentLoaded" on "turbo:load" in dist/flowbite.js and in vendor/javascript/flowbite.js, but it's not work for me, my scripts work only if reload page
| [
"Maybe a little bit later, but I did this\nGo to app/javascript/application.js and add the following code.\n\nimport \"flowbite\"\nimport { Turbo } from \"@hotwired/turbo-rails\"\nTurbo.session.drive = false\n\n\nIt is not my solution, but I works!.\n"
] | [
0
] | [] | [] | [
"flowbite",
"ruby_on_rails",
"turbo"
] | stackoverflow_0073964791_flowbite_ruby_on_rails_turbo.txt |
Q:
CSS : Scroll two div side by side independently
I have two columns and certain contents in both the columns.
I want a scroll to the each div when content is bigger.
I have fixed header and when I scroll then two divs is also scrolling.
I want only one div to be scrolled whenever I want to do so.
.b-r{
border-right: thin black solid;
}
.margin_top_600px{
margin-top:600px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70" >
<p class="margin_top_600px">
Left side Data
</p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70" >
<p class="margin_top_600px">
Right side Data
</p>
</div>
</div>
If I want to scroll for only left side data then only that div should scroll.
Any help would be great.
Thank you.
A:
You need to set height and overflow: auto; to .b-r:
.b-r{
border-right: thin black solid;
height: 100vh;
overflow: auto;
}
.margin_top_600px{
margin-top:600px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70" >
<p class="margin_top_600px">
Left side Data
</p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70" >
<p class="margin_top_600px">
Right side Data
</p>
</div>
</div>
To hide scrollbar you need to define one more wrapping div with overflow-y: scroll;. Outer div should have overflow: hidden;
scroll available with hidden scrollbars
.b-r{
border-right: thin black solid;
height: 100vh;
overflow: hidden;
}
.margin_top_600px{
margin-top:600px;
}
.scrll_hide {
float: right;
height: 100%;
width: calc(100% + 48px);
overflow-y: scroll;
margin: 0 -32px 0 0 !important;
box-sizing: border-box;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container-fluid">
<div class="row">
<div class="col-xs-6 b-r padding_bottom_70" >
<div class="scrll_hide">
<p class="margin_top_600px">
Left side Data
</p>
</div>
</div>
<div class="col-xs-6 b-r padding_bottom_70" >
<div class="scrll_hide">
<p class="margin_top_600px">
Right side Data
</p>
</div>
</div>
</div>
A:
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 my-content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam neque repellat libero facere, inventore natus! Laudantium laborum unde veritatis, nemo commodi ducimus quasi quam incidunt accusamus dolore asperiores optio repellendus!
</div>
<div class=" col-lg-6 col-md-6 col-sm-6 col-xs-6 my-content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem soluta corrupti, veniam sit, delectus sunt ipsum placeat recusandae eaque, voluptatum nemo optio cumque omnis veritatis quam itaque ab. Cupiditate, exercitationem?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo dolorem adipisci sint ducimus voluptates eveniet qui nisi error reiciendis laborum sed, neque officia aspernatur omnis dolore consequuntur, natus optio, mollitia!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa dignissimos enim expedita temporibus iure. Quam vitae autem laborum magnam optio nihil quisquam, est aliquid perspiciatis quia tempora cumque, enim vel.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero quis veritatis, alias dicta, commodi adipisci sint natus reiciendis. Atque eius labore alias cum ratione beatae provident voluptatum eum id mollitia.
</div>
</div>
.my-content{
height: 200px;
overflow: auto;
border: 1px solid #000;
}
Working Fiddle https://jsfiddle.net/DTcHh/29480/
A:
For all the React/Next JS and Tailwind Devs.
<div className="flex overflow-auto">
<div className="overflow-auto w-1/4">
<div className="flex flex-col w-full bg-red-200 h-[1000px]">
a
</div>
</div>
<div className="overflow-auto w-3/4">
<div className="flex flex-col w-full bg-blue-200 h-[1000px]">
a
</div>
</div>
</div>
| CSS : Scroll two div side by side independently | I have two columns and certain contents in both the columns.
I want a scroll to the each div when content is bigger.
I have fixed header and when I scroll then two divs is also scrolling.
I want only one div to be scrolled whenever I want to do so.
.b-r{
border-right: thin black solid;
}
.margin_top_600px{
margin-top:600px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70" >
<p class="margin_top_600px">
Left side Data
</p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70" >
<p class="margin_top_600px">
Right side Data
</p>
</div>
</div>
If I want to scroll for only left side data then only that div should scroll.
Any help would be great.
Thank you.
| [
"You need to set height and overflow: auto; to .b-r:\n\n\n.b-r{\r\n border-right: thin black solid;\r\n height: 100vh;\r\n overflow: auto;\r\n}\r\n\r\n.margin_top_600px{\r\n margin-top:600px;\r\n}\n<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\r\n\r\n<div class=\"row\">\r\n<div class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70\" >\r\n <p class=\"margin_top_600px\">\r\n Left side Data\r\n </p>\r\n \r\n</div>\r\n\r\n<div class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6 b-r padding_bottom_70\" >\r\n <p class=\"margin_top_600px\">\r\n Right side Data\r\n </p>\r\n \r\n</div>\r\n</div>\n\n\n\nTo hide scrollbar you need to define one more wrapping div with overflow-y: scroll;. Outer div should have overflow: hidden;\nscroll available with hidden scrollbars\n\n\n.b-r{\r\n border-right: thin black solid;\r\n height: 100vh;\r\n overflow: hidden;\r\n}\r\n.margin_top_600px{\r\n margin-top:600px;\r\n}\r\n.scrll_hide {\r\n float: right;\r\n height: 100%;\r\n width: calc(100% + 48px);\r\n overflow-y: scroll;\r\n margin: 0 -32px 0 0 !important;\r\n box-sizing: border-box;\r\n}\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">\r\n<div class=\"container-fluid\">\r\n <div class=\"row\">\r\n <div class=\"col-xs-6 b-r padding_bottom_70\" >\r\n <div class=\"scrll_hide\">\r\n <p class=\"margin_top_600px\">\r\n Left side Data\r\n </p>\r\n </div>\r\n </div>\r\n\r\n <div class=\"col-xs-6 b-r padding_bottom_70\" >\r\n <div class=\"scrll_hide\">\r\n <p class=\"margin_top_600px\">\r\n Right side Data\r\n </p>\r\n </div>\r\n </div>\r\n </div>\n\n\n\n",
" <div class=\"row\">\n <div class=\"col-lg-6 col-md-6 col-sm-6 col-xs-6 my-content\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam neque repellat libero facere, inventore natus! Laudantium laborum unde veritatis, nemo commodi ducimus quasi quam incidunt accusamus dolore asperiores optio repellendus!\n </div>\n <div class=\" col-lg-6 col-md-6 col-sm-6 col-xs-6 my-content\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit. Exercitationem soluta corrupti, veniam sit, delectus sunt ipsum placeat recusandae eaque, voluptatum nemo optio cumque omnis veritatis quam itaque ab. Cupiditate, exercitationem?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quo dolorem adipisci sint ducimus voluptates eveniet qui nisi error reiciendis laborum sed, neque officia aspernatur omnis dolore consequuntur, natus optio, mollitia!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa dignissimos enim expedita temporibus iure. Quam vitae autem laborum magnam optio nihil quisquam, est aliquid perspiciatis quia tempora cumque, enim vel.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero quis veritatis, alias dicta, commodi adipisci sint natus reiciendis. Atque eius labore alias cum ratione beatae provident voluptatum eum id mollitia.\n </div>\n </div>\n\n\n.my-content{\n height: 200px;\n overflow: auto;\n border: 1px solid #000;\n}\n\nWorking Fiddle https://jsfiddle.net/DTcHh/29480/\n",
"For all the React/Next JS and Tailwind Devs.\n<div className=\"flex overflow-auto\">\n \n <div className=\"overflow-auto w-1/4\">\n <div className=\"flex flex-col w-full bg-red-200 h-[1000px]\">\n a\n </div>\n </div>\n\n <div className=\"overflow-auto w-3/4\">\n <div className=\"flex flex-col w-full bg-blue-200 h-[1000px]\">\n a\n </div>\n </div>\n\n</div>\n\n"
] | [
4,
2,
0
] | [] | [] | [
"css",
"html",
"scrollbar"
] | stackoverflow_0042105751_css_html_scrollbar.txt |
Q:
How to plot learning curves in k-fold cross validation settings?
I would like to plot learning curves for diagnosing my approach in a 5 fold cross-validation process.
My first issue is if the learning curve should plot the loss of training and validation or the loss of training and testing. I found both approaches in the literature.
The second issue is how to plot the curves in cross-validation settings. Plotting learning curves when we have a fixed split of the data is straightforward, but in k-fold cross-validation settings, actually, we have k different outputs that should be summarized. And I don't know how to do this.
Just as a reference. In this link, the author plots learning curves with a fixed split of the data, and plots training vs validation.
https://machinelearningmastery.com/learning-curves-for-diagnosing-machine-learning-model-performance/
On the other hand, in this link, they present an approach for summarizing reults of k-folds, but using training and test folds instead of using validation.
https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py
It is not clear to me which approach should I use.
Best regards.
A:
In general, it is best to use learning curves to diagnose the performance of a machine learning model by plotting the training and validation losses or accuracies (depending on the evaluation metric you are using) as a function of the number of training examples. In the case of k-fold cross-validation, one common approach is to average the learning curves from each of the k folds, and then plot the average training and validation losses or accuracies as a function of the number of training examples. This will give you a sense of how the model is performing on average across all k folds, and can help you diagnose any issues with the model.
Here is an example of how you might go about plotting learning curves in k-fold cross-validation using the scikit-learn library in Python:
# First, import the necessary libraries
from sklearn.model_selection import learning_curve
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt
# Next, define your machine learning model and the dataset
model = ... # define your model here
X = ... # define your dataset features here
y = ... # define your dataset labels here
# Then, define the number of folds for k-fold cross-validation
n_folds = 5
# Define the training sizes and corresponding train/validation scores
train_sizes, train_scores, val_scores = learning_curve(model, X, y, cv=n_folds,
train_sizes=np.linspace(0.1, 1.0, 10),
scoring='accuracy')
# Compute the average training and validation scores across all folds
train_scores_mean = np.mean(train_scores, axis=1)
val_scores_mean = np.mean(val_scores, axis=1)
# Plot the learning curves
plt.plot(train_sizes, train_scores_mean, label='Training score')
plt.plot(train_sizes, val_scores_mean, label='Validation score')
plt.xlabel('Training size')
plt.ylabel('Accuracy')
plt.title('Learning curves')
plt.legend(loc='best')
plt.show()
In this example, we use the learning_curve() function from scikit-learn to compute the train and validation scores for different training sizes, using k-fold cross-validation with k = 5. We then average the scores across all folds, and plot the average training and validation scores as a function of the training size.
I hope this helps! Let me know if you have any other questions.
| How to plot learning curves in k-fold cross validation settings? | I would like to plot learning curves for diagnosing my approach in a 5 fold cross-validation process.
My first issue is if the learning curve should plot the loss of training and validation or the loss of training and testing. I found both approaches in the literature.
The second issue is how to plot the curves in cross-validation settings. Plotting learning curves when we have a fixed split of the data is straightforward, but in k-fold cross-validation settings, actually, we have k different outputs that should be summarized. And I don't know how to do this.
Just as a reference. In this link, the author plots learning curves with a fixed split of the data, and plots training vs validation.
https://machinelearningmastery.com/learning-curves-for-diagnosing-machine-learning-model-performance/
On the other hand, in this link, they present an approach for summarizing reults of k-folds, but using training and test folds instead of using validation.
https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py
It is not clear to me which approach should I use.
Best regards.
| [
"In general, it is best to use learning curves to diagnose the performance of a machine learning model by plotting the training and validation losses or accuracies (depending on the evaluation metric you are using) as a function of the number of training examples. In the case of k-fold cross-validation, one common approach is to average the learning curves from each of the k folds, and then plot the average training and validation losses or accuracies as a function of the number of training examples. This will give you a sense of how the model is performing on average across all k folds, and can help you diagnose any issues with the model.\nHere is an example of how you might go about plotting learning curves in k-fold cross-validation using the scikit-learn library in Python:\n# First, import the necessary libraries\nfrom sklearn.model_selection import learning_curve\nfrom sklearn.model_selection import KFold\nimport matplotlib.pyplot as plt\n\n# Next, define your machine learning model and the dataset\nmodel = ... # define your model here\nX = ... # define your dataset features here\ny = ... # define your dataset labels here\n\n# Then, define the number of folds for k-fold cross-validation\nn_folds = 5\n\n# Define the training sizes and corresponding train/validation scores\ntrain_sizes, train_scores, val_scores = learning_curve(model, X, y, cv=n_folds,\n train_sizes=np.linspace(0.1, 1.0, 10),\n scoring='accuracy')\n\n# Compute the average training and validation scores across all folds\ntrain_scores_mean = np.mean(train_scores, axis=1)\nval_scores_mean = np.mean(val_scores, axis=1)\n\n# Plot the learning curves\nplt.plot(train_sizes, train_scores_mean, label='Training score')\nplt.plot(train_sizes, val_scores_mean, label='Validation score')\nplt.xlabel('Training size')\nplt.ylabel('Accuracy')\nplt.title('Learning curves')\nplt.legend(loc='best')\nplt.show()\n\nIn this example, we use the learning_curve() function from scikit-learn to compute the train and validation scores for different training sizes, using k-fold cross-validation with k = 5. We then average the scores across all folds, and plot the average training and validation scores as a function of the training size.\nI hope this helps! Let me know if you have any other questions.\n"
] | [
1
] | [] | [] | [
"machine_learning",
"validation"
] | stackoverflow_0074669126_machine_learning_validation.txt |
Q:
Avoiding long word breaks
I have an icon button with an icon and the title. The title of the button is coming from API which is a combination of two words or sometimes more than two words. i.e Chinese Restaurants or Mexican restaurants. Sometimes, it breaks the word Restaurant if the name is too big and other time it also breaks the name as well. So is there any way to fix that so that I can see the full name without breaking the word? I tried using it.
textOverflow: TextOverflow.ellipsis,
and also tried max line to two/three. but I am not getting the desired result.
on large screen its working fine i am having problems only on small devices.
Any help or suggestions on that? thanks.
IconButton(
icon: Icon(Icon.resutaurant),
title: restaurantname,
textOverflow: TextOverflow.ellipsis,
onPressed: () {},
),
A:
If the text is too long for the available space, you will need to decrease the font size. This can be done manually via calculating the necessary space with a TextPainter, or you can chose a readily available package such as auto_size_text to manage that for you.
In its most basic form, it can be used like this
AutoSizeText(
'A really long String',
style: TextStyle(fontSize: 30),
maxLines: 2,
)
The style argument is used to set the font when enough space is available. A "target font size" if you want to call it that way.
There are a lot of customisation options that are illustrated in the Github repository.
The animation below taken from above-linked GitHub repo gives a nice visual representation of the effect that auto sizing has on your text. When it comes to the UX question of text truncation vs font size adaption, this question can serve as an introduction to the topic.
| Avoiding long word breaks | I have an icon button with an icon and the title. The title of the button is coming from API which is a combination of two words or sometimes more than two words. i.e Chinese Restaurants or Mexican restaurants. Sometimes, it breaks the word Restaurant if the name is too big and other time it also breaks the name as well. So is there any way to fix that so that I can see the full name without breaking the word? I tried using it.
textOverflow: TextOverflow.ellipsis,
and also tried max line to two/three. but I am not getting the desired result.
on large screen its working fine i am having problems only on small devices.
Any help or suggestions on that? thanks.
IconButton(
icon: Icon(Icon.resutaurant),
title: restaurantname,
textOverflow: TextOverflow.ellipsis,
onPressed: () {},
),
| [
"If the text is too long for the available space, you will need to decrease the font size. This can be done manually via calculating the necessary space with a TextPainter, or you can chose a readily available package such as auto_size_text to manage that for you.\nIn its most basic form, it can be used like this\nAutoSizeText(\n 'A really long String',\n style: TextStyle(fontSize: 30),\n maxLines: 2,\n)\n\nThe style argument is used to set the font when enough space is available. A \"target font size\" if you want to call it that way.\nThere are a lot of customisation options that are illustrated in the Github repository.\nThe animation below taken from above-linked GitHub repo gives a nice visual representation of the effect that auto sizing has on your text. When it comes to the UX question of text truncation vs font size adaption, this question can serve as an introduction to the topic.\n\n"
] | [
2
] | [] | [] | [
"flutter",
"iconbutton",
"word_wrap"
] | stackoverflow_0074671601_flutter_iconbutton_word_wrap.txt |
Q:
nginx configuration to load files without trailing slash no redirect
I want nginx to run /filename rendered as html file, /folder/ as folder (I mean loading /folder/index.html), and /filename.html as html file.
With default setup /filename not working. When I put a file as /filename to the server, it downloads the file.
I dont want any redirects, just load the files without trailing slash.
My current setup is
location / {
try_files $uri @proxy;
}
A:
Try adding default_type text/html; to your server configuration.
Details of my test:
server {
server_name www.example.com;
root /var/www/example.com;
default_type text/html;
}
Test directory structure:
βββ afile
βββ afile.html
βββ afolder
Β Β βββ index.html
afile:
<html>
<b>html with no extension</b>
</html>
afile.html:
<html>
<b>html with an html extension</b>
</html>
afolder/index.html
<html>
<b>index.html</b>
</html>
| nginx configuration to load files without trailing slash no redirect | I want nginx to run /filename rendered as html file, /folder/ as folder (I mean loading /folder/index.html), and /filename.html as html file.
With default setup /filename not working. When I put a file as /filename to the server, it downloads the file.
I dont want any redirects, just load the files without trailing slash.
My current setup is
location / {
try_files $uri @proxy;
}
| [
"Try adding default_type text/html; to your server configuration.\nDetails of my test:\nserver {\n server_name www.example.com;\n root /var/www/example.com;\n\n default_type text/html;\n}\n\nTest directory structure:\n\nβββ afile\nβββ afile.html\nβββ afolder\n Β Β βββ index.html\n\nafile:\n<html>\n<b>html with no extension</b>\n</html>\n\nafile.html:\n<html>\n<b>html with an html extension</b>\n</html>\n\nafolder/index.html\n<html>\n<b>index.html</b>\n</html>\n\n"
] | [
0
] | [] | [] | [
"nginx",
"nginx_config"
] | stackoverflow_0074670149_nginx_nginx_config.txt |
Q:
NOT SUPPORTED: keyword "id", use "$id" for schema ID : TSLint (ng add @angular-eslint/schematics)
I am upgrading my Angular 10 application to Angular 13. I did well with other compatibilities of dependencies. The project is compiling and working fine. Now the time for TSLint I tried to update the lint with the below command.
ng add @angular-eslint/schematics
But getting the error message:
An unhandled exception occurred: NOT SUPPORTED: keyword "id", use "$id" for schema ID
A:
ng add @angular-eslint/schematics@next
This worked for me
github.com/angular-eslint/angular-eslint/issues/790.
A:
I solved the problem downgrading angular cli version to 12
A:
It seams that a lot of packages throw this error. I had the same error when adding NgRx store. It looks like that installing the latest version of the packages usually fix the issue:
ng add package_name/@latest
A:
I faced the same issue in Angular 14, IONIC 6 project while generating pages/components . And resolved it by replacing id with $id manually on following paths:
node_modules > @Ionic > angular-toolkit > schematics > page > schema.json > replace id with $id on line 3.
node_modules > @Ionic > angular-toolkit > schematics > component > schema.json > replace id with $id on line 3.
A:
I had the same problem. I could fix it by by upgrading angular/universal to the same version as my angular version is.
A:
I had a conflict where the third-party package I was using had been replaced by an official one, but for some reason I had both of them in my package.json file The real issue though was that the angular.json file was using the older builder instead of the newer one.
I removed the package and used ng add to add the new package via its schematic, and after that things started working properly.
A:
It appear while I'm using angular 14, after upgrading angular 15(before that reinstalling angular cli) resolve problem for me.
A:
Install manually the version of @angular/pwa corresponding to your version of angular and then run "ng add @angular/pwa"
A:
For eslint:
ng add @angular-eslint/schematics@12 for angular 12
ng add @angular-eslint/schematics@13 for angular 13
ng add @angular-eslint/schematics@14 for angular 14
| NOT SUPPORTED: keyword "id", use "$id" for schema ID : TSLint (ng add @angular-eslint/schematics) | I am upgrading my Angular 10 application to Angular 13. I did well with other compatibilities of dependencies. The project is compiling and working fine. Now the time for TSLint I tried to update the lint with the below command.
ng add @angular-eslint/schematics
But getting the error message:
An unhandled exception occurred: NOT SUPPORTED: keyword "id", use "$id" for schema ID
| [
"ng add @angular-eslint/schematics@next\n\nThis worked for me\ngithub.com/angular-eslint/angular-eslint/issues/790.\n",
"I solved the problem downgrading angular cli version to 12\n\n",
"It seams that a lot of packages throw this error. I had the same error when adding NgRx store. It looks like that installing the latest version of the packages usually fix the issue:\nng add package_name/@latest\n\n",
"I faced the same issue in Angular 14, IONIC 6 project while generating pages/components . And resolved it by replacing id with $id manually on following paths:\n\nnode_modules > @Ionic > angular-toolkit > schematics > page > schema.json > replace id with $id on line 3.\n\nnode_modules > @Ionic > angular-toolkit > schematics > component > schema.json > replace id with $id on line 3.\n\n\n",
"I had the same problem. I could fix it by by upgrading angular/universal to the same version as my angular version is.\n",
"I had a conflict where the third-party package I was using had been replaced by an official one, but for some reason I had both of them in my package.json file The real issue though was that the angular.json file was using the older builder instead of the newer one.\nI removed the package and used ng add to add the new package via its schematic, and after that things started working properly.\n",
"It appear while I'm using angular 14, after upgrading angular 15(before that reinstalling angular cli) resolve problem for me.\n",
"Install manually the version of @angular/pwa corresponding to your version of angular and then run \"ng add @angular/pwa\"\n",
"For eslint:\nng add @angular-eslint/schematics@12 for angular 12\nng add @angular-eslint/schematics@13 for angular 13\nng add @angular-eslint/schematics@14 for angular 14\n"
] | [
23,
11,
5,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"angular",
"lint",
"node.js"
] | stackoverflow_0069895552_angular_lint_node.js.txt |
Q:
How do you provide an error when an invalid input is provided ie. (a color other than purple or sky blue) or a number
while True:
try:
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
user_info = {"color2": color1, "color2": color2,}
except ValueError:
print("Choose a valid input please...")
continue
else:
break
Trying to get it to give an error and restart the loop but its not working.
A:
To check if the input is valid, you can use an if statement inside the try block to check if the input matches the expected colors. If the input is not valid, you can raise a ValueError to indicate that there was an issue with the input. Here is an example of how you can do this:
while True:
try:
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
if color1 not in ["purple", "sky blue"]:
raise ValueError("Invalid input for color1: {}".format(color1))
if color2 not in ["white", "yellow", "pink"]:
raise ValueError("Invalid input for color2: {}".format(color2))
user_info = {"color2": color1, "color2": color2,}
except ValueError as error:
print("Error: {}".format(error))
continue
else:
break
This code will check if the input for color1 is either "purple" or "sky blue", and if the input for color2 is either "white", "yellow", or "pink". If the input is not valid, a ValueError is raised with a message indicating which color had an invalid input. The except block will catch this error and print the error message, then continue the loop to prompt for input again. If the input is valid, the loop will break and the program will continue. I hope this helps. Feel free to ask if you have any other questions.
A:
That works:
while True:
try:
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
user_info = {"color2": color1, "color2": color2,}
valid_input1 = ['purple', 'sky blue']
valid_input2 = ['white', 'yellow', 'pink']
if color1 not in valid_input1 or color2 not in valid_input2:
raise ValueError
except ValueError:
print("Choose a valid input please...")
continue
else:
break
You could also do something like this:
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
user_info = {"color2": color1, "color2": color2,}
valid_input1 = ['purple', 'sky blue']
valid_input2 = ['white', 'yellow', 'pink']
while color1 not in valid_input1 or color2 not in valid_input2:
print("Choose a valid input please...")
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
A:
You aren't raising ValueError, you can change your code to check for invalid input using an if statement for each input:
while True:
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
user_info = {"color2": color1, "color2": color2,}
if color1 not in ["purple", "sky blue"] or color2 not in ["yellow", "pink"]:
print("Choose a valid input please...")
continue
break
Also if you are using Python 3, then input returns a string, so passing it to str isn't needed.
| How do you provide an error when an invalid input is provided ie. (a color other than purple or sky blue) or a number | while True:
try:
color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip()
color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip()
user_info = {"color2": color1, "color2": color2,}
except ValueError:
print("Choose a valid input please...")
continue
else:
break
Trying to get it to give an error and restart the loop but its not working.
| [
"To check if the input is valid, you can use an if statement inside the try block to check if the input matches the expected colors. If the input is not valid, you can raise a ValueError to indicate that there was an issue with the input. Here is an example of how you can do this:\nwhile True:\n try:\n color1 = str(input(\"What should the color of the broken window be, Purple or Sky Blue? > \")).lower().strip()\n color2 = str(input(\"What should the color of the broken window, white Yellow or Pink? > \")).lower().strip()\n if color1 not in [\"purple\", \"sky blue\"]:\n raise ValueError(\"Invalid input for color1: {}\".format(color1))\n if color2 not in [\"white\", \"yellow\", \"pink\"]:\n raise ValueError(\"Invalid input for color2: {}\".format(color2))\n user_info = {\"color2\": color1, \"color2\": color2,}\n except ValueError as error:\n print(\"Error: {}\".format(error))\n continue\n else:\n break\n\nThis code will check if the input for color1 is either \"purple\" or \"sky blue\", and if the input for color2 is either \"white\", \"yellow\", or \"pink\". If the input is not valid, a ValueError is raised with a message indicating which color had an invalid input. The except block will catch this error and print the error message, then continue the loop to prompt for input again. If the input is valid, the loop will break and the program will continue. I hope this helps. Feel free to ask if you have any other questions.\n",
"That works:\nwhile True:\n try:\n color1 = str(input(\"What should the color of the broken window be, Purple or Sky Blue? > \")).lower().strip()\n color2 = str(input(\"What should the color of the broken window, white Yellow or Pink? > \")).lower().strip()\n user_info = {\"color2\": color1, \"color2\": color2,}\n valid_input1 = ['purple', 'sky blue']\n valid_input2 = ['white', 'yellow', 'pink']\n if color1 not in valid_input1 or color2 not in valid_input2:\n raise ValueError\n except ValueError:\n print(\"Choose a valid input please...\")\n continue\n else:\n break\n\nYou could also do something like this:\n\ncolor1 = str(input(\"What should the color of the broken window be, Purple or Sky Blue? > \")).lower().strip()\ncolor2 = str(input(\"What should the color of the broken window, white Yellow or Pink? > \")).lower().strip()\nuser_info = {\"color2\": color1, \"color2\": color2,}\n\nvalid_input1 = ['purple', 'sky blue']\nvalid_input2 = ['white', 'yellow', 'pink']\n\nwhile color1 not in valid_input1 or color2 not in valid_input2:\n print(\"Choose a valid input please...\")\n color1 = str(input(\"What should the color of the broken window be, Purple or Sky Blue? > \")).lower().strip()\n color2 = str(input(\"What should the color of the broken window, white Yellow or Pink? > \")).lower().strip()\n\n",
"You aren't raising ValueError, you can change your code to check for invalid input using an if statement for each input:\nwhile True:\n color1 = str(input(\"What should the color of the broken window be, Purple or Sky Blue? > \")).lower().strip()\n color2 = str(input(\"What should the color of the broken window, white Yellow or Pink? > \")).lower().strip()\n user_info = {\"color2\": color1, \"color2\": color2,}\n if color1 not in [\"purple\", \"sky blue\"] or color2 not in [\"yellow\", \"pink\"]:\n print(\"Choose a valid input please...\")\n continue\n break\n\nAlso if you are using Python 3, then input returns a string, so passing it to str isn't needed.\n"
] | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074671719_python.txt |
Q:
python how can I convert shap values to probability increase/decreases?
Issue on shap's repo: https://github.com/slundberg/shap/issues/2783
So currently, I know how to convert the base (expected) value from log odds to probability, with
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_train)
odds = np.exp(explainer.expected_value)
odds / (1 + odds)
This works fine, but the problem comes when I try and convert each individual shap value to a probability increase/decrease. That formula doesn't work, so I'm wondering how I can get the percent increase/decrease that each feature contributes
Basically, what percent do each of the lengths (like the length I annotated in red on the picture) take up?
I'm looking for a discrete number that corresponds to the percent increase/decrease for the bar of each feature (in probability, not log odds)
# this generates the plot
shap.force_plot(
explainer.expected_value,
shap_values[1, :],
X_train.iloc[1, :],
link='logit'
)
A:
I think I may have found the answer, not sure if it's correct because the only way to compare is by visual approximation, but here is what I came up with. If anyone could try it out and determine is the calculation is off, that would be amazing!
First, we have to create a helper function to convert log odds to probabilities
def lo_to_prob(x):
odds = np.exp(x)
return odds / (1 + odds)
Set up our shap
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_train)
This is the conversion formula I found
# this is the row that we want to find the shap outcomes for
observation = 0
# this is the column that we want to find the percent change for
column_num = 2
# this formula gives us the outcome probability number
shap_outcome_val = lo_to_prob(
explainer.expected_value + shap_values[observation, :].sum()
)
# this give us the shap outcome value, without the single column
shap_outcome_minus_one_column = lo_to_prob(
explainer.expected_value + shap_values[observation, :].sum() - shap_values[observation, :][column_num]
)
# simply subtract the 2 probabilities to get the pct increase that the one column provides
pct_change = shap_outcome_val - shap_outcome_minus_one_column
pct_change
Check the graph to see if the length of the bar of the column we're interested in, is about the length that we get from the calculation
shap.force_plot(
explainer.expected_value,
shap_values[observation, :],
X_train.iloc[observation, :],
link='logit'
)
Again, not sure if this is 100% correct, as the only way to verify is visually. It looks close tho. Try it out and let me know
| python how can I convert shap values to probability increase/decreases? | Issue on shap's repo: https://github.com/slundberg/shap/issues/2783
So currently, I know how to convert the base (expected) value from log odds to probability, with
explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(X_train)
odds = np.exp(explainer.expected_value)
odds / (1 + odds)
This works fine, but the problem comes when I try and convert each individual shap value to a probability increase/decrease. That formula doesn't work, so I'm wondering how I can get the percent increase/decrease that each feature contributes
Basically, what percent do each of the lengths (like the length I annotated in red on the picture) take up?
I'm looking for a discrete number that corresponds to the percent increase/decrease for the bar of each feature (in probability, not log odds)
# this generates the plot
shap.force_plot(
explainer.expected_value,
shap_values[1, :],
X_train.iloc[1, :],
link='logit'
)
| [
"I think I may have found the answer, not sure if it's correct because the only way to compare is by visual approximation, but here is what I came up with. If anyone could try it out and determine is the calculation is off, that would be amazing!\nFirst, we have to create a helper function to convert log odds to probabilities\ndef lo_to_prob(x):\n odds = np.exp(x)\n return odds / (1 + odds)\n\nSet up our shap\nexplainer = shap.TreeExplainer(model)\nshap_values = explainer.shap_values(X_train)\n\nThis is the conversion formula I found\n# this is the row that we want to find the shap outcomes for\nobservation = 0\n\n# this is the column that we want to find the percent change for\ncolumn_num = 2\n\n# this formula gives us the outcome probability number\nshap_outcome_val = lo_to_prob(\n explainer.expected_value + shap_values[observation, :].sum()\n)\n\n# this give us the shap outcome value, without the single column\nshap_outcome_minus_one_column = lo_to_prob(\n explainer.expected_value + shap_values[observation, :].sum() - shap_values[observation, :][column_num]\n)\n\n# simply subtract the 2 probabilities to get the pct increase that the one column provides\npct_change = shap_outcome_val - shap_outcome_minus_one_column\npct_change\n\nCheck the graph to see if the length of the bar of the column we're interested in, is about the length that we get from the calculation\nshap.force_plot(\n explainer.expected_value,\n shap_values[observation, :],\n X_train.iloc[observation, :],\n link='logit'\n)\n\nAgain, not sure if this is 100% correct, as the only way to verify is visually. It looks close tho. Try it out and let me know\n"
] | [
0
] | [] | [] | [
"machine_learning",
"math",
"probability",
"python",
"shap"
] | stackoverflow_0074664259_machine_learning_math_probability_python_shap.txt |
Q:
Can I generate a value per second with React?
Is there a way I can generate multiple SET VALUES per second using react?
What am I trying to accomplish?
I have created this "tap game" where you could generate $1 per tap up to $250 per tap depending on where you tap. In this game I want to be able to "hire employees." After designating the hired employee to, lets say "$1 team", my "Score" will increase by 1 per second. If I decided to hire another employee and I decided to assign it to "$5 team", it would increase by 5. Since I have 2 employees at this time, I do not want to cancel one or the other out, I would like them to run simultaneously (e.g. 6 per second in this example).
What Have I tried?
I have not tried, or tested, anything specifically because of course I am unsure of how to accomplish this. I have researched other Stack Overflow examples and I have came across one very similar, however, they are using an API where as I am not. Stack Overflow Example I am not sure if I would even need an API, I would assume I would not?
Request:
If at all possible, a solution that I could use dynamically would be extremely appreciated. If I decided to hire 10 employees and stick them all on $1 team, I would like to be able to do so.
Attached is a fully functional code.
import React, {useState, useEffect} from 'react'
const App = () => {
// ======================================
// HOOKS
// ======================================
const [score, setScore] = useState(0)
const [showEZBake, setShowEZBake] = useState(false)
const [showToasterOven, setShowToasterOven] = useState(false)
const [showConvectionOven, setShowConvectionOven] = useState(false)
const [showSmallFactory, setShowSmallFactory] = useState(false)
// ======================================
// FUNCTIONS
// ======================================
const winCondition = () => {
if (score >= 100000) {
return (
<h1>YOURE A WINNER!!</h1>
)
}
}
// EARN REVENUE FUNCTIONS
const earn1 = () => {
setScore(score + 1)
winCondition()
}
const earn5 = () => {
setScore(score + 5)
winCondition()
}
const earn25 = () => {
setScore(score + 25)
winCondition()
}
const earn50 = () => {
setScore(score + 50)
winCondition()
}
const earn250 = () => {
setScore(score + 250)
winCondition()
}
// PURCHASE ITEMS FUNCTIONS
const buyEZOven = () => {
setScore(score - 25)
}
const buyToasterOven = () => {
setScore(score - 250)
}
const buyConvectionOven = () => {
setScore(score - 1000)
}
const buySmallFactory = () => {
setScore(score - 15000)
}
const upgradeEZOven = () => {
if (score >= 25) {
setShowEZBake(true)
buyEZOven()
}
}
const upgradeToasterOven = () => {
if (score >= 250 ) {
setShowToasterOven(true)
buyToasterOven()
}
}
const upgradeConvectionOven = () => {
if (score >= 1000) {
setShowConvectionOven(true)
buyConvectionOven()
}
}
const upgradeSmallFactory = () => {
if (score >= 15000) {
setShowSmallFactory(true)
buySmallFactory()
}
}
// ======================================
// DISPLAY
// ======================================
return (
<div>
<h1>Bakery</h1>
<h2>Revenue {score}</h2>
<h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>
{/* EZ BAKE OVEN */}
{showEZBake ? (
<>
<h3>Easy Bake Oven</h3>
<button onClick={earn5}>$5</button>
</>
) : (
<>
<h3>Purchase Easy Bake Oven</h3>
<button onClick={upgradeEZOven}>$25</button>
</>
)
}
{/* TOASTER OVEN */}
{showToasterOven ? (
<>
<h3>Toaster Oven</h3>
<button onClick={earn25}>$25</button>
</>
) : (
<>
<h3>Purchase Toaster Oven</h3>
<button onClick={upgradeToasterOven}>$250</button>
</>
)}
{/* CONVECTION OVEN */}
{showConvectionOven ? (
<>
<h3>Convection Oven</h3>
<button onClick={earn50}>$50</button>
</>
) : (
<>
<h3>Purchase Convection Oven</h3>
<button onClick={upgradeConvectionOven}>$1000</button>
</>
)}
{/* FACTORY */}
{showSmallFactory ? (
<>
<h3>Small Factory Production</h3>
<button onClick={earn250}>$250</button>
</>
) : (
<>
<h3>Purchase Small Factory</h3>
<button onClick={upgradeSmallFactory}>$15,000</button>
</>
)}
{/* WIN CONDITION */}
{
winCondition()
}
</div>
)
}
export default App
A:
You can generate a value every second pretty easily with useEffect:
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setTimeout(() => {
setCount(count + 1);
}, 1000);
return () => clearTimeout(timer);
}, [count, setCount]);
| Can I generate a value per second with React? | Is there a way I can generate multiple SET VALUES per second using react?
What am I trying to accomplish?
I have created this "tap game" where you could generate $1 per tap up to $250 per tap depending on where you tap. In this game I want to be able to "hire employees." After designating the hired employee to, lets say "$1 team", my "Score" will increase by 1 per second. If I decided to hire another employee and I decided to assign it to "$5 team", it would increase by 5. Since I have 2 employees at this time, I do not want to cancel one or the other out, I would like them to run simultaneously (e.g. 6 per second in this example).
What Have I tried?
I have not tried, or tested, anything specifically because of course I am unsure of how to accomplish this. I have researched other Stack Overflow examples and I have came across one very similar, however, they are using an API where as I am not. Stack Overflow Example I am not sure if I would even need an API, I would assume I would not?
Request:
If at all possible, a solution that I could use dynamically would be extremely appreciated. If I decided to hire 10 employees and stick them all on $1 team, I would like to be able to do so.
Attached is a fully functional code.
import React, {useState, useEffect} from 'react'
const App = () => {
// ======================================
// HOOKS
// ======================================
const [score, setScore] = useState(0)
const [showEZBake, setShowEZBake] = useState(false)
const [showToasterOven, setShowToasterOven] = useState(false)
const [showConvectionOven, setShowConvectionOven] = useState(false)
const [showSmallFactory, setShowSmallFactory] = useState(false)
// ======================================
// FUNCTIONS
// ======================================
const winCondition = () => {
if (score >= 100000) {
return (
<h1>YOURE A WINNER!!</h1>
)
}
}
// EARN REVENUE FUNCTIONS
const earn1 = () => {
setScore(score + 1)
winCondition()
}
const earn5 = () => {
setScore(score + 5)
winCondition()
}
const earn25 = () => {
setScore(score + 25)
winCondition()
}
const earn50 = () => {
setScore(score + 50)
winCondition()
}
const earn250 = () => {
setScore(score + 250)
winCondition()
}
// PURCHASE ITEMS FUNCTIONS
const buyEZOven = () => {
setScore(score - 25)
}
const buyToasterOven = () => {
setScore(score - 250)
}
const buyConvectionOven = () => {
setScore(score - 1000)
}
const buySmallFactory = () => {
setScore(score - 15000)
}
const upgradeEZOven = () => {
if (score >= 25) {
setShowEZBake(true)
buyEZOven()
}
}
const upgradeToasterOven = () => {
if (score >= 250 ) {
setShowToasterOven(true)
buyToasterOven()
}
}
const upgradeConvectionOven = () => {
if (score >= 1000) {
setShowConvectionOven(true)
buyConvectionOven()
}
}
const upgradeSmallFactory = () => {
if (score >= 15000) {
setShowSmallFactory(true)
buySmallFactory()
}
}
// ======================================
// DISPLAY
// ======================================
return (
<div>
<h1>Bakery</h1>
<h2>Revenue {score}</h2>
<h3>No Bake Pudding</h3><button onClick={earn1}>$1</button>
{/* EZ BAKE OVEN */}
{showEZBake ? (
<>
<h3>Easy Bake Oven</h3>
<button onClick={earn5}>$5</button>
</>
) : (
<>
<h3>Purchase Easy Bake Oven</h3>
<button onClick={upgradeEZOven}>$25</button>
</>
)
}
{/* TOASTER OVEN */}
{showToasterOven ? (
<>
<h3>Toaster Oven</h3>
<button onClick={earn25}>$25</button>
</>
) : (
<>
<h3>Purchase Toaster Oven</h3>
<button onClick={upgradeToasterOven}>$250</button>
</>
)}
{/* CONVECTION OVEN */}
{showConvectionOven ? (
<>
<h3>Convection Oven</h3>
<button onClick={earn50}>$50</button>
</>
) : (
<>
<h3>Purchase Convection Oven</h3>
<button onClick={upgradeConvectionOven}>$1000</button>
</>
)}
{/* FACTORY */}
{showSmallFactory ? (
<>
<h3>Small Factory Production</h3>
<button onClick={earn250}>$250</button>
</>
) : (
<>
<h3>Purchase Small Factory</h3>
<button onClick={upgradeSmallFactory}>$15,000</button>
</>
)}
{/* WIN CONDITION */}
{
winCondition()
}
</div>
)
}
export default App
| [
"You can generate a value every second pretty easily with useEffect:\nconst [count, setCount] = useState(0);\n\nuseEffect(() => {\n const timer = setTimeout(() => {\n setCount(count + 1);\n }, 1000);\n return () => clearTimeout(timer);\n}, [count, setCount]);\n\n"
] | [
0
] | [] | [] | [
"jsx",
"reactjs"
] | stackoverflow_0074671621_jsx_reactjs.txt |
Q:
python FastAPI websocket, Popen - print device stdout works, but stdout to websocket client doesn't
I have a websocket server and a js/html client. When I click a button on the client, it invokes a shell command on the server.
I use Popen to call the command cat /dev/ttyUSB0 to read the content of a device which is constantly changing. When I print the output on terminal it works, but when I send the output through the websocket it doesn't do anything until I interrupt the program. I don't know what's happening.
This is what i've tried
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import json
from subprocess import Popen, PIPE, STDOUT
import shlex
app = FastAPI()
html = open('templates/index.html').read()
@app.get("/")
async def get():
return HTMLResponse(html)
Here's where the problem occur
async def run_command(websocket: WebSocket):
print("running command")
command = "cat /dev/ttyUSB0"
args = shlex.split(command)
with Popen(args, stdout=PIPE, stderr=STDOUT) as process:
for output in process.stdout:
await websocket.send_text(output.decode())
# print(output.decode(), end='')
I tried to send just one readline and it worked, except in a while loop
await websocket.send_text( process.stdout.readline() )
Route
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
message = None
data = await websocket.receive_text()
try:
message = json.loads(data)
except:
await websocket.send_text("Bad message")
if message.get("type") == "monitor":
await websocket.send_text("Uploading project")
await run_command(websocket)
client
<form action="" onsubmit="sendMessage(event)">
<button>Send</button>
</form>
<ul id='output'></ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) { console.log(event.data) };
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send('{"type": "monitor"}')
event.preventDefault()
}
</script>
| python FastAPI websocket, Popen - print device stdout works, but stdout to websocket client doesn't | I have a websocket server and a js/html client. When I click a button on the client, it invokes a shell command on the server.
I use Popen to call the command cat /dev/ttyUSB0 to read the content of a device which is constantly changing. When I print the output on terminal it works, but when I send the output through the websocket it doesn't do anything until I interrupt the program. I don't know what's happening.
This is what i've tried
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
import json
from subprocess import Popen, PIPE, STDOUT
import shlex
app = FastAPI()
html = open('templates/index.html').read()
@app.get("/")
async def get():
return HTMLResponse(html)
Here's where the problem occur
async def run_command(websocket: WebSocket):
print("running command")
command = "cat /dev/ttyUSB0"
args = shlex.split(command)
with Popen(args, stdout=PIPE, stderr=STDOUT) as process:
for output in process.stdout:
await websocket.send_text(output.decode())
# print(output.decode(), end='')
I tried to send just one readline and it worked, except in a while loop
await websocket.send_text( process.stdout.readline() )
Route
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
message = None
data = await websocket.receive_text()
try:
message = json.loads(data)
except:
await websocket.send_text("Bad message")
if message.get("type") == "monitor":
await websocket.send_text("Uploading project")
await run_command(websocket)
client
<form action="" onsubmit="sendMessage(event)">
<button>Send</button>
</form>
<ul id='output'></ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) { console.log(event.data) };
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send('{"type": "monitor"}')
event.preventDefault()
}
</script>
| [] | [] | [
"I think the issue is that your websocket server is not handling the client's messages properly. When the client sends a message, the server receives it and parses it as JSON. If the type property of the message is \"monitor\", the server starts running the run_command function. However, your run_command function does not handle the case where the client disconnects from the websocket. As a result, when the client disconnects, the server continues to run the run_command function indefinitely, without being able to send any more messages over the websocket.\nTo fix this, you can add a try block around the for loop in the run_command function, and use the websocket.closed property to check if the client has disconnected. If the client has disconnected, you can break out of the loop and return from the run_command function.\nHere's an example of how you could modify the run_command function to do this:\nasync def run_command(websocket: WebSocket):\n print(\"running command\")\n command = \"cat /dev/ttyUSB0\"\n args = shlex.split(command)\n\n with Popen(args, stdout=PIPE, stderr=STDOUT) as process:\n try:\n for output in process.stdout:\n # If the client has disconnected, break out of the loop\n if websocket.closed:\n break\n await websocket.send_text(output.decode())\n except:\n # Catch any exceptions that occur while sending messages\n pass\n\n"
] | [
-1
] | [
"fastapi",
"popen",
"python",
"stdout",
"websocket"
] | stackoverflow_0074671794_fastapi_popen_python_stdout_websocket.txt |
Q:
Cant calculate percentage difference between two numbers
I am trying to show the percentage after a number is subtracted.
Example:
Cost of work = Β£165.00
Workers charge = Β£42.00
Left Over = %
What is the percentage of Cost left after the worker has got his cut.
My Code output is showing 0
int number = 0, number1, result = 0;
if (Int32.TryParse(SelectedQuoteForEditing.JobPrice, out number) && Int32.TryParse(Rate.Content.ToString().ToString(), out number1))
{result = number - number1;}
JobPercentage.Content = result.ToString();
A:
The simple formula is PART / MAX * 100
In your fault It should look like this:
double costOfWork = 165;
double workersCharge = 42;
double left = Math.Round((costOfWork - workersCharge) / costOfWork * 100, 2);
It calculates the remaining cost using costOfWork - workersCharge.
Then it calculates how many percents the remaining cost is.
It's getting rounded to two digits.
A:
I ran across the issue in C#- FileComparison
double size = (LengthOfTxt-LengthOfDocx) / LengthOfDocx / 100;
| Cant calculate percentage difference between two numbers | I am trying to show the percentage after a number is subtracted.
Example:
Cost of work = Β£165.00
Workers charge = Β£42.00
Left Over = %
What is the percentage of Cost left after the worker has got his cut.
My Code output is showing 0
int number = 0, number1, result = 0;
if (Int32.TryParse(SelectedQuoteForEditing.JobPrice, out number) && Int32.TryParse(Rate.Content.ToString().ToString(), out number1))
{result = number - number1;}
JobPercentage.Content = result.ToString();
| [
"The simple formula is PART / MAX * 100\nIn your fault It should look like this:\ndouble costOfWork = 165;\ndouble workersCharge = 42;\n\ndouble left = Math.Round((costOfWork - workersCharge) / costOfWork * 100, 2);\n\nIt calculates the remaining cost using costOfWork - workersCharge.\nThen it calculates how many percents the remaining cost is.\nIt's getting rounded to two digits.\n",
"I ran across the issue in C#- FileComparison\ndouble size = (LengthOfTxt-LengthOfDocx) / LengthOfDocx / 100;\n"
] | [
7,
0
] | [] | [] | [
"c#"
] | stackoverflow_0056481047_c#.txt |
Q:
Getting null value in db when using @embbeded in Spring boot Rest api? new to java help me out guys
Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private int id;
private String name;
@Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Croller {
@Autowired
TestRepo repo;
@PostMapping("/add")
public String save(@RequestBody User mode) {
repo.save(mode);
return "details saved";
}
@GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
@GetMapping("/search")
public List<User> searchname(@RequestParam("name")String name){
return repo.name(name);
}
@GetMapping("/byid/{id}")
public Optional <User> getone (@PathVariable int id){
return repo.findById(id);
}
@PutMapping("/update")
public String updateid(@RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
@DeleteMapping("/remove/{id}")
public String delete(@PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
A:
Your request has to match the @RequestBody object for spring to map the keys appropriately
Try this request -
{
"id":19,
"name":"Alex",
"address":{
"cityname":"california",
"streetname":"ring road",
"Housename":"Housename"
}
}
A:
Please make sure you give input as per your Model.
| Getting null value in db when using @embbeded in Spring boot Rest api? new to java help me out guys | Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private int id;
private String name;
@Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
@Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Croller {
@Autowired
TestRepo repo;
@PostMapping("/add")
public String save(@RequestBody User mode) {
repo.save(mode);
return "details saved";
}
@GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
@GetMapping("/search")
public List<User> searchname(@RequestParam("name")String name){
return repo.name(name);
}
@GetMapping("/byid/{id}")
public Optional <User> getone (@PathVariable int id){
return repo.findById(id);
}
@PutMapping("/update")
public String updateid(@RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
@DeleteMapping("/remove/{id}")
public String delete(@PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
| [
"Your request has to match the @RequestBody object for spring to map the keys appropriately\nTry this request -\n{\n \"id\":19,\n \"name\":\"Alex\",\n \"address\":{\n \"cityname\":\"california\",\n \"streetname\":\"ring road\",\n \"Housename\":\"Housename\"\n }\n}\n\n",
"Please make sure you give input as per your Model.\n\n"
] | [
1,
0
] | [] | [] | [
"hibernate",
"java",
"jpa",
"spring",
"spring_boot"
] | stackoverflow_0061977519_hibernate_java_jpa_spring_spring_boot.txt |
Q:
Concatenate strings from cells using WHILE/UNTIL LOOP?
I have strings stored in cells of a column in Excel that I would like to concatenate in several pieces, like sentences, with VBA. Here is an example:
Column A
Jack
learns
VBA
Jack
sits
on
a
couch
Jack
wants
chocolate
cake
I finally found a way to concatenate all strings and save the sentences to a cell:
Sub JACK()
Dim MP() As String
Dim Str As String
Dim i As Integer
For i = 2 To 10
ReDim Preserve MP(i)
MP(i) = Cells(i, 1).Value
Next i
Str = Join(MP)
Cells(1, 2).Value = Str
End Sub
But I would like to have the sentences that start with "Jack" and end with the row "Jack - 1", each saved in seperate cells.
Could anyone help me???
Thank you so much!
A:
This is the code snippet that will do what you want:
Sub test_func()
' this is the starting cell (keep in mind that the first word in the cell is 'Jack' so the start cell is actually starting at C2)
Dim startCell As range
Set startCell = ThisWorkbook.ActiveSheet.range("B2")
' reading all the cells in the range
Dim wordRange As range
Set wordRange = ThisWorkbook.ActiveSheet.range("A2:A13")
' creating two variables row and col
Dim row As Long
Dim col As Long
' for each word in wordRange
Dim word As Variant
For Each word In wordRange
' as soon as we find the word 'Jack'
If word.Value = "Jack" Then
' move the cursor to row 0
row = 0
' move the cursor one cell to the right
col = col + 1
End If
' else if the word is not 'Jack', put the word on the cursor cell
startCell.Offset(row, col) = word
' then move the cursor one cell down
row = row + 1
Next
End Sub
The function is:
reading all the words from the column A into a range.
dumping the elements from the range (word) starting on B2, one by one
as soon as it finds the word 'Jack', it will start at row 0, move to the right and continue
The outcome looks like this:
This is the output of the script
Note that the words are starting on C2 even though you chose B2 to be the starting cell; this is because the first word in the list is 'Jack', so it is moving one cell to the right as soon as it starts.
EDIT:
Here might be the function that you are looking for:
Sub test_func()
' this is the starting cell (keep in mind that the first word in the cell is 'Jack' so the start cell is actually starting at C2)
Dim startCell As range
Set startCell = ThisWorkbook.ActiveSheet.range("B2")
' reading all the cells in the range
Dim wordRange As range
Set wordRange = ThisWorkbook.ActiveSheet.range("A2:A13")
' creating two variables row and col
Dim row As Long
Dim col As Long
' string that holds each sentence
Dim sentence As String
' for each word in wordRange
Dim word As Variant
For Each word In wordRange
' as soon as we find the word 'Jack' and the sentence is not empty, the sentence is complete
If word.Value = "Jack" And sentence <> "" Then
'printing out the whole sentence
startCell.Offset(row, col) = sentence
' emptying the sentence when 'Jack' is found
sentence = ""
' move the cursor one cell down
row = row + 1
End If
' else if the word is not 'Jack', concatenates the word into the sentence
sentence = sentence & " " & word
Next
' adding this again at the end of the loop because the last sentence is not outputted otherwise
startCell.Offset(row, col) = sentence
End Sub
This function differs from the previous one because it concatenates the words into a sentence before dumping it out. In this function, the start cell is correct and is not moving down or right when the program starts. This is because we can check whether the sentence that it is about to dump out is empty or not, if it is; then it means we did not finish our sentence.
Hope this helps!
This is the result screenshot of the second version of the code
A:
Extract Sentences From Column
Sub JACK()
Const JackStart As String = "Jack"
Const JackEnd As String = "."
Const Delimiter As String = " "
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim slCell As Range: Set slCell = ws.Cells(ws.Rows.Count, "A").End(xlUp)
Dim srg As Range: Set srg = ws.Range("A2", slCell)
Dim dCell As Range: Set dCell = ws.Range("B2")
Dim sCell As Range
Dim JackString As String
Dim FoundFirst As Boolean
For Each sCell In srg.Cells
If sCell.Value = JackStart Then
If FoundFirst Then
dCell.Value = JackString & JackEnd
Set dCell = dCell.Offset(1) ' next row
Else
FoundFirst = True
End If
JackString = JackStart
Else
If FoundFirst Then JackString = JackString & Delimiter & sCell.Value
End If
Next sCell
dCell.Value = JackString & JackEnd
MsgBox "Jacks extracted.", vbInformation
End Sub
| Concatenate strings from cells using WHILE/UNTIL LOOP? | I have strings stored in cells of a column in Excel that I would like to concatenate in several pieces, like sentences, with VBA. Here is an example:
Column A
Jack
learns
VBA
Jack
sits
on
a
couch
Jack
wants
chocolate
cake
I finally found a way to concatenate all strings and save the sentences to a cell:
Sub JACK()
Dim MP() As String
Dim Str As String
Dim i As Integer
For i = 2 To 10
ReDim Preserve MP(i)
MP(i) = Cells(i, 1).Value
Next i
Str = Join(MP)
Cells(1, 2).Value = Str
End Sub
But I would like to have the sentences that start with "Jack" and end with the row "Jack - 1", each saved in seperate cells.
Could anyone help me???
Thank you so much!
| [
"This is the code snippet that will do what you want:\nSub test_func()\n\n ' this is the starting cell (keep in mind that the first word in the cell is 'Jack' so the start cell is actually starting at C2)\n Dim startCell As range\n Set startCell = ThisWorkbook.ActiveSheet.range(\"B2\")\n \n ' reading all the cells in the range\n Dim wordRange As range\n Set wordRange = ThisWorkbook.ActiveSheet.range(\"A2:A13\")\n \n ' creating two variables row and col\n Dim row As Long\n Dim col As Long\n \n ' for each word in wordRange\n Dim word As Variant\n For Each word In wordRange\n ' as soon as we find the word 'Jack'\n If word.Value = \"Jack\" Then\n ' move the cursor to row 0\n row = 0\n ' move the cursor one cell to the right\n col = col + 1\n End If\n ' else if the word is not 'Jack', put the word on the cursor cell\n startCell.Offset(row, col) = word\n ' then move the cursor one cell down\n row = row + 1\n Next\n\nEnd Sub\n\nThe function is:\n\nreading all the words from the column A into a range.\ndumping the elements from the range (word) starting on B2, one by one\nas soon as it finds the word 'Jack', it will start at row 0, move to the right and continue\n\nThe outcome looks like this:\nThis is the output of the script\nNote that the words are starting on C2 even though you chose B2 to be the starting cell; this is because the first word in the list is 'Jack', so it is moving one cell to the right as soon as it starts.\nEDIT:\nHere might be the function that you are looking for:\nSub test_func()\n\n ' this is the starting cell (keep in mind that the first word in the cell is 'Jack' so the start cell is actually starting at C2)\n Dim startCell As range\n Set startCell = ThisWorkbook.ActiveSheet.range(\"B2\")\n \n ' reading all the cells in the range\n Dim wordRange As range\n Set wordRange = ThisWorkbook.ActiveSheet.range(\"A2:A13\")\n \n ' creating two variables row and col\n Dim row As Long\n Dim col As Long\n \n ' string that holds each sentence\n Dim sentence As String\n \n ' for each word in wordRange\n Dim word As Variant\n For Each word In wordRange\n ' as soon as we find the word 'Jack' and the sentence is not empty, the sentence is complete\n If word.Value = \"Jack\" And sentence <> \"\" Then\n 'printing out the whole sentence\n startCell.Offset(row, col) = sentence\n ' emptying the sentence when 'Jack' is found\n sentence = \"\"\n ' move the cursor one cell down\n row = row + 1\n End If\n ' else if the word is not 'Jack', concatenates the word into the sentence\n sentence = sentence & \" \" & word\n Next\n \n ' adding this again at the end of the loop because the last sentence is not outputted otherwise\n startCell.Offset(row, col) = sentence\n\nEnd Sub\n\nThis function differs from the previous one because it concatenates the words into a sentence before dumping it out. In this function, the start cell is correct and is not moving down or right when the program starts. This is because we can check whether the sentence that it is about to dump out is empty or not, if it is; then it means we did not finish our sentence.\nHope this helps!\nThis is the result screenshot of the second version of the code\n",
"Extract Sentences From Column\n\nSub JACK()\n\n Const JackStart As String = \"Jack\"\n Const JackEnd As String = \".\"\n Const Delimiter As String = \" \"\n\n Dim ws As Worksheet: Set ws = ActiveSheet ' improve!\n \n Dim slCell As Range: Set slCell = ws.Cells(ws.Rows.Count, \"A\").End(xlUp)\n Dim srg As Range: Set srg = ws.Range(\"A2\", slCell)\n \n Dim dCell As Range: Set dCell = ws.Range(\"B2\")\n \n Dim sCell As Range\n Dim JackString As String\n Dim FoundFirst As Boolean\n \n For Each sCell In srg.Cells\n If sCell.Value = JackStart Then\n If FoundFirst Then\n dCell.Value = JackString & JackEnd\n Set dCell = dCell.Offset(1) ' next row\n Else\n FoundFirst = True\n End If\n JackString = JackStart\n Else\n If FoundFirst Then JackString = JackString & Delimiter & sCell.Value\n End If\n Next sCell\n \n dCell.Value = JackString & JackEnd\n \n MsgBox \"Jacks extracted.\", vbInformation\n \nEnd Sub\n\n"
] | [
0,
0
] | [] | [] | [
"concatenation",
"excel",
"string",
"until_loop",
"vba"
] | stackoverflow_0074671409_concatenation_excel_string_until_loop_vba.txt |
Q:
Cannot set headers after they are sent to the client | Redirect causing issue?
I am redirecting a successful login to my admin page but once my app.get route with express is initiated it is throwing me the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client".. Any ideas why?
app.post('/login', function(request, response) {
// Capture the input fields
let username = request.body.username;
let password = request.body.password;
console.log(username);
console.log(password);
// Ensure the input fields exists and are not empty
if (username && password) {
// Execute SQL query that'll select the account from the database based on the specified username and password
con.query('SELECT * FROM something WHERE user = ? AND password = ?', [username, password], function(error, results, fields) {
// If there is an issue with the query, output the error
if (error) throw error;
// If the account exists
if (results.length > 0) {
// Authenticate the user
request.session.loggedin = true;
request.session.username = username;
response.redirect('Admin'); //redirect to app.get('/Admin')
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
});
//LOGIN SESSION //
app.get('/Admin', function (req, res) {
if (req.session.loggedin) {
activeEmails()
.then((result) =>{
var email = result;
console.log(email);
res.render('Admin', { //error is coming here!
email : email
});
});
} else {
// Not logged in
res.redirect('login');
}
res.end();
});
A:
res.end signals that all headers are sent and res.render sets headers. The order of execution in the request handler for the /Admin GET request is:
app.get('/Admin', function (req, res) {
if (req.session.loggedin) {
activeEmails().then((result) => {
var email = result;
console.log(email);
res.render('Admin', { // second
email : email
});
});
} else {
// Not logged in
res.redirect('login');
}
res.end(); // first
});
First, res.end signals that all headers are sent and then, res.render tries to set headers. That causes the error. You must not call res.render after res.end.
I don't know why you call res.end in your code. You probably can remove all the calls. AFAIK, they are superfluous in your code.
| Cannot set headers after they are sent to the client | Redirect causing issue? | I am redirecting a successful login to my admin page but once my app.get route with express is initiated it is throwing me the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client".. Any ideas why?
app.post('/login', function(request, response) {
// Capture the input fields
let username = request.body.username;
let password = request.body.password;
console.log(username);
console.log(password);
// Ensure the input fields exists and are not empty
if (username && password) {
// Execute SQL query that'll select the account from the database based on the specified username and password
con.query('SELECT * FROM something WHERE user = ? AND password = ?', [username, password], function(error, results, fields) {
// If there is an issue with the query, output the error
if (error) throw error;
// If the account exists
if (results.length > 0) {
// Authenticate the user
request.session.loggedin = true;
request.session.username = username;
response.redirect('Admin'); //redirect to app.get('/Admin')
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
});
//LOGIN SESSION //
app.get('/Admin', function (req, res) {
if (req.session.loggedin) {
activeEmails()
.then((result) =>{
var email = result;
console.log(email);
res.render('Admin', { //error is coming here!
email : email
});
});
} else {
// Not logged in
res.redirect('login');
}
res.end();
});
| [
"res.end signals that all headers are sent and res.render sets headers. The order of execution in the request handler for the /Admin GET request is:\napp.get('/Admin', function (req, res) {\n if (req.session.loggedin) {\n activeEmails().then((result) => {\n var email = result;\n console.log(email);\n res.render('Admin', { // second\n email : email\n });\n });\n } else {\n // Not logged in\n res.redirect('login');\n }\n res.end(); // first\n});\n\nFirst, res.end signals that all headers are sent and then, res.render tries to set headers. That causes the error. You must not call res.render after res.end.\nI don't know why you call res.end in your code. You probably can remove all the calls. AFAIK, they are superfluous in your code.\n"
] | [
2
] | [] | [] | [
"express",
"javascript"
] | stackoverflow_0074671761_express_javascript.txt |
Q:
How to fix bootstrap navbar button spacing?
I know this is a dumb question I should know how to solve, but I don't do front-end that much.
So, I'm making a cool navbar with bootstrap, but when I try to add more than one button, the button spacing gets weird.
Does anyone know how to fix this problem?
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #333;">
<a class="navbar-brand" href="/">
<img src="/static/img/AdiAvi.png" width="30" height="30" class="d-inline-block align-top" alt="">
AdiAvi
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item">
<a {% if homePage %} class="nav-link active" {% endif %} {% if dashboardPage %} class="nav-link active" {% endif %} class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a {% if contactPage %} class="nav-link active" {% endif %} class="nav-link" href="/contact">Contact</a>
</li>
{% if baseTemplate %}
<button type="button" id="loginButton" class="ml-2 btn btn-danger navbar-btn">
Login
</button>
{% endif %}
{% if baseTemplate %}
<button type="button" id="registerTrigger" class="btn btn-primary navbar-btn ml-2">
Register
</button>
{% endif %}
</ul>
</div>
</nav>
Also the buttons I am looking at are the login and register buttons.
I am using BootStrap 5
Here is an example image of what happens when I run the code:
I tried using position relative to make the distance regular, but instead, what happened was that it stayed the same. Results
A:
You can use the bootstrap class ml-x (x select a value of choice for your spacing) to increase spacing between buttons.
For example ml-2:
<button type="button" id="registerTrigger" class="btn btn-primary navbar-btn ml-2">
Register
</button>
I modified your html with that (expand viewport to make it look like in your screenshot):
https://jsfiddle.net/aeo3v29w/
For more information check out this post: Does bootstrap have builtin padding and margin classes?
| How to fix bootstrap navbar button spacing? | I know this is a dumb question I should know how to solve, but I don't do front-end that much.
So, I'm making a cool navbar with bootstrap, but when I try to add more than one button, the button spacing gets weird.
Does anyone know how to fix this problem?
<nav class="navbar navbar-expand-lg navbar-dark" style="background-color: #333;">
<a class="navbar-brand" href="/">
<img src="/static/img/AdiAvi.png" width="30" height="30" class="d-inline-block align-top" alt="">
AdiAvi
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item">
<a {% if homePage %} class="nav-link active" {% endif %} {% if dashboardPage %} class="nav-link active" {% endif %} class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a {% if contactPage %} class="nav-link active" {% endif %} class="nav-link" href="/contact">Contact</a>
</li>
{% if baseTemplate %}
<button type="button" id="loginButton" class="ml-2 btn btn-danger navbar-btn">
Login
</button>
{% endif %}
{% if baseTemplate %}
<button type="button" id="registerTrigger" class="btn btn-primary navbar-btn ml-2">
Register
</button>
{% endif %}
</ul>
</div>
</nav>
Also the buttons I am looking at are the login and register buttons.
I am using BootStrap 5
Here is an example image of what happens when I run the code:
I tried using position relative to make the distance regular, but instead, what happened was that it stayed the same. Results
| [
"You can use the bootstrap class ml-x (x select a value of choice for your spacing) to increase spacing between buttons.\nFor example ml-2:\n<button type=\"button\" id=\"registerTrigger\" class=\"btn btn-primary navbar-btn ml-2\">\n Register\n</button>\n\nI modified your html with that (expand viewport to make it look like in your screenshot):\nhttps://jsfiddle.net/aeo3v29w/\nFor more information check out this post: Does bootstrap have builtin padding and margin classes?\n"
] | [
0
] | [] | [] | [
"bootstrap_5",
"css",
"html"
] | stackoverflow_0074670375_bootstrap_5_css_html.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.