qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
I had the same problem. The reason was, that there were incorrect rights set to the folder. I mean, I manually created a data folder and PostgreSQL service wasn't started. When I copied my data folder content to the original data folder (the one created by PostgreSQL during the installation) everything worked properly.
That log data is from a running server! Is that the end of the newest log if so it not even seems to create new log files anymore. When postgresql is started it is passed the path to the data folder using the -D option. If you go to the windows services manager you should be able to check that path there. See if that matches with the actual path. If it contains forward slashes instead of backslashes that's normal in this case. If the path is wrong you will have to dive into the registry to correct it as the service manager doesn't give you a method to change it. While you are in the service manager also check the postgres service runs under the postgres user account. Also check the postgres user has all rights on the data folder. Other users shouldn't have rights on the folder. If this doesn't help maybe you better try making a backup of your data folder. Uninstall postgres reinstall the same version. DON'T put back your backup, first check if it is working. Then stop the server put the backup back start the server and keep your fingers crossed.
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
I had this kind of issue when installing and old versión on a MS Server 2019. I verified that the Postgre's service wasn't being able to start. I had to locate the installation directory and change the permissions, give "Modify" permission to an specific user that may be having this issue. In case of a windows service, the the "Network Service" user. As a test, you can give Modify permissions to "Authentificated Users" to verify that's the cause and later on try to look for the specific user. In my case, it was a very custom installation and the service was registered to "Network Service" user. I'm not sure if on typical or other installations the running user may change
That log data is from a running server! Is that the end of the newest log if so it not even seems to create new log files anymore. When postgresql is started it is passed the path to the data folder using the -D option. If you go to the windows services manager you should be able to check that path there. See if that matches with the actual path. If it contains forward slashes instead of backslashes that's normal in this case. If the path is wrong you will have to dive into the registry to correct it as the service manager doesn't give you a method to change it. While you are in the service manager also check the postgres service runs under the postgres user account. Also check the postgres user has all rights on the data folder. Other users shouldn't have rights on the folder. If this doesn't help maybe you better try making a backup of your data folder. Uninstall postgres reinstall the same version. DON'T put back your backup, first check if it is working. Then stop the server put the backup back start the server and keep your fingers crossed.
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
PostgreSQL is having an error on startup and to find out what it is you will have to start PostgreSQL manually. PostgreSQL does not log its startup failures as often as you would hope and how i find out what is going on is by starting a cmd.exe window under the postgres user and manually starting PostgreSQL. Run this to start a CMD.exe under the postgres user ``` runas /user:postgres cmd.exe ``` Enter in the postgres password. And then in that new CMD window start PostgreSQL ``` "C:/Program Files (x86)/PostgreSQL/8.3/bin/postgres.exe" -D "C:/Program Files (x86)/PostgreSQL/8.3/data" ``` And let us know the output...
had similar problem on windows 10. coudln't start postgres service in windows services, so I decided just to reinstall it and it did resolve the issue.
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
PostgreSQL is having an error on startup and to find out what it is you will have to start PostgreSQL manually. PostgreSQL does not log its startup failures as often as you would hope and how i find out what is going on is by starting a cmd.exe window under the postgres user and manually starting PostgreSQL. Run this to start a CMD.exe under the postgres user ``` runas /user:postgres cmd.exe ``` Enter in the postgres password. And then in that new CMD window start PostgreSQL ``` "C:/Program Files (x86)/PostgreSQL/8.3/bin/postgres.exe" -D "C:/Program Files (x86)/PostgreSQL/8.3/data" ``` And let us know the output...
I had the same problem. The reason was, that there were incorrect rights set to the folder. I mean, I manually created a data folder and PostgreSQL service wasn't started. When I copied my data folder content to the original data folder (the one created by PostgreSQL during the installation) everything worked properly.
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
PostgreSQL is having an error on startup and to find out what it is you will have to start PostgreSQL manually. PostgreSQL does not log its startup failures as often as you would hope and how i find out what is going on is by starting a cmd.exe window under the postgres user and manually starting PostgreSQL. Run this to start a CMD.exe under the postgres user ``` runas /user:postgres cmd.exe ``` Enter in the postgres password. And then in that new CMD window start PostgreSQL ``` "C:/Program Files (x86)/PostgreSQL/8.3/bin/postgres.exe" -D "C:/Program Files (x86)/PostgreSQL/8.3/data" ``` And let us know the output...
I had this kind of issue when installing and old versión on a MS Server 2019. I verified that the Postgre's service wasn't being able to start. I had to locate the installation directory and change the permissions, give "Modify" permission to an specific user that may be having this issue. In case of a windows service, the the "Network Service" user. As a test, you can give Modify permissions to "Authentificated Users" to verify that's the cause and later on try to look for the specific user. In my case, it was a very custom installation and the service was registered to "Network Service" user. I'm not sure if on typical or other installations the running user may change
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
I had the same problem. The reason was, that there were incorrect rights set to the folder. I mean, I manually created a data folder and PostgreSQL service wasn't started. When I copied my data folder content to the original data folder (the one created by PostgreSQL during the installation) everything worked properly.
had similar problem on windows 10. coudln't start postgres service in windows services, so I decided just to reinstall it and it did resolve the issue.
262,753
Today, my PostgreSQL doesn't start anymore on my windows machine... I've tried to start the service in windows services and got the following error: ``` Windows could not start the PostgreSQL Database Server 8.3 service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion. ``` Then I went to the command line to manually start C:/Program Files (x86)/PostgreSQL/8.3/bin/psql.exe, and then I got this error: ``` psql: Could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "???" and accepting TCP/IP connections on port 5432? ``` Edit: I found this in the logs: ``` 2011-04-22 13:13:16 CEST LOG: could not receive data from client: No connection could be made because the target machine actively refused it. 2011-04-22 13:13:16 CEST LOG: unexpected EOF on client connection ```
2011/04/23
[ "https://serverfault.com/questions/262753", "https://serverfault.com", "https://serverfault.com/users/79339/" ]
I had this kind of issue when installing and old versión on a MS Server 2019. I verified that the Postgre's service wasn't being able to start. I had to locate the installation directory and change the permissions, give "Modify" permission to an specific user that may be having this issue. In case of a windows service, the the "Network Service" user. As a test, you can give Modify permissions to "Authentificated Users" to verify that's the cause and later on try to look for the specific user. In my case, it was a very custom installation and the service was registered to "Network Service" user. I'm not sure if on typical or other installations the running user may change
had similar problem on windows 10. coudln't start postgres service in windows services, so I decided just to reinstall it and it did resolve the issue.
19,515,737
I am new in TestNG. This is my code which I tried in eclipse, but there is a problem occurring in launching internet explorer. The error it is giving is *org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)* This is the complete code.... ``` package com.tcs.medmantra; import java.io.File; import java.io.IOException; import java.util.Set; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.ie.InternetExplorerDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class Registration { WebDriver driver; WebElement element; WebElement element2; WebDriverWait waiter; @Test(priority = 1) public void register_With_Cash() throws RowsExceededException, BiffException, WriteException, IOException { driver=new InternetExplorerDriver(); driver.get("https://172.25.155.250/loginpage.aspx"); //((JavascriptExecutor)driver).executeScript("window.resizeTo(1366, 768);"); waiter = new WebDriverWait (driver, 40); driver.findElement(By.id("txtuname")).sendKeys("122337"); driver.findElement(By.name("txtpwd")).sendKeys("Tcs!@345"); driver.findElement(By.id("btnsubmit")).click(); sleep(25000); //print URL String url = driver.getCurrentUrl(); System.out.println(url); } @BeforeTest public void beforeTest() { File file = new File("D:\\IEDriverServer.exe"); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); } @AfterTest public void afterTest() { driver.quit(); } } ```
2013/10/22
[ "https://Stackoverflow.com/questions/19515737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1986969/" ]
As the error says you need set the protected mode same for all zones, either enabled or disabled. Preferred would be enabled. See [here](http://www.sevenforums.com/tutorials/63141-internet-explorer-protected-mode-turn-off.html)
Change your code to include the path for InternetExplorerDriver. ``` File file = new File("C:/Selenium/iexploredriver.exe"); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); WebDriver driver = new InternetExplorerDriver(); ```
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
There is a documented way to do this. See `UITableView.beginUpdates()` [documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/beginUpdates): > > You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell. > > > So, the correct solution is: ``` tableView.beginUpdates() tableView.endUpdates() ``` Also note that there is a feature that is not documented - you can add a completion handler for the update animation here, too: ``` tableView.beginUpdates() CATransaction.setCompletionBlock { // this will be called when the update animation ends } tableView.endUpdates() ``` However, tread lightly, it's not documented (but it works because `UITableView` uses a `CATransaction` for the animation).
I got your point, and I met the problem before. Your cell is in AutoLayout, and you wish the cell changes by itself. Here is recommended answer for that: [Using Auto Layout in UITableView for dynamic cell layouts & variable row heights](https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights) , so we don't talk about that again. So here we focus on your problem. Since the content of your cell changes constantly, which means the content has updated. Here we suppose the content is a label. We set the label's text, and surely the label's height maybe change. ### Here comes the point: How does the label's change inform the cell to update? We use **AutoLayout**, surely we have to **update the constraint of height for the label.** And I think it will work! Below is the detail step: 1. We setup the constraints for the cell's subviews.(I think it's done) 2. One of the label's height is changed by itself.(I think it's done too) 3. We get the new height of the label, and update the constraint of height for the label.(what we have to do)
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
There is a documented way to do this. See `UITableView.beginUpdates()` [documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/beginUpdates): > > You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell. > > > So, the correct solution is: ``` tableView.beginUpdates() tableView.endUpdates() ``` Also note that there is a feature that is not documented - you can add a completion handler for the update animation here, too: ``` tableView.beginUpdates() CATransaction.setCompletionBlock { // this will be called when the update animation ends } tableView.endUpdates() ``` However, tread lightly, it's not documented (but it works because `UITableView` uses a `CATransaction` for the animation).
Seems you wanted to reload the particular cell/cells based on content changes Here we have a couple of options 1) Need to reload the entire table view . or else 2) Reload particular cell/cells based on content changes. But the preferred option would be reloading the particular cell, Why because when you asked your UITableView instance to reload a couple of cells,tableview will asks its datasource(-tableView:cellForRowAtIndexPath:) to get the updated content,so that the reloaded cells will have the updated size & Updated content aswell. Try to reload the cells when the content/height need to update based on content Hope that helps! Happy coding :)
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
I think the simplest solution is to reload that specific cell. For example: ``` - (void)yourDelegateMethodOfCell:(UITableViewCell *)cell { NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; //If cell is not visible then indexPath will be nil so, if (indexPath) { [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } ```
Seems you wanted to reload the particular cell/cells based on content changes Here we have a couple of options 1) Need to reload the entire table view . or else 2) Reload particular cell/cells based on content changes. But the preferred option would be reloading the particular cell, Why because when you asked your UITableView instance to reload a couple of cells,tableview will asks its datasource(-tableView:cellForRowAtIndexPath:) to get the updated content,so that the reloaded cells will have the updated size & Updated content aswell. Try to reload the cells when the content/height need to update based on content Hope that helps! Happy coding :)
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
There is a documented way to do this. See `UITableView.beginUpdates()` [documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/beginUpdates): > > You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell. > > > So, the correct solution is: ``` tableView.beginUpdates() tableView.endUpdates() ``` Also note that there is a feature that is not documented - you can add a completion handler for the update animation here, too: ``` tableView.beginUpdates() CATransaction.setCompletionBlock { // this will be called when the update animation ends } tableView.endUpdates() ``` However, tread lightly, it's not documented (but it works because `UITableView` uses a `CATransaction` for the animation).
I've found the best way to get it to check heights is to call, after whatever text change has been made, in order: ``` self.tableView.beginUpdates() self.tableView.endUpdates() ``` This causes the tableView to check heights for all visible cells and it will cause changes to be made as needed.
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
You can get automatic cell height by this code ``` tableView.beginUpdates() // add label text update code here // label.numberOfLines = label.numberOfLines == 0 ? 1 : 0 tableView.endUpdates() ``` Below is the reference to this solution with demo : [GitHub-RayFix-MultiLineDemo](https://github.com/rayfix/MultilineDemo)
You can resize your cell height by implementing below method only ``` - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{ return UITableViewAutomaticDimension; } ```
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
I've found the best way to get it to check heights is to call, after whatever text change has been made, in order: ``` self.tableView.beginUpdates() self.tableView.endUpdates() ``` This causes the tableView to check heights for all visible cells and it will cause changes to be made as needed.
I think the simplest solution is to reload that specific cell. For example: ``` - (void)yourDelegateMethodOfCell:(UITableViewCell *)cell { NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; //If cell is not visible then indexPath will be nil so, if (indexPath) { [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } ```
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
You can get automatic cell height by this code ``` tableView.beginUpdates() // add label text update code here // label.numberOfLines = label.numberOfLines == 0 ? 1 : 0 tableView.endUpdates() ``` Below is the reference to this solution with demo : [GitHub-RayFix-MultiLineDemo](https://github.com/rayfix/MultilineDemo)
To disable the annoying `tableView` animation: ``` UIView.setAnimationsEnabled(false) tableView.beginUpdates() // cell.titleLabel?.text = "title" // cell.detailTextLabel?.text = "Very long text ..." // cell.detailTextLabel?.numberOfLines = 0 tableView.endUpdates() UIView.setAnimationsEnabled(true) ```
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
I think the simplest solution is to reload that specific cell. For example: ``` - (void)yourDelegateMethodOfCell:(UITableViewCell *)cell { NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; //If cell is not visible then indexPath will be nil so, if (indexPath) { [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } ```
To disable the annoying `tableView` animation: ``` UIView.setAnimationsEnabled(false) tableView.beginUpdates() // cell.titleLabel?.text = "title" // cell.detailTextLabel?.text = "Very long text ..." // cell.detailTextLabel?.numberOfLines = 0 tableView.endUpdates() UIView.setAnimationsEnabled(true) ```
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
You can get automatic cell height by this code ``` tableView.beginUpdates() // add label text update code here // label.numberOfLines = label.numberOfLines == 0 ? 1 : 0 tableView.endUpdates() ``` Below is the reference to this solution with demo : [GitHub-RayFix-MultiLineDemo](https://github.com/rayfix/MultilineDemo)
I got your point, and I met the problem before. Your cell is in AutoLayout, and you wish the cell changes by itself. Here is recommended answer for that: [Using Auto Layout in UITableView for dynamic cell layouts & variable row heights](https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights) , so we don't talk about that again. So here we focus on your problem. Since the content of your cell changes constantly, which means the content has updated. Here we suppose the content is a label. We set the label's text, and surely the label's height maybe change. ### Here comes the point: How does the label's change inform the cell to update? We use **AutoLayout**, surely we have to **update the constraint of height for the label.** And I think it will work! Below is the detail step: 1. We setup the constraints for the cell's subviews.(I think it's done) 2. One of the label's height is changed by itself.(I think it's done too) 3. We get the new height of the label, and update the constraint of height for the label.(what we have to do)
35,975,450
I have a question regarding to the program. This program allows you to input a number and counts the numbers up to the given number. for ex. input 5, output will be 0 1 2 3 4 5. I have a question on how to add a second given number, for ex. input 5 & 10, output should be 5 6 7 8 9 10. And also vice versa input 10 & 5, output should be the same. Heres the code: ``` import java.io.*; import java.util.*; class Project1{ Scanner scan=new Scanner(System.in); int n; public void input()throws IOException{ System.out.println("Enter the limit: "); n=scan.nextInt(); } public void compute(){ if(n>1) System.out.println("First "+n+" natural numbers are: "); else System.out.println("First "+n+" natural number is: "); for(int i=0; i<=n; i++) System.out.println(i); } public static void main(String[] args)throws IOException{ Project1 obj=new Project1(); obj.input(); obj.compute(); } } ```
2016/03/13
[ "https://Stackoverflow.com/questions/35975450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6058090/" ]
There is a documented way to do this. See `UITableView.beginUpdates()` [documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/beginUpdates): > > You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell. > > > So, the correct solution is: ``` tableView.beginUpdates() tableView.endUpdates() ``` Also note that there is a feature that is not documented - you can add a completion handler for the update animation here, too: ``` tableView.beginUpdates() CATransaction.setCompletionBlock { // this will be called when the update animation ends } tableView.endUpdates() ``` However, tread lightly, it's not documented (but it works because `UITableView` uses a `CATransaction` for the animation).
You can get automatic cell height by this code ``` tableView.beginUpdates() // add label text update code here // label.numberOfLines = label.numberOfLines == 0 ? 1 : 0 tableView.endUpdates() ``` Below is the reference to this solution with demo : [GitHub-RayFix-MultiLineDemo](https://github.com/rayfix/MultilineDemo)
68,681,286
I work with database which I input. I declared array and wanted to push another array in first one. When I try to use my 2 dimensional array, console returned `undefined`. ```js let dataAboutCovid = []; let date, totalCases, todayCases, recovered; let country = "USA"; //Read file from input //Control if country exist //Put data about covid in dataAboutCovid function readFile(input) { let database; for (i = 0; i < input.files.length; i++) { let reader = new FileReader(); reader.readAsText(input.files[i]); reader.onload = function(e) { database = e.target.result; let arrayOfCountry = database.split(`\n`).find((item) => item.includes(country)) if (!arrayOfCountry) { return } if (arrayOfCountry.slice(0, 3) == ",,,") { date = arrayOfCountry.slice(3, this.length).split(",")[1].split(" ")[0]; totalCases = arrayOfCountry.slice(3, this.length).split(",")[4]; todayCases = arrayOfCountry.slice(3, this.length).split(",")[5]; recovered = arrayOfCountry.slice(3, this.length).split(",")[6]; dataAboutCovid.push([date, totalCases, todayCases, recovered]); } } }; console.log(dataAboutCovid[1][1]) } ```
2021/08/06
[ "https://Stackoverflow.com/questions/68681286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15673856/" ]
This has worked for me, with the `.get_attribute` ``` driver.get("https://tn.tunisiebooking.com/") select = driver.find_element_by_xpath("//select[@id='ville_des']") option = Select(select) option.select_by_index(3) #code to choose the option "Sousse" ,date- 06/08/21, and click on "Rechercher". search = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"((//div[@class='col-lg-5 col-md-5 col-sm-5'])[1])"))) search.click() hotels = driver.find_elements_by_xpath("//div[starts-with(@id,'produit_affair')]") for hotel in hotels: name = hotel.find_element_by_tag_name("h3").text argmts = hotel.find_element_by_class_name("angle_active").text #taken the help of contains() and tried to get the static part of the element ID. prize = hotel.find_element_by_xpath(".//div[contains(@id,'prixtotal_')]").get_attribute("innerText") print(name) print(argmts + ':' + prize) driver.quit() ``` **O/P** <https://i.stack.imgur.com/FdYJX.png>
I would get each hotel element separately, move to it and then get inner elements details. Also, the best way to get elements inside element is with XPath staring with dot `.` as below. Try this: ```py from selenium.webdriver.common.action_chains import ActionChains actions = ActionChains(driver) hotels = driver.find_elements_by_xpath("//div[starts-with(@id,'produit_affair')]") for i in range (1, len(hotels)+1): hotel = driver.find_element_by_xpath("(//div[starts-with(@id,'produit_affair')])[" + str(i) + "]") actions.move_to_element(hotel).perform() time.sleep(0.5) name = hotel.find_element_by_xpath(".//h3").text argmts = hotel.find_element_by_xpath(".//div[@class='angle_active']").text prize = hotel.find_element_by_xpath(".//div[starts-with(@id,'prixtotal_')]").text print(name) print(argmts + ':' + prize) driver.quit() ```
55,675
I have to replace one of the O-Rings in a leaky faucet, and would have to shut off the water valve to said faucet. However, the faucets in my place don't have individual shut off valves, and there is only one main valve. I am hesitant in shutting off the main valve, because it has been known to leak in the past upon re-opening. I have a water softener installed that is fed from the pipe from the main valve, the water softener then feeds the hot water tank and breaks off to feed the rest of the cold water in the house. If I was to shut off the water softener(unplug it) without changing it in bypass mode, would this turn off the cold water supply to the rest of my house?
2014/12/23
[ "https://diy.stackexchange.com/questions/55675", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/30011/" ]
The power to the softener is only used to run the backwash and recharge cycle. It will continue to operate without power, and will even continue to soften water for a while (though it does eventually need to be recharged, depending on the hardness of your water and how much you use). --- Certain types of bypasses can be used as shut-off valves. A custom-built one with 3 valves is easy: just close all valves. ![custom bypass](https://i.stack.imgur.com/oeQGfm.jpg) There's a type with two valves that can also be used: close one (so the valves are in opposite directions). ![Two-valve bypass](https://i.stack.imgur.com/1YeO2m.jpg) ![Two-valve bypass](https://i.stack.imgur.com/37QGQm.jpg) --- Other types that only have one valve/control handle don't shut off the water flowing through them. ![Handle bypass](https://i.stack.imgur.com/mSrOsm.jpg) ![Push bypass](https://i.stack.imgur.com/CqzLjm.jpg) ![Turn bypass](https://i.stack.imgur.com/zpzaZm.jpg) --- Separately, you should have a main-shutoff that is reliable. If you have a leak in your house it will likely cost much more than a valve will. Install a ball (quarter turn) valve, rather than a globe or gate valve -- very reliable, and will easily last at least a couple decades.
No, even without power, water will still flow through the water softener. You have to shut off the flow of water via a valve.
55,675
I have to replace one of the O-Rings in a leaky faucet, and would have to shut off the water valve to said faucet. However, the faucets in my place don't have individual shut off valves, and there is only one main valve. I am hesitant in shutting off the main valve, because it has been known to leak in the past upon re-opening. I have a water softener installed that is fed from the pipe from the main valve, the water softener then feeds the hot water tank and breaks off to feed the rest of the cold water in the house. If I was to shut off the water softener(unplug it) without changing it in bypass mode, would this turn off the cold water supply to the rest of my house?
2014/12/23
[ "https://diy.stackexchange.com/questions/55675", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/30011/" ]
No, the water softener electrical portion just determines when and the frequency of regeneration but it has no effect on whether water will or not pass through the unit
No, even without power, water will still flow through the water softener. You have to shut off the flow of water via a valve.
38,076,217
I am stuck with this problem. Consider the following table. I only know the value A(i.e. I can use something like `SELECT * from table WHERE user_one = A`). I tried doing a self join, but that didn't help. **Given table** ``` +----------+-----------+---------+ | USER_ONE | USER_TWO | STATUS | +----------+-----------+---------+ | | | | | A | B | 0 | | | | | | B | A | 1 | | | | | | A | C | 1 | | | | | | C | A | 1 | | | | | | D | A | 1 | | | | | | A | E | 0 | +----------+-----------+---------+ ``` My desired result needs to be the following. Imagine `user_one` is following `user_two` if status is 1.Status 0 means, the `user_one` was previously following `user_two`, but now he unfollowed `user_two`. I need the users Who are following "A". Notice that I **don't want**, the rows where they are both following each other like `(A -> B)` and `(B -> A)` both has Status 1. So the question to the following response would be something like, "Find me people following A, but A is not following them", makes sense? A little help would be appreciated. **Desired Rows** ``` +----------+-----------+---------+ | USER_ONE | USER_TWO | STATUS | +----------+-----------+---------+ | | | | | B | A | 1 | | | | | | D | A | 1 | +----------+-----------+---------+ ```
2016/06/28
[ "https://Stackoverflow.com/questions/38076217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3959018/" ]
Use `mouseenter` instead of `mousemove`. This only gets called once, when the mouse enters the element. ```html <table class="table table-hover"> <tbody> <tr *ngFor="let td of data; let i = index" (mousedown)="onSelectionStart(i)" (mouseenter)="onSelection(i)" (mouseup)="onSelectionEnd()" [class.selected]="td"> <td>row {{ i }}</td> <td>selected: {{ td }}</td> </tr> </tbody> </table> ``` --- > > See your updated [Plunker](https://plnkr.co/edit/HnDXIdCJ5PKYsTQuqEuV?p=preview) for a working example > > >
I don't think that it's not possible declarative right now with Angular2 / Rxjs since you don't have an asynchronous data flow. The following issue aims to provide observables from elements / events: * <https://github.com/angular/angular/issues/4062> You could achieve this by leveraging the `Observable.fromEvent` method directly... Here is a sample: ``` @Component({ template: ` <tr #tr ngFor="..."> </tr> ` }) export class TableComponent { @ViewChildren('tr') trs:QueryList<ElementRef>; ngAfterViewInit() { this.trs.toArray().forEach((tr)=> { Observable.fromEvent(tr, 'mousedown').subscribe(event => { }); }); } } ```
31,573,913
I was reading this tutorial on building a simple virtual machine/bytecode interpreter. It had instructions like PUSH, POP, HALT, etc... these instructions are decoded and evaluated in a switch, so you would say if the current instruction equals PUSH, then you would push it to a stack. But what if I wanted to print out a string or character? In assembly, you would use make a string in `.data`, push the length, then the message, then the file descriptor for stdout (1), the system write call number so 4 (for 32 bit), and then do int 80. How would I do something like this for a virtual machine? Would I handle it similarly? I thought maybe I could just dump whatever I wanted to write in a register, and then printf the contents when it has something other than (magic number) in it, but that doesn't seem like a good idea.
2015/07/22
[ "https://Stackoverflow.com/questions/31573913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3403431/" ]
You can use an input, and read it's value in your function. I also improved your function a little (while not changing functionality). ``` <!DOCTYPE html> <html> <body> <center> <input type="number" id="max" value="3"/> <button onclick="myFunction()" style="font-size: 17pt; margin-top: 5%;">Roll it</button> </center> <br> <center> <span id="demo" style="margin: 10% 5%; font-size: 45pt; color: blue;"></span> <span id="demo1" style="margin: 2% 5%; font-size: 45pt; color: red;"></span> </center> <script> function myFunction() { var max = document.getElementById('max').value || 3; var x = Math.floor((Math.random() * max) + 1); document.getElementById("demo").innerHTML = x; do { var y = Math.floor((Math.random() * max) + 1); } while (x === y); document.getElementById("demo1").innerHTML = y; } </script> </body> </html> ``` See [jsfiddle](http://jsfiddle.net/jscissr/k8ehjyw5/).
Try this way: ``` <!DOCTYPE html> <html> <body> <center> <input type="text" id="var" /> <br> <button onclick="myFunction()" style="font-size: 17pt; margin-top: 5%;">Roll it</button> </center> <br> <center> <span id="demo" style="margin: 10% 5%; font-size: 45pt; color: blue;"></span> <span id="demo1" style="margin: 2% 5%; font-size: 45pt; color: red;"></span> </center> <script> function myFunction() { debugger var x = Math.floor((Math.random() * document.getElementById("var").value) + 1); document.getElementById("demo").innerHTML = x; var y = Math.floor((Math.random() * document.getElementById("var").value) + 1); document.getElementById("demo1").innerHTML = y; if (x == y) { myFunction(); } else { } } </script> </body> </html> ``` Hope help you
39,534,919
I have a mongoose model containing 2 properties Array of String and some others: ``` var Model = new Schema({ _id: {type: Number, required: true, unique: true}, name: {type: String, required: true}, oneList: [String], anotherList: [String] }); ``` I create the model: ``` var model = new Model({ _id: 1, name: 'model', oneList: ['a', 'b'], anotherList: ['c', 'd'] }) ``` but when I inspect the model all the list are undefined: ``` model._doc === { _id: 1, name: 'model', oneList: undefined, anotherList: undefined } ``` I tried some variations: * change the model definition from [String] to [ ] * create separately the data outside the model then pass it * create the model without list data then add it to the model Even when I create an empty model: ``` var model = new Model({}) model._doc.oneList === undefined model._doc.anotherList === undefined ``` Context: **The problem occurs on a docker container but not on my local machine** node: v4.4.7 mongoose: v4.6.0 [GitHub](https://github.com/Automattic/mongoose/issues/4534)
2016/09/16
[ "https://Stackoverflow.com/questions/39534919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2785486/" ]
I had the same issue, apparently when you have a nested array within your model, mongoose has an [open issue 1335](https://github.com/Automattic/mongoose/issues/1335#issuecomment-90991319) that saves an empty array when a property references a schema. I experimented with presaves to force the property to be an empty array if the property's length is 0 or undefined. Also be careful when specifying `unique=true` in the property's schema, as empty or undefined properties will violate the indexing and throw an error. Note: ``` var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); var barSchema = new mongoose.Schema({ baz: String }); var fooSchema = new mongoose.Schema({ bars: [barSchema] }); var Foo = mongoose.model('Foo', fooSchema); var foo = new Foo(); console.log(foo); // { _id: 55256e20e3c38434687034fb, bars: [] } foo.save(function(err, foo2) { console.log(foo2); // { __v: 0, _id: 55256e20e3c38434687034fb, bars: [] } foo2.bars = undefined; foo2.save(function(err, foo3) { console.log(foo3); // { __v: 0, _id: 55256e20e3c38434687034fb, bars: undefined } Foo.findOne({ _id: foo3._id }, function(err, foo4) { console.log(foo4); // { _id: 55256e20e3c38434687034fb, __v: 0, bars: [] } mongoose.disconnect(); }); }); }); ```
You can do like this: ``` var schema = new Schema({ _id: { type: Number, required: true, unique: true }, name: { type: String, required: true }, oneList: [String], anotherList: [String] }), Model = mongoose.model('Model', schema), m = new Model(); m._id = 1; m.name = 'model'; m.oneList.push('a', 'b'); m.anotherList.push('c', 'd'); ```
14,215,361
When adding a new project into workspace it is not possible to expand it, it is not compilable, and it's related files are not accessible, it seems as if xcode treat it as a resource file ( although it is able to resolve the proper icon ). This is the way I add the proj 1. xcode->File->Add Files to "%ProjName%" 2. Select the project file What am I doing wrong here ?
2013/01/08
[ "https://Stackoverflow.com/questions/14215361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927438/" ]
The problem was that I had the project being added opened in another IDE, having that other IDE closed resolved the problem
Right click on your project & select new project give name which adds new project in your workspace. See image for reference. ![see here](https://i.stack.imgur.com/qwaJD.png). You can also add new project by drag & drop.
41,981,190
Iam working on a website and I want to show someone the difference between two fonts on the website on different pages. Is there a way that I can code it that I can switch between fonts easily? I was thinking about making an second stylesheet with the 2nd font in it and use jQuery to disable/enable the stylesheet. But this means I have to place this on every page there is. Is there a better way for this?
2017/02/01
[ "https://Stackoverflow.com/questions/41981190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4113598/" ]
you can use two classes with different fonts and toggle them using JS/jQuery
Yes you can do that easily with Js/Jquery. You just simply toggle a class with different *"font-familys"*. Here would be a example if you want to change the font in one div: ```css body, html { width: 100%; height: 100%; padding: 0; margin: 0; } .text { height: 100%; width: 100%; padding: 500px; box-sizing: border-box; font-family: cursive; } .font { font-family: monospace !important; } button { position: relative; left: 50%; transform: translate(-50%); background-color: black; border: none; color: white; margin: 20px; } ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>FontChange</title> <link rel="stylesheet" type="text/css" href="test.css"> <!-- Hosted jQuery libary --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("button").click(function () { $(".text").toggleClass("font"); }) }); </script> </head> <body> <div class="text"> <button>Click me to change the font-family!</button></br> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </div> </body> </html> ```
356,729
I just set up OSSEC, but I accidentally shut myself out already from my home ip. So does OSSEC have a function to unblock an IP after it is blocked or do I need to do this manually in iptables ? Also does OSSEC provide a way to temporary ban IP's ?
2012/02/03
[ "https://serverfault.com/questions/356729", "https://serverfault.com", "https://serverfault.com/users/86280/" ]
To manually unblock them you need to change the ‘add’ to ‘delete’, so to the delete the previous rules it would be: ``` /var/ossec/active-response/bin/host-deny.sh delete - 188.163.238.252 1328614852.61546 5712 /var/ossec/active-response/bin/firewall-drop.sh delete - 188.163.238.252 1328614852.61546 5712 ``` Sometimes rules are to strict or not strict enough. You might want to change something or add something yourself. This can be done in local\_rules.xml file. Suggest we want to increase the tresshold of failed login on http auth for apache2. If we look at the apache\_rules.xml we see a number of rules. The interesting one is: ``` <rule id="30119" level="12" frequency="6" timeframe="120"> <if_matched_sid>30118</if_matched_sid> <same_source_ip /> <description>Multiple attempts blocked by Mod Security.</description> <group>access_denied,</group> </rule> ``` To change the frequency from 6 to 10, we need to copy the rule and paste it in local\_rules.xml. Then we add a parameter overwrite=”yes” to tell OSSEC it needs to overwrite the rule defined in apache\_rules.xml and instead use the one defined in local\_rules.xml. The rule would look like this: ``` <rule id="30119" level="12" frequency="10" timeframe="120" overwrite="yes"> <if_matched_sid>30118</if_matched_sid> <same_source_ip /> <description>Multiple attempts blocked by Mod Security.</description> <group>access_denied,</group> </rule> ``` If we want to completely ignore this rule as it is not relevant for us, we just change the level to 0: ``` <rule id="30119" level="0" frequency="10" timeframe="120" overwrite="yes"> <if_matched_sid>30118</if_matched_sid> <same_source_ip /> <description>Multiple attempts blocked by Mod Security.</description> <group>access_denied,</group> </rule> ``` Excerpt from [my blog](http://cloud101.eu/blog/2012/03/01/ossec-keeping-your-system-safe-from-nasty-scanners-and-attackers/) answers this question.
An *I-need-to-unblock-IP-quickly* approach (replace `1.2.3.4` with your IP): ``` $ iptables -L | grep 1.2.3.4 $ grep 1.2.3.4 /etc/hosts.deny ``` --- If the IP is found in `iptables's DROP` rule, then run: ``` /var/ossec/active-response/bin/firewall-drop.sh delete - 1.2.3.4 ``` If the IP is found in `/etc/hosts.deny`, then run ``` /var/ossec/active-response/bin/host-deny.sh delete - 1.2.3.4 ```
3,669,660
All PropertyGrid examples I have seen allow the user to edit a single object, which PropertyGrid scans by reflection. I would like the user to be able to edit, for example, an ini file or a plain-old Dictionary, with one line per key-value pair. Is this possible?
2010/09/08
[ "https://Stackoverflow.com/questions/3669660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22820/" ]
Yes. Some years ago, I wrote [some code](http://blog.differentpla.net/blog/2005/02/26/using-propertygrid-with-a-dictionary-object) to display an `IDictionary` in a `PropertyGrid`.
The `PropertyGrid` will allow the editing of any property that has get and set accessors or an appropriate editor attached to it or the type it provides that describes how to convert or even edit that value. Therefore, if you expose a property that is, for example, a `Stream` of an INI file and attach a custom [`TypeConverter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx) that expands it to the name/value pairs within it, you can indeed edit an INI file with the `PropertyGrid`. Useful links: * [`EditorAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.editorattribute.aspx) * [`TypeConverter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx) * [`TypeConverterAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverterattribute.aspx) * Other types within the [`System.ComponentModel`](http://msdn.microsoft.com/en-us/library/system.componentmodel.aspx) namespace ### Type converters A type converter is attached to a type using a `TypeConverterAttribute` declaration. Type converters allow you to provide rules on how to convert your type to and from other types. A range of overrides are provided to tailor your conversions, all beginning with `Convert`. Through various `GetPropertiesxxxx` calls, type converters also allow you to specify what properties your type has that can be edited and how they appear (their names, for example). This makes it possible to expand values (like editing the `Point` type) and show or hide properties based on the state of a value (for example, your INI file would use this to show or hide made-up properties based on the contents of the file). Type converters also allow you to specify a list of values that your type can show as a drop-down list when being edited. This is provided by the `GetStandardValuesXxx` set of overrides and can be useful if you don't want to create a custom editor but you have a fixed list of allowable values. ### Editors Editors allow you to fine tune the design time experience of editing an instance of a type. They can be attached to a property or a type and indicate to the `PropertyGrid` what editor to use when editing a value. This allows you to show a dialog or your own dropdown with some custom user interface (for example, a slider).
3,669,660
All PropertyGrid examples I have seen allow the user to edit a single object, which PropertyGrid scans by reflection. I would like the user to be able to edit, for example, an ini file or a plain-old Dictionary, with one line per key-value pair. Is this possible?
2010/09/08
[ "https://Stackoverflow.com/questions/3669660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22820/" ]
Here is a complete example derived from the code that Roger linked to. I updated it so that * It uses `Dictionary<GridProperty,object>` instead of IDictionary * Each `GridProperty` specifies a name, category, description, etc. (Note, this post has been changed from my original design.) Thanks Roger! ``` public partial class PropertyEditor : Form { public PropertyEditor() { InitializeComponent(); var dict = new Dictionary<GridProperty, object>(); dict["Food"] = "Poutine"; dict["Ball"] = "Football"; dict[new GridProperty("1. Greeting", "Words", "The first word to say")] = "Hello"; dict[new GridProperty("2. Subject", "Words", "The second word to say")] = "Dogs"; dict[new GridProperty("3. Verb", "Words", "The third word to say")] = "Like"; dict[new GridProperty("4. Object", "Words", "The fourth word to say")] = "Burritos"; dict[new GridProperty("Integer", "Types", "")] = 42; dict[new GridProperty("Double", "Types", "")] = 42.5; dict[new GridProperty("Color", "Types", "")] = Color.ForestGreen; propertyGrid1.SelectedObject = new DictionaryPropertyGridAdapter(dict, "Stuff"); } } /// <summary> /// Holds information about a property in a Dictionary-based PropertyGrid /// </summary> public class GridProperty { public GridProperty(string name) { Name = name; } public GridProperty(string name, string category) { Name = name; Category = category; } public GridProperty(string name, string category, string description) { Name = name; Category = category; Description = description; } public string Name { get; private set; } public string Category { get; private set; } public string Description { get; set; } public bool IsReadOnly { get; set; } public object DefaultValue { get; set; } // shown if value is null public static implicit operator GridProperty(string name) { return new GridProperty(name); } } /// <summary>An object that wraps a dictionary so that it can be used as the /// SelectedObject property of a standard PropertyGrid control.</summary> /// <example> /// propertyGrid.SelectedObject = new DictionaryPropertyGridAdapter(dict, ""); /// </example> public class DictionaryPropertyGridAdapter : ICustomTypeDescriptor { internal IDictionary<GridProperty, object> _dictionary; internal string _defaultCategory; public DictionaryPropertyGridAdapter(Dictionary<GridProperty, object> dict, string defaultCategory) { _dictionary = dict; _defaultCategory = defaultCategory; } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { var props = new PropertyDescriptor[_dictionary.Count]; int i = 0; foreach (var prop in _dictionary) props[i++] = new GridPropertyDescriptor(prop.Key, this); return new PropertyDescriptorCollection(props); } #region Boilerplate #region Never called public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { return GetProperties(null); } #endregion public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return _dictionary; } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public PropertyDescriptor GetDefaultProperty() { return null; } #endregion class GridPropertyDescriptor : PropertyDescriptor { GridProperty _prop; DictionaryPropertyGridAdapter _parent; internal GridPropertyDescriptor(GridProperty prop, DictionaryPropertyGridAdapter parent) : base(prop.Name, null) { _prop = prop; _parent = parent; } public override string Description { get { return _prop.Description; } } public override string Category { get { return _prop.Category ?? _parent._defaultCategory; } } public override Type PropertyType { get { return (_parent._dictionary[_prop] ?? _prop.DefaultValue ?? "").GetType(); } } public override void SetValue(object component, object value) { _parent._dictionary[_prop] = value; } public override object GetValue(object component) { return _parent._dictionary[_prop]; } public override bool IsReadOnly { get { return _prop.IsReadOnly; } } public override Type ComponentType { get { return null; } } public override bool CanResetValue(object component) { return _prop.DefaultValue != null; } public override void ResetValue(object component) { SetValue(component, _prop.DefaultValue); } public override bool ShouldSerializeValue(object component) { return false; } } } ```
The `PropertyGrid` will allow the editing of any property that has get and set accessors or an appropriate editor attached to it or the type it provides that describes how to convert or even edit that value. Therefore, if you expose a property that is, for example, a `Stream` of an INI file and attach a custom [`TypeConverter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx) that expands it to the name/value pairs within it, you can indeed edit an INI file with the `PropertyGrid`. Useful links: * [`EditorAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.editorattribute.aspx) * [`TypeConverter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx) * [`TypeConverterAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverterattribute.aspx) * Other types within the [`System.ComponentModel`](http://msdn.microsoft.com/en-us/library/system.componentmodel.aspx) namespace ### Type converters A type converter is attached to a type using a `TypeConverterAttribute` declaration. Type converters allow you to provide rules on how to convert your type to and from other types. A range of overrides are provided to tailor your conversions, all beginning with `Convert`. Through various `GetPropertiesxxxx` calls, type converters also allow you to specify what properties your type has that can be edited and how they appear (their names, for example). This makes it possible to expand values (like editing the `Point` type) and show or hide properties based on the state of a value (for example, your INI file would use this to show or hide made-up properties based on the contents of the file). Type converters also allow you to specify a list of values that your type can show as a drop-down list when being edited. This is provided by the `GetStandardValuesXxx` set of overrides and can be useful if you don't want to create a custom editor but you have a fixed list of allowable values. ### Editors Editors allow you to fine tune the design time experience of editing an instance of a type. They can be attached to a property or a type and indicate to the `PropertyGrid` what editor to use when editing a value. This allows you to show a dialog or your own dropdown with some custom user interface (for example, a slider).
3,669,660
All PropertyGrid examples I have seen allow the user to edit a single object, which PropertyGrid scans by reflection. I would like the user to be able to edit, for example, an ini file or a plain-old Dictionary, with one line per key-value pair. Is this possible?
2010/09/08
[ "https://Stackoverflow.com/questions/3669660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22820/" ]
Yes. Some years ago, I wrote [some code](http://blog.differentpla.net/blog/2005/02/26/using-propertygrid-with-a-dictionary-object) to display an `IDictionary` in a `PropertyGrid`.
Here is a complete example derived from the code that Roger linked to. I updated it so that * It uses `Dictionary<GridProperty,object>` instead of IDictionary * Each `GridProperty` specifies a name, category, description, etc. (Note, this post has been changed from my original design.) Thanks Roger! ``` public partial class PropertyEditor : Form { public PropertyEditor() { InitializeComponent(); var dict = new Dictionary<GridProperty, object>(); dict["Food"] = "Poutine"; dict["Ball"] = "Football"; dict[new GridProperty("1. Greeting", "Words", "The first word to say")] = "Hello"; dict[new GridProperty("2. Subject", "Words", "The second word to say")] = "Dogs"; dict[new GridProperty("3. Verb", "Words", "The third word to say")] = "Like"; dict[new GridProperty("4. Object", "Words", "The fourth word to say")] = "Burritos"; dict[new GridProperty("Integer", "Types", "")] = 42; dict[new GridProperty("Double", "Types", "")] = 42.5; dict[new GridProperty("Color", "Types", "")] = Color.ForestGreen; propertyGrid1.SelectedObject = new DictionaryPropertyGridAdapter(dict, "Stuff"); } } /// <summary> /// Holds information about a property in a Dictionary-based PropertyGrid /// </summary> public class GridProperty { public GridProperty(string name) { Name = name; } public GridProperty(string name, string category) { Name = name; Category = category; } public GridProperty(string name, string category, string description) { Name = name; Category = category; Description = description; } public string Name { get; private set; } public string Category { get; private set; } public string Description { get; set; } public bool IsReadOnly { get; set; } public object DefaultValue { get; set; } // shown if value is null public static implicit operator GridProperty(string name) { return new GridProperty(name); } } /// <summary>An object that wraps a dictionary so that it can be used as the /// SelectedObject property of a standard PropertyGrid control.</summary> /// <example> /// propertyGrid.SelectedObject = new DictionaryPropertyGridAdapter(dict, ""); /// </example> public class DictionaryPropertyGridAdapter : ICustomTypeDescriptor { internal IDictionary<GridProperty, object> _dictionary; internal string _defaultCategory; public DictionaryPropertyGridAdapter(Dictionary<GridProperty, object> dict, string defaultCategory) { _dictionary = dict; _defaultCategory = defaultCategory; } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { var props = new PropertyDescriptor[_dictionary.Count]; int i = 0; foreach (var prop in _dictionary) props[i++] = new GridPropertyDescriptor(prop.Key, this); return new PropertyDescriptorCollection(props); } #region Boilerplate #region Never called public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { return GetProperties(null); } #endregion public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return _dictionary; } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public PropertyDescriptor GetDefaultProperty() { return null; } #endregion class GridPropertyDescriptor : PropertyDescriptor { GridProperty _prop; DictionaryPropertyGridAdapter _parent; internal GridPropertyDescriptor(GridProperty prop, DictionaryPropertyGridAdapter parent) : base(prop.Name, null) { _prop = prop; _parent = parent; } public override string Description { get { return _prop.Description; } } public override string Category { get { return _prop.Category ?? _parent._defaultCategory; } } public override Type PropertyType { get { return (_parent._dictionary[_prop] ?? _prop.DefaultValue ?? "").GetType(); } } public override void SetValue(object component, object value) { _parent._dictionary[_prop] = value; } public override object GetValue(object component) { return _parent._dictionary[_prop]; } public override bool IsReadOnly { get { return _prop.IsReadOnly; } } public override Type ComponentType { get { return null; } } public override bool CanResetValue(object component) { return _prop.DefaultValue != null; } public override void ResetValue(object component) { SetValue(component, _prop.DefaultValue); } public override bool ShouldSerializeValue(object component) { return false; } } } ```
17,840,567
For example if I have this html: ``` <div class="wrapper"> <div id="one"></div> <div id="two">this is the div i want to move</div> <div id="three"></div> <div id="four"></div> </div> ``` How can I move the div with the id "two" after all the other divs so my html becomes: ``` <div class="wrapper"> <div id="one"></div> <div id="three"></div> <div id="four"></div> <div id="two">this is the div i want to move</div> </div> ```
2013/07/24
[ "https://Stackoverflow.com/questions/17840567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217162/" ]
This must work : ``` $("#two").appendTo(".wrapper"); ``` This must also work : ``` $(".wrapper").append($("#two")); ``` [`append`](http://api.jquery.com/append/) and [`appendTo`](http://api.jquery.com/appendto/) are considered moving functions in jQuery. You must look at the docs more. Demo : <http://jsfiddle.net/hungerpain/gjJJe/>
You can try this: ``` $("#two").appendTo(".wrapper") ``` Example: <http://jsfiddle.net/SbeDN/>
312,336
I have multiple stores on my website. I need to get the store currency code by store Id. How can I get it? I was trying by below code but it's always returning default store currency code: ``` $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); $storeCurrencyCode = $storeManager->getStore()->getCurrentCurrencyCode(); ``` Thanks for your cooperation. **[Update with Solution]** I have got the solution after reviewing Magento core code. My solution code below: ``` $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface'); // Return Default Store Currency Code $defaultCurrencyCode = $storeManager->getStore()->getCurrentCurrencyCode(); // Return Specific Store Currency Code $storeId = 1; // it can be any store id $storeCurrencyCode = $storeManager->getStore($storeId)->getCurrentCurrencyCode(); ``` Thanks for your time.
2020/05/08
[ "https://magento.stackexchange.com/questions/312336", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/7913/" ]
best way to check customer session is login or not if login then shows the logout button and not logged in then show the login button. Check below code I just get the customer session using object manager and set conditions. try to find the template for use login HTML code and add condition there. Template code ``` <?php $objectManagerlogin = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManagerlogin->get('Magento\Customer\Model\Session'); $baseurl = $objectManagerlogin->get('Magento\Store\Model\StoreManagerInterface')->getStore(0)->getBaseUrl(); ?> <div class="logincs"> <?php if($customerSession->isLoggedIn()) { ?> <a href="<?php echo $baseurl .'customer/account/logout'; ?>"><span>Logout</span> <?php }else{ ?> <a href="<?php echo $baseurl .'customer/account/login/'; ?>">Login</a> <?php } ?> </div> ```
You can set the condition for the logged In customers and hide or change the text with a link for the button. To check the customer is logged In or not you can use below two methods. **Using ObjectManager** ``` <?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $userContext = $objectManager->get('Magento\Framework\App\Http\Context'); $isLoggedIn = $userContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH); ?> <?php if($isLoggedIn): ?> <a href="<?= $this->getUrl('customer/account/logout') ?>"><?= __('Logout') ?></a> <?php else: ?> <a href="<?= $this->getUrl('customer/account/login') ?>"><?= __('Login') ?></a> <?php endif; ?> ``` **Using Dependency Injection** You can check Customer is logged in or not by below way, In Block file, Pass Magento\Framework\App\Http\Context as a dependency to the construct method. > > **app/code/Vendor/Module/Block/Customer.php** > > > ``` <?php namespace Vendor\Module\Block; class Customer extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\App\Http\Context $httpContext, array $data = [] ) { $this->httpContext = $httpContext; parent::__construct($context, $data); } /* * return bool */ public function getIsLogin() { return $this->httpContext->isLoggedIn(); } ?> ``` And then Call **getIsLogin** function in template PHTML file. ``` $isLoggedin = $block->getIsLogin(); <?php if($isLoggedIn): ?> <a href="<?= $this->getUrl('customer/account/logout') ?>"><?= __('Logout') ?></a> <?php else: ?> <a href="<?= $this->getUrl('customer/account/login') ?>"><?= __('Login') ?></a> <?php endif; ?> ```
51,641,374
I'm new to pthread and attempting to implement a producer/consumer problem that will let the user pick buffer size, # of producers, # of consumers, and total # of items. I've been looking through what I thought were similar things on stack overflow, but can't seem to get it right. My code has a main class and it spawns producers and consumers. It hands the producers and consumers a pointer to a stack initialized in main (or at least I'm trying to). I thought that what I was doing was legal and in CLion I get the predictive text options I want so I thought I linked it properly but I'm segfaulting when I try to read the top element. I used GDB to make sure I knew what line I was crashing on, but don't understand what's wrong with my setup. While debugging I confirmed that a producer goes through its push() command first, but the consumer fails when attempting top() or pop(). I'd seen some threads here where the OP had problems because they didn't join their threads, but I am so I'm a little lost. ``` #include <iostream> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <stack> #include <cstring> #include <semaphore.h> #include <pthread.h> #define N 10000 sem_t mutex; sem_t fullCount; sem_t emptyCount; int iCount = 0; typedef struct _thread_data{ int id; int itemcount; std::stack<char>* ptr; }thread_data; void *producer(void *arg){ std::cout << "spawned producer\n"; thread_data *data = (thread_data *)arg; while(true){ char message = 'X'; sem_wait(&emptyCount); sem_wait(&mutex); if(iCount < data->itemcount){ data->ptr->push(message); iCount++; char temp [25]; sprintf(temp, "p:<%u>, item: %c, at %d\n", data->id, message, data->ptr->size()); std::cout << temp; //std::cout << "hi I'm a producer\n"; sem_post(&mutex); sem_post(&fullCount); } else{ sem_post(&fullCount); sem_post(&mutex); pthread_exit(nullptr); } } } void *consumer(void *arg){ std::cout << ("spawned consumer\n"); thread_data *data = (thread_data *)arg; while(true){ char message; sem_wait(&fullCount); sem_wait(&mutex); if(iCount < data->itemcount) { message = data->ptr->top(); //SEGFAULT char temp[25]; printf(temp, "c:<%u>, item: %c, at %d\n", data->id, message, data->ptr->size()); data->ptr->pop(); std::cout << temp; //std::cout << "Hi I'm a consumer\n"; sem_post(&mutex); sem_post(&emptyCount); } else if (iCount == data->itemcount){ message = data->ptr->top(); //SEGFAULT char temp[25]; printf(temp, "c:<%u>, item: %c, at %d\n", data->id, message, data->ptr->size()); data->ptr->pop(); std::cout << temp; sem_post(&emptyCount); sem_post(&mutex); pthread_exit(nullptr); } else{ sem_post(&mutex); pthread_exit(nullptr); } } } int main(int argc, char *argv[]){ int bufferSize = N; int pThreadCount,cThreadCount,itemCount; for (int x = 0; x < argc; ++x) { if(strcmp(argv[x],"-b") == 0){ bufferSize = atoi(argv[x+1]); } if(strcmp(argv[x],"-p") == 0){ pThreadCount = atoi(argv[x+1]); } if(strcmp(argv[x],"-c") == 0){ cThreadCount = atoi(argv[x+1]); } if(strcmp(argv[x],"-i") == 0){ itemCount = atoi(argv[x+1]); } } sem_init(&mutex,1,1); sem_init(&fullCount,1,0); sem_init(&emptyCount,1,bufferSize); std::stack<char> myStack; pthread_t myPThreads[pThreadCount]; thread_data thrData[pThreadCount]; pthread_t myCThreads[cThreadCount]; thread_data cThrData[cThreadCount]; for (int i = 0; i < pThreadCount; ++i) { thrData[i].id = i; thrData[i].itemcount = itemCount; thrData[i].ptr = &myStack; pthread_create(&myPThreads[i], NULL, producer, &thrData[i]); } for (int i = 0; i < cThreadCount; ++i) { cThrData[i].id = i; cThrData[i].itemcount = itemCount; thrData[i].ptr = &myStack; pthread_create(&myCThreads[i], NULL, consumer, &cThrData[i]); } for (int k = 0; k < pThreadCount; ++k) { pthread_join(myPThreads[k], NULL); } for (int j = 0; j < cThreadCount; ++j) { pthread_join(myCThreads[j], NULL); } return 0; } ```
2018/08/01
[ "https://Stackoverflow.com/questions/51641374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10167563/" ]
`iCount <= data->itemcount` is always true. `consumer` never exits the loop. At some point, it exhausts the stack, and the subsequent `top()` call exhibits undefined behavior.
`cThrData[i].ptr` is never initialized, for any `i`. `consumer` calls `top()` through an uninitialized pointer, whereupon the program exhibits undefined behavior.
37,266,627
Let's go straight to an example: ``` public bool MeetsAllConditions() { bool check1, check2, check3; // Some code to define result of check1 if (something...) { if (something...) { check1 = true; } } // many more code to define check2 and check3 .... if (check1 && check2 && check3) { return true; } return false; } ``` Now, the code to define each `check` is very **expensive**. Hence I would like to make it so that the code that defines result of each check is evaluated **only** **in** **the final** `if` statement. This way I can utilise lazy evaluation to save resource if **any** of the check **fails**. How would I approach this **without defining a separate method** for each `check` in C#?
2016/05/17
[ "https://Stackoverflow.com/questions/37266627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6180359/" ]
It depends by what you mean by a "separate method". If you're willing to create delegates inline in your code, you could do something like this: ``` Func<bool> check1 = () => { if(something...) { if(something...) { return true; } } } ... return check1() && check2() && check3(); ``` Another option is simply to short-circuit and return early any time you notice something that should cause you to return false. ``` if(!something...) { return false; } if(!something...) { return false; } ... // same pattern for check2 and check3 return true; ```
Why not use the `Lazy<T>` ? From [MSDN](https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx) > > Use lazy initialization to defer the creation of a large or > resource-intensive object, or the execution of a resource-intensive > task, particularly when such creation or execution might not occur > during the lifetime of the program. > > > Since you have mentioned Expensive Process, why not encapsulate the expensive process in a Type ?
55,713,024
I have a PC sending the byte value 2 to a Raspberry Pi. But I can't figure out why the Python program does not evaluate to true when it receives the value. If I print the values received it writes b'\x02' as output. ``` import serial def GetSerialData(): x = ser.inWaiting() if x > 0: received_data = ser.read(x) print (received_data) return x ser = serial.Serial ("/dev/ttyAMA0", 9600) try: while True: SData = GetSerialData () if ( SData == b'\x02'): print ("Ok - value is 2") except KeyboardInterrupt: ser.close() ```
2019/04/16
[ "https://Stackoverflow.com/questions/55713024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8983058/" ]
Your `GetSerialData` function does not appear to actually return the serial data. It *prints* the serial data, but then you never refer to `received_data` after that, and instead return `x`, which appears to be an integer representing the size of the response. Instead of returning x, try returning `received_data`. ``` def GetSerialData(): x = ser.inWaiting() if x > 0: return ser.read(x) else: return b"" #or whatever value is appropriate when no data has been sent yet ```
`\x02` is ASCII code for hex 02, which is `STX` (start of text). `\x32` is the ASCII for the digit `2`. If `SData` is an integer or any non-(binary) string, remember to convert it to string with `str(SData)`. Also, in general, `b'A' != 'A'`. You want to use `.encode('ascii')` to convert a Python string to an ASCII binary string. ``` >>> binary_A_from_string = 'A'.encode('ascii') >>> binary_A_from_string b'A' >>> binary_A = '\x41' # ASCII 41 (dec 65) is 'A' >>> binary_A b'A' >>> binary_A == 'A' False >>> binary_A == binary_A_from_string True ``` This is because Python sees binary ASCII strings as different from standard Python strings. Also, make sure that the information read is actually one byte long.
30,560,565
``` import java.util.Scanner; import java.util.Random; public class cominback{ public static void main(String args[]){ Scanner key = new Scanner(System.in); System.out.println(" please enter a password:"); String x = key.nextLine(); System.out.println("Connfirm your password:"); String y = key.nextLine(); if ( x == null) System.out.println("please restart the program:"); if (x != y) System.out.println("wrong password"); if (x == y ) System.out.println("you are logged in"); } } ``` It always print out wrong password for even when the input is same passwords. how can i fix this problem? did i do something wrong or is it my eclipse glitching?
2015/05/31
[ "https://Stackoverflow.com/questions/30560565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4959042/" ]
You should use `equals` method to compare two string like: ``` if (x.equals(y))//password matches ```
The `==` check against reference. Use `equals()` instead for checking if tow string are meaningfully equals. Use the following code snippet - f ``` if( x.equals(y) ){} if( !(x.equals(y)) ){} ``` **Note:** ``` String str1 = "string one"; String str2 = str1; String str3 = "string two"; System.out.println( str1.equals(str3) ); //false; meaningfully not equals. System.out.println( str1 == str2 ); //true; referencing same String content System.out.println( "string one".equals(str1) ); //true; meaningfully equals ```
3,690,994
Let $f(x)$ be an injective function with domain $[a,b]$ and range $[c,d]$. If $\alpha$ is a point in $(a,b)$ such that $f$ has left hand derivative $l$ and right hand derivative $r$ at $x=\alpha$ with both $l$ and $r$ being non-zero different and negative , then prove that the left hand derivative and the right hand derivative of $f^{-1}(x)$ at $x=f(\alpha)$ are $\frac{1}{r}$ and $\frac{1}{l}$ respectively. **My Attempt:** If $g(x)$ be the inverse of $f((x)$ then $f(g(x))=x$ which gives $g'(x)=\frac{1}{f'(g(x))}$. So if $x=f(\alpha)$ then $g'(f(\alpha))=\frac{1}{f'(g(f(\alpha)))}=\frac{1}{f'(\alpha)}$. But now how do I get the left hand derivative and the right hand derivative. I could frame an example $f(x)=\left\{ \begin{array}{ll} \frac{1}{x} & 0<x<2 \\ \frac{2}{x^2} & x\geq 2 \\ \end{array} \right.$ Left hand derivative at $x=2$ equals $\frac{-1}{4}=l$ Right hand derivative at $x=2$ equals $\frac{-1}{2}=r$ $f^{-1}(x)=\left\{ \begin{array}{ll} \\\sqrt {\frac{2}{x}} & 0<x\leq \frac{1}{2} \\ \frac{1}{x} & x> \frac{1}{2} \\ \end{array} \right.$ Left hand derivative of $f^{-1}(x)$ at $x=\frac{1}{2}$ equals $-2=\frac{1}{r}$ Right hand derivative of $f^{-1}(x)$ at $x=\frac{1}{2}$ equals $-4=\frac{1}{l}$ But I am not able to get a proper method.
2020/05/25
[ "https://math.stackexchange.com/questions/3690994", "https://math.stackexchange.com", "https://math.stackexchange.com/users/171392/" ]
We have $f'\_-(\alpha)=l < 0$ and $f'\_+(\alpha)=r < 0$, with $l \neq r$. That implies, for $h > 0$ small enough, that $f(\alpha - h) > f(\alpha) > f(\alpha + h)$. Since $f$ has a left and a right derivative at $\alpha$, it is continuous at $\alpha$. Let $\beta = f(\alpha)$ and given $h > 0$, let $k\_1 = f(\alpha + h) - f(\alpha)$ and $k\_2 = f(\alpha - h) - f(\alpha)$. Note that $k\_1 < 0$ and $k\_2 > 0$. Then $\frac{g(\beta + k\_1) - g(\beta)}{k\_1}=\frac{h}{f(\alpha + h) - f(\alpha)} \to\_{h \to 0^+} \frac{1}{r}$, and $\frac{g(\beta + k\_2) - g(\beta)}{k\_2}=\frac{-h}{f(\alpha - h) - f(\alpha)} \to\_{h \to 0^+} \frac{1}{l}$.
Let $\beta=f(\alpha)$.. First, since $f$ is differentiable at $x=\alpha$ then $f$ is continuous at $x=\alpha$ and consequently $$x\rightarrow \alpha^{+}\Longrightarrow f(x)\rightarrow f(\alpha)=\beta.$$ Since $f^{\prime+}(\alpha)=\lim\_{x\rightarrow \alpha^{+}}{\frac{f(x)-f(\alpha)}{x-\alpha}}=r$ then $$\frac{1}{{(f^{-1})}^{\prime}(\beta)}=\lim\_{y\rightarrow \beta}{\frac{y-\beta}{f^{-1}(y)-f^{-1}(\beta)}}=r$$. Observe that we denoted $y=f(x)$, $x\in [a,b]$ or equivalently $x=f^{-1}(y)$, $y\in [c,d]$. More importantly, we have that $f^{-1}(y)-f^{-1}(\beta)\neq 0$ since $f$ is injective and $x\neq \alpha$. The left derivative of the inverse can be obtained analogously.
3,690,994
Let $f(x)$ be an injective function with domain $[a,b]$ and range $[c,d]$. If $\alpha$ is a point in $(a,b)$ such that $f$ has left hand derivative $l$ and right hand derivative $r$ at $x=\alpha$ with both $l$ and $r$ being non-zero different and negative , then prove that the left hand derivative and the right hand derivative of $f^{-1}(x)$ at $x=f(\alpha)$ are $\frac{1}{r}$ and $\frac{1}{l}$ respectively. **My Attempt:** If $g(x)$ be the inverse of $f((x)$ then $f(g(x))=x$ which gives $g'(x)=\frac{1}{f'(g(x))}$. So if $x=f(\alpha)$ then $g'(f(\alpha))=\frac{1}{f'(g(f(\alpha)))}=\frac{1}{f'(\alpha)}$. But now how do I get the left hand derivative and the right hand derivative. I could frame an example $f(x)=\left\{ \begin{array}{ll} \frac{1}{x} & 0<x<2 \\ \frac{2}{x^2} & x\geq 2 \\ \end{array} \right.$ Left hand derivative at $x=2$ equals $\frac{-1}{4}=l$ Right hand derivative at $x=2$ equals $\frac{-1}{2}=r$ $f^{-1}(x)=\left\{ \begin{array}{ll} \\\sqrt {\frac{2}{x}} & 0<x\leq \frac{1}{2} \\ \frac{1}{x} & x> \frac{1}{2} \\ \end{array} \right.$ Left hand derivative of $f^{-1}(x)$ at $x=\frac{1}{2}$ equals $-2=\frac{1}{r}$ Right hand derivative of $f^{-1}(x)$ at $x=\frac{1}{2}$ equals $-4=\frac{1}{l}$ But I am not able to get a proper method.
2020/05/25
[ "https://math.stackexchange.com/questions/3690994", "https://math.stackexchange.com", "https://math.stackexchange.com/users/171392/" ]
We have $f'\_-(\alpha)=l < 0$ and $f'\_+(\alpha)=r < 0$, with $l \neq r$. That implies, for $h > 0$ small enough, that $f(\alpha - h) > f(\alpha) > f(\alpha + h)$. Since $f$ has a left and a right derivative at $\alpha$, it is continuous at $\alpha$. Let $\beta = f(\alpha)$ and given $h > 0$, let $k\_1 = f(\alpha + h) - f(\alpha)$ and $k\_2 = f(\alpha - h) - f(\alpha)$. Note that $k\_1 < 0$ and $k\_2 > 0$. Then $\frac{g(\beta + k\_1) - g(\beta)}{k\_1}=\frac{h}{f(\alpha + h) - f(\alpha)} \to\_{h \to 0^+} \frac{1}{r}$, and $\frac{g(\beta + k\_2) - g(\beta)}{k\_2}=\frac{-h}{f(\alpha - h) - f(\alpha)} \to\_{h \to 0^+} \frac{1}{l}$.
[![enter image description here](https://i.stack.imgur.com/rhZKr.png)](https://i.stack.imgur.com/rhZKr.png) Picking up from both answers given I was able to understand and consequently plotted the graph depicting $y=f(x)$ and $y=f^{-1}(x)$
46,862
I was wondering why ARM CPUs are popular for mobile and other portable devices but not on desktop/server computers? The only thing I know is that ARM CPUs consume much less power than x86 processors. This is a good argument in favor of using it on mobile devices but also on desktop/servers. Yet it is not so widely used. Is it the instruction set or performance or smth. else?
2012/10/30
[ "https://electronics.stackexchange.com/questions/46862", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/15487/" ]
From what I see: 1. Software compatibility (for most people, a desktop PC that can't run x86 software is a definitive no-no). 2. Even the fastest ARM CPUs are often slower than x86 CPUs. From [here](http://liliputing.com/2012/02/fastest-arm-chips-are-comparable-to-intels-slowest-atom-chips.html) (which links to [this Phoronix](http://www.phoronix.com/scan.php?page=article&item=ubuntu_1204_armfeb&num=1) article): > > In a nutshell, the system with a 1 GHz TI OMAP 4460 dual core processor came out ahead of the netbook with a 1.6 GHz Intel Atom N270 chip in some of the benchmarks, and came out behind in others. > > > 3. Power consumption is not really the biggest concern on a desktop computer. Though ARM is starting to be used on servers, e.g. [Calxeda](http://www.calxeda.com/): > > Founded in 2008 and funded with a $48M investment from ARM and seasoned venture capital investors in 2010, Calxeda provides revolutionary efficiency to the data center. Leveraging ultra-low power technology from ARM, servers built on Calxeda’s silicon and software platform consume a fraction of the power and space of today’s best-in-class servers, enabling data centers to realize significant reduction in capital and operating expenses. > > > And recently AMD announced plans to make [ARM-based Opterons](http://www.theinquirer.net/inquirer/news/2220944/amd-says-arm-based-opteron-chips-will-appear-in-2014) > > CHIP DESIGNER AMD has announced that it will release ARM based server chips under its Opteron brand in 2014. > > >
In addition to what Renan said, there weren't 64-bit ARM parts in 2012. Since servers have needed more than 4 GB for some time, this is a show stopper. However as pointed out by Igor Skochinsky below, it isn't quite that simple
46,862
I was wondering why ARM CPUs are popular for mobile and other portable devices but not on desktop/server computers? The only thing I know is that ARM CPUs consume much less power than x86 processors. This is a good argument in favor of using it on mobile devices but also on desktop/servers. Yet it is not so widely used. Is it the instruction set or performance or smth. else?
2012/10/30
[ "https://electronics.stackexchange.com/questions/46862", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/15487/" ]
From what I see: 1. Software compatibility (for most people, a desktop PC that can't run x86 software is a definitive no-no). 2. Even the fastest ARM CPUs are often slower than x86 CPUs. From [here](http://liliputing.com/2012/02/fastest-arm-chips-are-comparable-to-intels-slowest-atom-chips.html) (which links to [this Phoronix](http://www.phoronix.com/scan.php?page=article&item=ubuntu_1204_armfeb&num=1) article): > > In a nutshell, the system with a 1 GHz TI OMAP 4460 dual core processor came out ahead of the netbook with a 1.6 GHz Intel Atom N270 chip in some of the benchmarks, and came out behind in others. > > > 3. Power consumption is not really the biggest concern on a desktop computer. Though ARM is starting to be used on servers, e.g. [Calxeda](http://www.calxeda.com/): > > Founded in 2008 and funded with a $48M investment from ARM and seasoned venture capital investors in 2010, Calxeda provides revolutionary efficiency to the data center. Leveraging ultra-low power technology from ARM, servers built on Calxeda’s silicon and software platform consume a fraction of the power and space of today’s best-in-class servers, enabling data centers to realize significant reduction in capital and operating expenses. > > > And recently AMD announced plans to make [ARM-based Opterons](http://www.theinquirer.net/inquirer/news/2220944/amd-says-arm-based-opteron-chips-will-appear-in-2014) > > CHIP DESIGNER AMD has announced that it will release ARM based server chips under its Opteron brand in 2014. > > >
Though ARM is catching up the pace quickly, IMO: Intel still manages to do better on **single core performance**, better memory bandwidth, larger cache design, and reasonable power consumption these days. One of the current i7 core can outperform best single ARM core by 3~10x(depending on application). And i7/xeon is already 4/6 core per chip + hyper threading. you will need 64/128/256 ARM core to match up.
46,862
I was wondering why ARM CPUs are popular for mobile and other portable devices but not on desktop/server computers? The only thing I know is that ARM CPUs consume much less power than x86 processors. This is a good argument in favor of using it on mobile devices but also on desktop/servers. Yet it is not so widely used. Is it the instruction set or performance or smth. else?
2012/10/30
[ "https://electronics.stackexchange.com/questions/46862", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/15487/" ]
In addition to what Renan said, there weren't 64-bit ARM parts in 2012. Since servers have needed more than 4 GB for some time, this is a show stopper. However as pointed out by Igor Skochinsky below, it isn't quite that simple
Though ARM is catching up the pace quickly, IMO: Intel still manages to do better on **single core performance**, better memory bandwidth, larger cache design, and reasonable power consumption these days. One of the current i7 core can outperform best single ARM core by 3~10x(depending on application). And i7/xeon is already 4/6 core per chip + hyper threading. you will need 64/128/256 ARM core to match up.
46,416,414
for the line ```none Tester[0]/Test[4]/testId Tester[0]/Test[4]/testId Test[1]/Test[4]/testId Test[2]/Test[4]/testId ``` I want to match the first part of the path including the first [, n and ] and first / so for line above I would get ```none Tester[0] Tester[0] Test[1] Test[2] ``` I have tried using ``` var rx = new Regex(@"^\[.*\]\/"); var res = rx.Replace("Tester[0]/Test[4]/testId", "", 1 /*only one occurrence */); ``` i get ``` res == "testId"; ``` rather than ``` res == "Test[4]/testId" ``` which is what im hoping for so its matching the first open square bracket and the last closing bracket. I need it to match only the first closing bracket **Update:** Sorry, i am trying to match the first forward slash also. ```none Tester[0]/ Tester[0]/ Test[1]/ Test[2]/ ``` **Solution:** to remove the first match using "?": ``` var rx = new Regex(@"^.*?\[.*?\]\/"); var res = rx.Replace("Tester[0]/Test[4]/testId", "", 1 /*only one occurrence */); ```
2017/09/26
[ "https://Stackoverflow.com/questions/46416414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/675699/" ]
I'm assuming this was your original regex pattern: `^.*\[.*\]/` (the pattern in your question does not match the lines). This pattern uses *greedy* quantifiers (`*`), so, even though we only requested one match, the pattern itself matches more than we'd like. As you noticed, it matched until the second occurrence of the square brackets. We can make this pattern *non-greedy* by adding question marks to the quantifiers: `^.*?\[.*?\]/`. Although this works for your use-case, a better pattern may be: `^[^/]+/`. This removes any character up to the first forward-slash. The `[^ ... ]` is a negative character class (the brackets are unrelated to the brackets in the strings we're matching against). In this case, it matches any character that *isn't* a forward-slash. For this simple text manipulation, though, we could just use a `String.Substring()` instead of regular expressions: ``` line.Substring(line.IndexOf('/') + 1); ``` This is faster and easier to understand than a regular expression pattern.
Is this the sort of thing you are looking for? **updated** ``` var str="Tester[0]/Test[4]/testId\nTester[0]/Test[4]/testId\nTest[1]/Test[4]/testId\nTest[2]/Test[4]/testId" console.log(str) // Tester[0]/Test[4]/testId // Tester[0]/Test[4]/testId // Test[1]/Test[4]/testId // Test[2]/Test[4]/testId var str2=str.replace(/\/.+/mg,"") console.log(str2) // Tester[0] // Tester[0] // Test[1] // Test[2] ``` this works by starting the match at the first '/' and then ending when the line ends and replaces this match with " ". the m flags multi-line and the g flags to do a global match.
46,416,414
for the line ```none Tester[0]/Test[4]/testId Tester[0]/Test[4]/testId Test[1]/Test[4]/testId Test[2]/Test[4]/testId ``` I want to match the first part of the path including the first [, n and ] and first / so for line above I would get ```none Tester[0] Tester[0] Test[1] Test[2] ``` I have tried using ``` var rx = new Regex(@"^\[.*\]\/"); var res = rx.Replace("Tester[0]/Test[4]/testId", "", 1 /*only one occurrence */); ``` i get ``` res == "testId"; ``` rather than ``` res == "Test[4]/testId" ``` which is what im hoping for so its matching the first open square bracket and the last closing bracket. I need it to match only the first closing bracket **Update:** Sorry, i am trying to match the first forward slash also. ```none Tester[0]/ Tester[0]/ Test[1]/ Test[2]/ ``` **Solution:** to remove the first match using "?": ``` var rx = new Regex(@"^.*?\[.*?\]\/"); var res = rx.Replace("Tester[0]/Test[4]/testId", "", 1 /*only one occurrence */); ```
2017/09/26
[ "https://Stackoverflow.com/questions/46416414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/675699/" ]
I'm assuming this was your original regex pattern: `^.*\[.*\]/` (the pattern in your question does not match the lines). This pattern uses *greedy* quantifiers (`*`), so, even though we only requested one match, the pattern itself matches more than we'd like. As you noticed, it matched until the second occurrence of the square brackets. We can make this pattern *non-greedy* by adding question marks to the quantifiers: `^.*?\[.*?\]/`. Although this works for your use-case, a better pattern may be: `^[^/]+/`. This removes any character up to the first forward-slash. The `[^ ... ]` is a negative character class (the brackets are unrelated to the brackets in the strings we're matching against). In this case, it matches any character that *isn't* a forward-slash. For this simple text manipulation, though, we could just use a `String.Substring()` instead of regular expressions: ``` line.Substring(line.IndexOf('/') + 1); ``` This is faster and easier to understand than a regular expression pattern.
You can use `lookahead` and `lookbehind` approach to find matching and replace accordingly : With `lookaround` approach, your regex would be like this : ``` (?=/).*(?<=]) ```
42,595
Secular ethical theories are not enforced except by humans, which means they are of little use against someone whom they deem evil. Why should I abstain from breaking an ethical code if I am assured that there will be no negative consequences for me in life, and only oblivion awaits me in the afterlife? And if everything we have ever done — including the evidence of our crimes — will be destroyed when the Earth or universe dies, what motivation do I have to be "good" at all? Thus I cannot help but wonder if philosophers intend that their laws be interpreted as written into the fabric of the universe, akin to a religion. Is this so? It has certainly been the impression I have received from my studies of ethics.
2017/05/23
[ "https://philosophy.stackexchange.com/questions/42595", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/23478/" ]
Socrates was pressured to answer the question "what motivation do I have to be good (or just) if I have Gyges' ring?" 2500 years ago, which he fudged with misdirection: "Hey, Let's look at justice in a bigger context (the just nation)." So I do not assume there will be *the* answer to your question. Your impression that any system of morality is either akin to a religion or backed by a religion sounds right to me. Spinoza, for instance, believed that the study of ethics is deductive by virtue of the properties of the god. Kant's moral system is incomplete without the postulation of the retribution in afterlife. John Rawls believed that any moral system is like a religion in that people holding different moral theories would never be able to reconcile their differences. Rawls thus called any theory of the good (moral theories as well as religions) a comprehensive doctrine.
In a certain sense you're right - you eventually have to resort to faith of a certain kind in something you can't prove. Although that's not limited to ethics, you could say that about any area. I don't think there is a good answer to the question in terms of rational reasons. Do you think intuition is good enough? I don't feel I need to have a rational reason to think I shouldn't kill, ie it's not just the threat of incarceration or the disapproval of others that stops me. It's just one of the things I don't do. Eventually you will reach rock bottom when trying to look for justifications
42,595
Secular ethical theories are not enforced except by humans, which means they are of little use against someone whom they deem evil. Why should I abstain from breaking an ethical code if I am assured that there will be no negative consequences for me in life, and only oblivion awaits me in the afterlife? And if everything we have ever done — including the evidence of our crimes — will be destroyed when the Earth or universe dies, what motivation do I have to be "good" at all? Thus I cannot help but wonder if philosophers intend that their laws be interpreted as written into the fabric of the universe, akin to a religion. Is this so? It has certainly been the impression I have received from my studies of ethics.
2017/05/23
[ "https://philosophy.stackexchange.com/questions/42595", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/23478/" ]
The short answer is yes. Moral theorists intend for their ethical theories to be objective; in the sense that you could derive the answer from a series of rules/axioms/principles/etc. An objective morality doesn't require some supreme lawmaker to act as the moral source, and some might argue that it could not be the case that morality originates in this way (i.e. Socrates/Plato's *Euthyphro*). To find a moral philosopher that describes an objective morality without appeals to the divine, we need look no further than Kant. He believes that morality ultimately derives from human reason, and requires nothing else to justify. There are some fundamental issues with the line of reasoning that without God (or some other divine lawmaker), morality serves no purpose. It denies the essential goals of morality, and tries to reduce it to a chess game where moves are only made to advance your position. > > Why should I abstain from breaking an ethical code if I am assured that there will be no negative consequences for me in life, and only oblivion awaits me in the afterlife? > > > In essence you are asking: > > What sorts of material benefits can I expect from playing by the rules? > > > I think that for all of his faults, Kant does an excellent job of deconstructing this sort of ethical question. When discussing what one ought to do, Kant distinguishes between two types of ought-statements: *hypothetical imperatives* and *categorical imperatives*. A hypothetical imperative is an ought-statement that deals with questions of prudence. If you want to do well on your next exam, you *ought* to study and prepare for the exam. Nobody would think you immoral for not studying, just imprudent. Another way of viewing these statements is that they are logically contingent upon circumstances. I personally believe that religions with a reward are ultimately making these sorts of statements, which I will touch on later on. Categorical imperatives are logically absolute. They apply in all cases, without regard to circumstances. You *ought* not murder, is a categorical imperative in Kant's eyes, for reasons which are beyond the scope of this question. By asking why you should obey a moral code if it doesn't promise a reward, you are totally missing the point of an objective morality. You are trying to treat categorical imperatives like they are hypothetical imperatives; i.e. not like a moral code. Even when we don't argue from the position of Kant's strict deontological ethics, I think we find similar issues. Utilitarians are concerned with human welfare (in one form or another), and virtue ethicists are concerned with cultivating positive qualities in people; neither of which promise an everlasting reward. Ethical theories that are concerned with reward and the self are generally labeled *egoistic*. So yes, I do think that moral theorists intend for their theories to be objective, and no, I don't think they intend for their theories to be treated like religion. Moral theories grounded in reason and human welfare are more sophisticated than "If you do X, I will give you Y," which is what most religions essentially state.
In a certain sense you're right - you eventually have to resort to faith of a certain kind in something you can't prove. Although that's not limited to ethics, you could say that about any area. I don't think there is a good answer to the question in terms of rational reasons. Do you think intuition is good enough? I don't feel I need to have a rational reason to think I shouldn't kill, ie it's not just the threat of incarceration or the disapproval of others that stops me. It's just one of the things I don't do. Eventually you will reach rock bottom when trying to look for justifications
42,595
Secular ethical theories are not enforced except by humans, which means they are of little use against someone whom they deem evil. Why should I abstain from breaking an ethical code if I am assured that there will be no negative consequences for me in life, and only oblivion awaits me in the afterlife? And if everything we have ever done — including the evidence of our crimes — will be destroyed when the Earth or universe dies, what motivation do I have to be "good" at all? Thus I cannot help but wonder if philosophers intend that their laws be interpreted as written into the fabric of the universe, akin to a religion. Is this so? It has certainly been the impression I have received from my studies of ethics.
2017/05/23
[ "https://philosophy.stackexchange.com/questions/42595", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/23478/" ]
The short answer is yes. Moral theorists intend for their ethical theories to be objective; in the sense that you could derive the answer from a series of rules/axioms/principles/etc. An objective morality doesn't require some supreme lawmaker to act as the moral source, and some might argue that it could not be the case that morality originates in this way (i.e. Socrates/Plato's *Euthyphro*). To find a moral philosopher that describes an objective morality without appeals to the divine, we need look no further than Kant. He believes that morality ultimately derives from human reason, and requires nothing else to justify. There are some fundamental issues with the line of reasoning that without God (or some other divine lawmaker), morality serves no purpose. It denies the essential goals of morality, and tries to reduce it to a chess game where moves are only made to advance your position. > > Why should I abstain from breaking an ethical code if I am assured that there will be no negative consequences for me in life, and only oblivion awaits me in the afterlife? > > > In essence you are asking: > > What sorts of material benefits can I expect from playing by the rules? > > > I think that for all of his faults, Kant does an excellent job of deconstructing this sort of ethical question. When discussing what one ought to do, Kant distinguishes between two types of ought-statements: *hypothetical imperatives* and *categorical imperatives*. A hypothetical imperative is an ought-statement that deals with questions of prudence. If you want to do well on your next exam, you *ought* to study and prepare for the exam. Nobody would think you immoral for not studying, just imprudent. Another way of viewing these statements is that they are logically contingent upon circumstances. I personally believe that religions with a reward are ultimately making these sorts of statements, which I will touch on later on. Categorical imperatives are logically absolute. They apply in all cases, without regard to circumstances. You *ought* not murder, is a categorical imperative in Kant's eyes, for reasons which are beyond the scope of this question. By asking why you should obey a moral code if it doesn't promise a reward, you are totally missing the point of an objective morality. You are trying to treat categorical imperatives like they are hypothetical imperatives; i.e. not like a moral code. Even when we don't argue from the position of Kant's strict deontological ethics, I think we find similar issues. Utilitarians are concerned with human welfare (in one form or another), and virtue ethicists are concerned with cultivating positive qualities in people; neither of which promise an everlasting reward. Ethical theories that are concerned with reward and the self are generally labeled *egoistic*. So yes, I do think that moral theorists intend for their theories to be objective, and no, I don't think they intend for their theories to be treated like religion. Moral theories grounded in reason and human welfare are more sophisticated than "If you do X, I will give you Y," which is what most religions essentially state.
Socrates was pressured to answer the question "what motivation do I have to be good (or just) if I have Gyges' ring?" 2500 years ago, which he fudged with misdirection: "Hey, Let's look at justice in a bigger context (the just nation)." So I do not assume there will be *the* answer to your question. Your impression that any system of morality is either akin to a religion or backed by a religion sounds right to me. Spinoza, for instance, believed that the study of ethics is deductive by virtue of the properties of the god. Kant's moral system is incomplete without the postulation of the retribution in afterlife. John Rawls believed that any moral system is like a religion in that people holding different moral theories would never be able to reconcile their differences. Rawls thus called any theory of the good (moral theories as well as religions) a comprehensive doctrine.
50,576,628
**[enter image description here]** [1](https://i.stack.imgur.com/y6TGP.jpg)Error showing when i run my app...My code is below ...can anyone tell what is wrong with my code /////////////////////// Error showing when i run my app...My code is below ...can anyone tell what is wrong with my code /////////////////////// ``` import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'dart:async'; import ``` 'package:flutter\_staggered\_grid\_view/flutter\_staggered\_grid\_view.dart'; ``` class OfferPage extends StatefulWidget { @override _OfferPageState createState() => new _OfferPageState(); } class _OfferPageState extends State<OfferPage> { StreamSubscription<QuerySnapshot> subscription; List<DocumentSnapshot> offerpostList; final CollectionReference collectionReference = Firestore.instance.collection("todos"); @override void initState() { // TODO: implement initState super.initState(); subscription = collectionReference.snapshots().listen((datasnapshot) { setState(() { offerpostList = datasnapshot.documents; }); }); // _currentScreen(); } @override void dispose() { subscription?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return new Scaffold( body: offerpostList != null? new StaggeredGridView.countBuilder( padding: const EdgeInsets.all(8.0), crossAxisCount: 4, itemCount: offerpostList.length, itemBuilder: (context, i) { String imgPath = offerpostList[i].data['url']; String title = offerpostList[i].data['productTitle']; return new Material( elevation: 8.0, borderRadius: new BorderRadius.all(new Radius.circular(8.0)), child: new InkWell( child:new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(title,style: new TextStyle( fontStyle: FontStyle.italic, color: Colors.green[900], fontSize: 16.0)), new Hero( tag: imgPath, child: new FadeInImage( image: new NetworkImage(imgPath), fit: BoxFit.cover, placeholder: new AssetImage("assets/logo.png"), ), ), ], ), ), ); }, staggeredTileBuilder: (i) => new StaggeredTile.count(2, i.isEven ? 2 : 3), mainAxisSpacing: 8.0, crossAxisSpacing: 8.0, ) : new Center( child: new CircularProgressIndicator(), )); } } ```
2018/05/29
[ "https://Stackoverflow.com/questions/50576628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9862146/" ]
You can do it this way: ``` node --debug=5412 app.js ``` You can also use `--inspect` option for node version >= v8 ``` node --inspect=5622 app.js ``` See for [More Help.](https://nodejs.org/en/docs/inspector/)
use param "--inspect" node --inspect=0.0.0.0:[your port] app.js
64,328,173
I am creating a scatterplot using ggplot. I am able to create a scatterplot using the following code. ``` ggplot(df2, aes(x = date, y = mean, color = NULL)) + geom_point(position = "jitter") + labs(title = "ShotSpotter incidents around July 4th", x = "Day of year", y = "Mean daily gunshots") + labs(fill = "Treatment Status") + geom_segment(aes(x = "07-01", xend = "07-01", y = 0, yend = 50), colour = "red") ``` I would like to change the labels on the x-axis so that they are easier to read. When I try to do so using scale\_x\_discrete(), most of the datapoints disappear except for those corresponding to the values now labeled on the x-axis. ``` ggplot(df2, aes(x = date, y = mean, color = NULL)) + geom_point(position = "jitter") + labs(title = "ShotSpotter incidents around July 4th", x = "Day of year", y = "Mean daily gunshots") + labs(fill = "Treatment Status") + geom_segment(aes(x = "07-01", xend = "07-01", y = 0, yend = 50), colour = "red") + scale_x_discrete(limits = c("05-01", "06-01", "07-01", "08-01", "09-01"), labels = c("May 1", "June 1", "July 1", "Aug 1", "Sept 1")) ``` How can I keep the labels from the 2nd graph and include all the datapoints shown in the 1st? ``` Data using dput(): structure(list(date = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L), .Label = c("05-01", "05-02", "05-03", "05-04", "05-05", "05-06", "05-07", "05-08", "05-09", "05-10", "05-11", "05-12", "05-13", "05-14", "05-15", "05-16", "05-17", "05-18", "05-19", "05-20", "05-21", "05-22", "05-23", "05-24", "05-25", "05-26", "05-27", "05-28", "05-29", "05-30", "05-31", "06-01", "06-02", "06-03", "06-04", "06-05", "06-06", "06-07", "06-08", "06-09", "06-10", "06-11", "06-12", "06-13", "06-14", "06-15", "06-16", "06-17", "06-18", "06-19", "06-20", "06-21", "06-22", "06-23", "06-24", "06-25", "06-26", "06-27", "06-28", "06-29", "06-30", "07-01", "07-02", "07-03", "07-04", "07-05", "07-06", "07-07", "07-08", "07-09", "07-10", "07-11", "07-12", "07-13", "07-14", "07-15", "07-16", "07-17", "07-18", "07-19", "07-20", "07-21", "07-22", "07-23", "07-24", "07-25", "07-26", "07-27", "07-28", "07-29", "07-30", "07-31", "08-01", "08-02", "08-03", "08-04", "08-05", "08-06", "08-07", "08-08", "08-09", "08-10", "08-11", "08-12", "08-13", "08-14", "08-15", "08-16", "08-17", "08-18", "08-19", "08-20", "08-21", "08-22", "08-23", "08-24", "08-25", "08-26", "08-27", "08-28", "08-29", "08-30", "08-31", "09-01" ), class = "factor"), mean = c(13, 15, 16.5, 17.6666666666667, 14.5, 13.3333333333333, 11.8333333333333, 13, 13, 14.3333333333333, 13.8333333333333, 15.5, 11.1666666666667, 15, 12.5, 15.6666666666667, 14.5, 10.5, 11.6666666666667, 17.5, 14.5, 13, 14.6666666666667, 15.6666666666667, 21.3333333333333, 30.6666666666667, 18.5, 17.5, 13.5, 18.5, 13.3333333333333, 14.5, 14.8333333333333, 9.66666666666667, 15.8333333333333, 13.5, 20.5, 16.1666666666667, 15.1666666666667, 14.8333333333333, 15.3333333333333, 14.1666666666667, 14.5, 13.6666666666667, 20.1666666666667, 17.8333333333333, 22.3333333333333, 15.8333333333333, 15.5, 16.1666666666667, 15, 20, 20.8333333333333, 20.8333333333333, 25, 21.1666666666667, 18.1666666666667, 27, 19.5, 19.5, 19.6666666666667, 25.6666666666667, 36.8333333333333, 46.6666666666667, 40.5, 21.3333333333333, 16.3333333333333, 18, 20.1666666666667, 22.6666666666667, 16.8333333333333, 13.8333333333333, 14.5, 14.1666666666667, 16.5, 15.1666666666667, 15.1666666666667, 13.3333333333333, 13.3333333333333, 12.6666666666667, 12.8333333333333, 12.3333333333333, 16.5, 19.6666666666667, 16.3333333333333, 10.6666666666667, 13.1666666666667, 17.5, 10.3333333333333, 15.5, 12.1666666666667, 14.3333333333333, 13.8333333333333, 11.6666666666667, 13, 10.6666666666667, 17.5, 19.3333333333333, 12.6666666666667, 12.5, 12.5, 13.5, 15.8333333333333, 13.5, 15.6666666666667, 16.3333333333333, 14.5, 13.8333333333333, 14.3333333333333, 11, 13.3333333333333, 23.8333333333333, 14.1666666666667, 13.5, 13.3333333333333, 13.3333333333333, 14, 10.6666666666667, 14.3333333333333, 13.3333333333333, 13.1666666666667 )), class = "data.frame", row.names = c(NA, -121L)) ```
2020/10/13
[ "https://Stackoverflow.com/questions/64328173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9273649/" ]
Use string concatenation `+` operator. This construct must be wrapped in `( ... )` to break it cross more than one code line. ``` def return_error(): return ('Error in converting data to the appropriate data type. ' + 'Please try again.') ```
``` print("""Error in converting data to the appropriate data type.""" """Please try again """) ``` Not sure if this will exceed your char limit. Try it out.
64,328,173
I am creating a scatterplot using ggplot. I am able to create a scatterplot using the following code. ``` ggplot(df2, aes(x = date, y = mean, color = NULL)) + geom_point(position = "jitter") + labs(title = "ShotSpotter incidents around July 4th", x = "Day of year", y = "Mean daily gunshots") + labs(fill = "Treatment Status") + geom_segment(aes(x = "07-01", xend = "07-01", y = 0, yend = 50), colour = "red") ``` I would like to change the labels on the x-axis so that they are easier to read. When I try to do so using scale\_x\_discrete(), most of the datapoints disappear except for those corresponding to the values now labeled on the x-axis. ``` ggplot(df2, aes(x = date, y = mean, color = NULL)) + geom_point(position = "jitter") + labs(title = "ShotSpotter incidents around July 4th", x = "Day of year", y = "Mean daily gunshots") + labs(fill = "Treatment Status") + geom_segment(aes(x = "07-01", xend = "07-01", y = 0, yend = 50), colour = "red") + scale_x_discrete(limits = c("05-01", "06-01", "07-01", "08-01", "09-01"), labels = c("May 1", "June 1", "July 1", "Aug 1", "Sept 1")) ``` How can I keep the labels from the 2nd graph and include all the datapoints shown in the 1st? ``` Data using dput(): structure(list(date = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L), .Label = c("05-01", "05-02", "05-03", "05-04", "05-05", "05-06", "05-07", "05-08", "05-09", "05-10", "05-11", "05-12", "05-13", "05-14", "05-15", "05-16", "05-17", "05-18", "05-19", "05-20", "05-21", "05-22", "05-23", "05-24", "05-25", "05-26", "05-27", "05-28", "05-29", "05-30", "05-31", "06-01", "06-02", "06-03", "06-04", "06-05", "06-06", "06-07", "06-08", "06-09", "06-10", "06-11", "06-12", "06-13", "06-14", "06-15", "06-16", "06-17", "06-18", "06-19", "06-20", "06-21", "06-22", "06-23", "06-24", "06-25", "06-26", "06-27", "06-28", "06-29", "06-30", "07-01", "07-02", "07-03", "07-04", "07-05", "07-06", "07-07", "07-08", "07-09", "07-10", "07-11", "07-12", "07-13", "07-14", "07-15", "07-16", "07-17", "07-18", "07-19", "07-20", "07-21", "07-22", "07-23", "07-24", "07-25", "07-26", "07-27", "07-28", "07-29", "07-30", "07-31", "08-01", "08-02", "08-03", "08-04", "08-05", "08-06", "08-07", "08-08", "08-09", "08-10", "08-11", "08-12", "08-13", "08-14", "08-15", "08-16", "08-17", "08-18", "08-19", "08-20", "08-21", "08-22", "08-23", "08-24", "08-25", "08-26", "08-27", "08-28", "08-29", "08-30", "08-31", "09-01" ), class = "factor"), mean = c(13, 15, 16.5, 17.6666666666667, 14.5, 13.3333333333333, 11.8333333333333, 13, 13, 14.3333333333333, 13.8333333333333, 15.5, 11.1666666666667, 15, 12.5, 15.6666666666667, 14.5, 10.5, 11.6666666666667, 17.5, 14.5, 13, 14.6666666666667, 15.6666666666667, 21.3333333333333, 30.6666666666667, 18.5, 17.5, 13.5, 18.5, 13.3333333333333, 14.5, 14.8333333333333, 9.66666666666667, 15.8333333333333, 13.5, 20.5, 16.1666666666667, 15.1666666666667, 14.8333333333333, 15.3333333333333, 14.1666666666667, 14.5, 13.6666666666667, 20.1666666666667, 17.8333333333333, 22.3333333333333, 15.8333333333333, 15.5, 16.1666666666667, 15, 20, 20.8333333333333, 20.8333333333333, 25, 21.1666666666667, 18.1666666666667, 27, 19.5, 19.5, 19.6666666666667, 25.6666666666667, 36.8333333333333, 46.6666666666667, 40.5, 21.3333333333333, 16.3333333333333, 18, 20.1666666666667, 22.6666666666667, 16.8333333333333, 13.8333333333333, 14.5, 14.1666666666667, 16.5, 15.1666666666667, 15.1666666666667, 13.3333333333333, 13.3333333333333, 12.6666666666667, 12.8333333333333, 12.3333333333333, 16.5, 19.6666666666667, 16.3333333333333, 10.6666666666667, 13.1666666666667, 17.5, 10.3333333333333, 15.5, 12.1666666666667, 14.3333333333333, 13.8333333333333, 11.6666666666667, 13, 10.6666666666667, 17.5, 19.3333333333333, 12.6666666666667, 12.5, 12.5, 13.5, 15.8333333333333, 13.5, 15.6666666666667, 16.3333333333333, 14.5, 13.8333333333333, 14.3333333333333, 11, 13.3333333333333, 23.8333333333333, 14.1666666666667, 13.5, 13.3333333333333, 13.3333333333333, 14, 10.6666666666667, 14.3333333333333, 13.3333333333333, 13.1666666666667 )), class = "data.frame", row.names = c(NA, -121L)) ```
2020/10/13
[ "https://Stackoverflow.com/questions/64328173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9273649/" ]
Use string concatenation `+` operator. This construct must be wrapped in `( ... )` to break it cross more than one code line. ``` def return_error(): return ('Error in converting data to the appropriate data type. ' + 'Please try again.') ```
You can return `False` if the **rate\_float** is not between 0.00 to 1.00 and `None` if `ValueError` is raised. I have written a small function that return `rate_float` if it is between 0.00 to 1.00 and if it is number(`if it does not raise ValueError`) ``` def check(rate_float): try: if not (0 < rate_float < 1.0): return False except (ValueError, TypeError): return None return rate_float rate_float = 0.5 _check = check(rate_float) if _check is False: print("""The interest rate must be between 0.00 to 1.00. Please try again""") elif _check is None: print("Error in converting data to the appropriate data type. Please try" " again") else: # do_something() pass ```
64,328,173
I am creating a scatterplot using ggplot. I am able to create a scatterplot using the following code. ``` ggplot(df2, aes(x = date, y = mean, color = NULL)) + geom_point(position = "jitter") + labs(title = "ShotSpotter incidents around July 4th", x = "Day of year", y = "Mean daily gunshots") + labs(fill = "Treatment Status") + geom_segment(aes(x = "07-01", xend = "07-01", y = 0, yend = 50), colour = "red") ``` I would like to change the labels on the x-axis so that they are easier to read. When I try to do so using scale\_x\_discrete(), most of the datapoints disappear except for those corresponding to the values now labeled on the x-axis. ``` ggplot(df2, aes(x = date, y = mean, color = NULL)) + geom_point(position = "jitter") + labs(title = "ShotSpotter incidents around July 4th", x = "Day of year", y = "Mean daily gunshots") + labs(fill = "Treatment Status") + geom_segment(aes(x = "07-01", xend = "07-01", y = 0, yend = 50), colour = "red") + scale_x_discrete(limits = c("05-01", "06-01", "07-01", "08-01", "09-01"), labels = c("May 1", "June 1", "July 1", "Aug 1", "Sept 1")) ``` How can I keep the labels from the 2nd graph and include all the datapoints shown in the 1st? ``` Data using dput(): structure(list(date = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L, 120L, 121L, 122L, 123L, 124L), .Label = c("05-01", "05-02", "05-03", "05-04", "05-05", "05-06", "05-07", "05-08", "05-09", "05-10", "05-11", "05-12", "05-13", "05-14", "05-15", "05-16", "05-17", "05-18", "05-19", "05-20", "05-21", "05-22", "05-23", "05-24", "05-25", "05-26", "05-27", "05-28", "05-29", "05-30", "05-31", "06-01", "06-02", "06-03", "06-04", "06-05", "06-06", "06-07", "06-08", "06-09", "06-10", "06-11", "06-12", "06-13", "06-14", "06-15", "06-16", "06-17", "06-18", "06-19", "06-20", "06-21", "06-22", "06-23", "06-24", "06-25", "06-26", "06-27", "06-28", "06-29", "06-30", "07-01", "07-02", "07-03", "07-04", "07-05", "07-06", "07-07", "07-08", "07-09", "07-10", "07-11", "07-12", "07-13", "07-14", "07-15", "07-16", "07-17", "07-18", "07-19", "07-20", "07-21", "07-22", "07-23", "07-24", "07-25", "07-26", "07-27", "07-28", "07-29", "07-30", "07-31", "08-01", "08-02", "08-03", "08-04", "08-05", "08-06", "08-07", "08-08", "08-09", "08-10", "08-11", "08-12", "08-13", "08-14", "08-15", "08-16", "08-17", "08-18", "08-19", "08-20", "08-21", "08-22", "08-23", "08-24", "08-25", "08-26", "08-27", "08-28", "08-29", "08-30", "08-31", "09-01" ), class = "factor"), mean = c(13, 15, 16.5, 17.6666666666667, 14.5, 13.3333333333333, 11.8333333333333, 13, 13, 14.3333333333333, 13.8333333333333, 15.5, 11.1666666666667, 15, 12.5, 15.6666666666667, 14.5, 10.5, 11.6666666666667, 17.5, 14.5, 13, 14.6666666666667, 15.6666666666667, 21.3333333333333, 30.6666666666667, 18.5, 17.5, 13.5, 18.5, 13.3333333333333, 14.5, 14.8333333333333, 9.66666666666667, 15.8333333333333, 13.5, 20.5, 16.1666666666667, 15.1666666666667, 14.8333333333333, 15.3333333333333, 14.1666666666667, 14.5, 13.6666666666667, 20.1666666666667, 17.8333333333333, 22.3333333333333, 15.8333333333333, 15.5, 16.1666666666667, 15, 20, 20.8333333333333, 20.8333333333333, 25, 21.1666666666667, 18.1666666666667, 27, 19.5, 19.5, 19.6666666666667, 25.6666666666667, 36.8333333333333, 46.6666666666667, 40.5, 21.3333333333333, 16.3333333333333, 18, 20.1666666666667, 22.6666666666667, 16.8333333333333, 13.8333333333333, 14.5, 14.1666666666667, 16.5, 15.1666666666667, 15.1666666666667, 13.3333333333333, 13.3333333333333, 12.6666666666667, 12.8333333333333, 12.3333333333333, 16.5, 19.6666666666667, 16.3333333333333, 10.6666666666667, 13.1666666666667, 17.5, 10.3333333333333, 15.5, 12.1666666666667, 14.3333333333333, 13.8333333333333, 11.6666666666667, 13, 10.6666666666667, 17.5, 19.3333333333333, 12.6666666666667, 12.5, 12.5, 13.5, 15.8333333333333, 13.5, 15.6666666666667, 16.3333333333333, 14.5, 13.8333333333333, 14.3333333333333, 11, 13.3333333333333, 23.8333333333333, 14.1666666666667, 13.5, 13.3333333333333, 13.3333333333333, 14, 10.6666666666667, 14.3333333333333, 13.3333333333333, 13.1666666666667 )), class = "data.frame", row.names = c(NA, -121L)) ```
2020/10/13
[ "https://Stackoverflow.com/questions/64328173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9273649/" ]
Use string concatenation `+` operator. This construct must be wrapped in `( ... )` to break it cross more than one code line. ``` def return_error(): return ('Error in converting data to the appropriate data type. ' + 'Please try again.') ```
You can use **\** to break strings. ``` print("The interest rate must be between 0.00 to 1.00."\ "Please try again") ``` output ``` The interest rate must be between 0.00 to 1.00.Please try again ```
30,319,666
I'm looking for ideas how to implement two factor authentication (2FA) with spring security OAuth2. The requirement is that the user needs two factor authentication only for specific applications with sensitive information. Those webapps have their own client ids. One idea that popped in my mind would be to "mis-use" the scope approval page to force the user to enter the 2FA code/PIN (or whatever). Sample flows would look like this: **Accessing apps without and with 2FA** * User is logged out * User accesses app A which does not require 2FA * Redirect to OAuth app, user logs in with username and password * Redirected back to app A and user is logged in * User accesses app B which also does not require 2FA * Redirect to OAuth app, redirect back to app B and user is directly logged in * User accesses app S which *does* require 2FA * Redirect to OAuth app, user needs to additionally provide the 2FA token * Redirected back to app S and user is logged in **Directly accessing app with 2FA** * User is logged out * User accesses app S which *does* require 2FA * Redirect to OAuth app, user logs in with username and password, user needs to additionally provide the 2FA token * Redirected back to app S and user is logged in Do you have other ideas how to apporach this?
2015/05/19
[ "https://Stackoverflow.com/questions/30319666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285288/" ]
So this is how two factor authentication has been implemented finally: A filter is registered for the /oauth/authorize path after the spring security filter: ``` @Order(200) public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { @Override protected void afterSpringSecurityFilterChain(ServletContext servletContext) { FilterRegistration.Dynamic twoFactorAuthenticationFilter = servletContext.addFilter("twoFactorAuthenticationFilter", new DelegatingFilterProxy(AppConfig.TWO_FACTOR_AUTHENTICATION_BEAN)); twoFactorAuthenticationFilter.addMappingForUrlPatterns(null, false, "/oauth/authorize"); super.afterSpringSecurityFilterChain(servletContext); } } ``` This filter checks if the user hasn't already authenticated with a 2nd factor (by checking if the `ROLE_TWO_FACTOR_AUTHENTICATED` authority isn't available) and creates an OAuth `AuthorizationRequest` which is put into the session. The user is then redirected to the page where he has to enter the 2FA code: ``` /** * Stores the oauth authorizationRequest in the session so that it can * later be picked by the {@link com.example.CustomOAuth2RequestFactory} * to continue with the authoriztion flow. */ public class TwoFactorAuthenticationFilter extends OncePerRequestFilter { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private OAuth2RequestFactory oAuth2RequestFactory; @Autowired public void setClientDetailsService(ClientDetailsService clientDetailsService) { oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); } private boolean twoFactorAuthenticationEnabled(Collection<? extends GrantedAuthority> authorities) { return authorities.stream().anyMatch( authority -> ROLE_TWO_FACTOR_AUTHENTICATION_ENABLED.equals(authority.getAuthority()) ); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Check if the user hasn't done the two factor authentication. if (AuthenticationUtil.isAuthenticated() && !AuthenticationUtil.hasAuthority(ROLE_TWO_FACTOR_AUTHENTICATED)) { AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(paramsFromRequest(request)); /* Check if the client's authorities (authorizationRequest.getAuthorities()) or the user's ones require two factor authenticatoin. */ if (twoFactorAuthenticationEnabled(authorizationRequest.getAuthorities()) || twoFactorAuthenticationEnabled(SecurityContextHolder.getContext().getAuthentication().getAuthorities())) { // Save the authorizationRequest in the session. This allows the CustomOAuth2RequestFactory // to return this saved request to the AuthenticationEndpoint after the user successfully // did the two factor authentication. request.getSession().setAttribute(CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME, authorizationRequest); // redirect the the page where the user needs to enter the two factor authentiation code redirectStrategy.sendRedirect(request, response, ServletUriComponentsBuilder.fromCurrentContextPath() .path(TwoFactorAuthenticationController.PATH) .toUriString()); return; } else { request.getSession().removeAttribute(CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); } } filterChain.doFilter(request, response); } private Map<String, String> paramsFromRequest(HttpServletRequest request) { Map<String, String> params = new HashMap<>(); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { params.put(entry.getKey(), entry.getValue()[0]); } return params; } } ``` The `TwoFactorAuthenticationController` that handles entering the 2FA-code adds the authority `ROLE_TWO_FACTOR_AUTHENTICATED` if the code was correct and redirects the user back to the /oauth/authorize endpoint. ``` @Controller @RequestMapping(TwoFactorAuthenticationController.PATH) public class TwoFactorAuthenticationController { private static final Logger LOG = LoggerFactory.getLogger(TwoFactorAuthenticationController.class); public static final String PATH = "/secure/two_factor_authentication"; @RequestMapping(method = RequestMethod.GET) public String auth(HttpServletRequest request, HttpSession session, ....) { if (AuthenticationUtil.isAuthenticatedWithAuthority(ROLE_TWO_FACTOR_AUTHENTICATED)) { LOG.info("User {} already has {} authority - no need to enter code again", ROLE_TWO_FACTOR_AUTHENTICATED); throw ....; } else if (session.getAttribute(CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME) == null) { LOG.warn("Error while entering 2FA code - attribute {} not found in session.", CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); throw ....; } return ....; // Show the form to enter the 2FA secret } @RequestMapping(method = RequestMethod.POST) public String auth(....) { if (userEnteredCorrect2FASecret()) { AuthenticationUtil.addAuthority(ROLE_TWO_FACTOR_AUTHENTICATED); return "forward:/oauth/authorize"; // Continue with the OAuth flow } return ....; // Show the form to enter the 2FA secret again } } ``` A custom `OAuth2RequestFactory` retrieves the previously saved `AuthorizationRequest` from the session if available and returns that or creates a new one if none can be found in the session. ``` /** * If the session contains an {@link AuthorizationRequest}, this one is used and returned. * The {@link com.example.TwoFactorAuthenticationFilter} saved the original AuthorizationRequest. This allows * to redirect the user away from the /oauth/authorize endpoint during oauth authorization * and show him e.g. a the page where he has to enter a code for two factor authentication. * Redirecting him back to /oauth/authorize will use the original authorizationRequest from the session * and continue with the oauth authorization. */ public class CustomOAuth2RequestFactory extends DefaultOAuth2RequestFactory { public static final String SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME = "savedAuthorizationRequest"; public CustomOAuth2RequestFactory(ClientDetailsService clientDetailsService) { super(clientDetailsService); } @Override public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(false); if (session != null) { AuthorizationRequest authorizationRequest = (AuthorizationRequest) session.getAttribute(SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); if (authorizationRequest != null) { session.removeAttribute(SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); return authorizationRequest; } } return super.createAuthorizationRequest(authorizationParameters); } } ``` This custom OAuth2RequestFactory is set to the authorization server like: ```xml <bean id="customOAuth2RequestFactory" class="com.example.CustomOAuth2RequestFactory"> <constructor-arg index="0" ref="clientDetailsService" /> </bean> <!-- Configures the authorization-server and provides the /oauth/authorize endpoint --> <oauth:authorization-server client-details-service-ref="clientDetailsService" token-services-ref="tokenServices" user-approval-handler-ref="approvalStoreUserApprovalHandler" redirect-resolver-ref="redirectResolver" authorization-request-manager-ref="customOAuth2RequestFactory"> <oauth:authorization-code authorization-code-services-ref="authorizationCodeServices"/> <oauth:implicit /> <oauth:refresh-token /> <oauth:client-credentials /> <oauth:password /> </oauth:authorization-server> ``` When using java config you can create a `TwoFactorAuthenticationInterceptor` instead of the `TwoFactorAuthenticationFilter` and register it with an `AuthorizationServerConfigurer` with ``` @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig implements AuthorizationServerConfigurer { ... @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .addInterceptor(twoFactorAuthenticationInterceptor()) ... .requestFactory(customOAuth2RequestFactory()); } @Bean public HandlerInterceptor twoFactorAuthenticationInterceptor() { return new TwoFactorAuthenticationInterceptor(); } } ``` The `TwoFactorAuthenticationInterceptor` contains the same logic as the `TwoFactorAuthenticationFilter` in its `preHandle` method.
I couldn't make the accepted solution work. I have been working on this for a while, and finally I wrote my solution by using the ideas explained here and on this thread "[null client in OAuth2 Multi-Factor Authentication](https://stackoverflow.com/questions/36899386/null-client-in-oauth2-multi-factor-authentication)" Here is the GitHub location for the working solution for me: <https://github.com/turgos/oauth2-2FA> I appreciate if you share your feedback in case you see any issues or better approach. Below you can find the key configuration files for this solution. **AuthorizationServerConfig** ``` @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private ClientDetailsService clientDetailsService; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients .inMemory() .withClient("ClientId") .secret("secret") .authorizedGrantTypes("authorization_code") .scopes("user_info") .authorities(TwoFactorAuthenticationFilter.ROLE_TWO_FACTOR_AUTHENTICATION_ENABLED) .autoApprove(true); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .authenticationManager(authenticationManager) .requestFactory(customOAuth2RequestFactory()); } @Bean public DefaultOAuth2RequestFactory customOAuth2RequestFactory(){ return new CustomOAuth2RequestFactory(clientDetailsService); } @Bean public FilterRegistrationBean twoFactorAuthenticationFilterRegistration(){ FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(twoFactorAuthenticationFilter()); registration.addUrlPatterns("/oauth/authorize"); registration.setName("twoFactorAuthenticationFilter"); return registration; } @Bean public TwoFactorAuthenticationFilter twoFactorAuthenticationFilter(){ return new TwoFactorAuthenticationFilter(); } } ``` **CustomOAuth2RequestFactory** ``` public class CustomOAuth2RequestFactory extends DefaultOAuth2RequestFactory { private static final Logger LOG = LoggerFactory.getLogger(CustomOAuth2RequestFactory.class); public static final String SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME = "savedAuthorizationRequest"; public CustomOAuth2RequestFactory(ClientDetailsService clientDetailsService) { super(clientDetailsService); } @Override public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) { ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); HttpSession session = attr.getRequest().getSession(false); if (session != null) { AuthorizationRequest authorizationRequest = (AuthorizationRequest) session.getAttribute(SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); if (authorizationRequest != null) { session.removeAttribute(SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); LOG.debug("createAuthorizationRequest(): return saved copy."); return authorizationRequest; } } LOG.debug("createAuthorizationRequest(): create"); return super.createAuthorizationRequest(authorizationParameters); } } ``` **WebSecurityConfig** ``` @EnableResourceServer @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class ResourceServerConfig extends WebSecurityConfigurerAdapter { @Autowired CustomDetailsService customDetailsService; @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Bean(name = "authenticationManager") @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/webjars/**"); web.ignoring().antMatchers("/css/**","/fonts/**","/libs/**"); } @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.requestMatchers() .antMatchers("/login", "/oauth/authorize", "/secure/two_factor_authentication","/exit", "/resources/**") .and() .authorizeRequests() .anyRequest() .authenticated() .and() .formLogin().loginPage("/login") .permitAll(); } // @formatter:on @Override @Autowired // <-- This is crucial otherwise Spring Boot creates its own protected void configure(AuthenticationManagerBuilder auth) throws Exception { // auth//.parentAuthenticationManager(authenticationManager) // .inMemoryAuthentication() // .withUser("demo") // .password("demo") // .roles("USER"); auth.userDetailsService(customDetailsService).passwordEncoder(encoder()); } } ``` **TwoFactorAuthenticationFilter** ``` public class TwoFactorAuthenticationFilter extends OncePerRequestFilter { private static final Logger LOG = LoggerFactory.getLogger(TwoFactorAuthenticationFilter.class); private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private OAuth2RequestFactory oAuth2RequestFactory; //These next two are added as a test to avoid the compilation errors that happened when they were not defined. public static final String ROLE_TWO_FACTOR_AUTHENTICATED = "ROLE_TWO_FACTOR_AUTHENTICATED"; public static final String ROLE_TWO_FACTOR_AUTHENTICATION_ENABLED = "ROLE_TWO_FACTOR_AUTHENTICATION_ENABLED"; @Autowired public void setClientDetailsService(ClientDetailsService clientDetailsService) { oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); } private boolean twoFactorAuthenticationEnabled(Collection<? extends GrantedAuthority> authorities) { return authorities.stream().anyMatch( authority -> ROLE_TWO_FACTOR_AUTHENTICATION_ENABLED.equals(authority.getAuthority()) ); } private Map<String, String> paramsFromRequest(HttpServletRequest request) { Map<String, String> params = new HashMap<>(); for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) { params.put(entry.getKey(), entry.getValue()[0]); } return params; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Check if the user hasn't done the two factor authentication. if (isAuthenticated() && !hasAuthority(ROLE_TWO_FACTOR_AUTHENTICATED)) { AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(paramsFromRequest(request)); /* Check if the client's authorities (authorizationRequest.getAuthorities()) or the user's ones require two factor authentication. */ if (twoFactorAuthenticationEnabled(authorizationRequest.getAuthorities()) || twoFactorAuthenticationEnabled(SecurityContextHolder.getContext().getAuthentication().getAuthorities())) { // Save the authorizationRequest in the session. This allows the CustomOAuth2RequestFactory // to return this saved request to the AuthenticationEndpoint after the user successfully // did the two factor authentication. request.getSession().setAttribute(CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME, authorizationRequest); LOG.debug("doFilterInternal(): redirecting to {}", TwoFactorAuthenticationController.PATH); // redirect the the page where the user needs to enter the two factor authentication code redirectStrategy.sendRedirect(request, response, TwoFactorAuthenticationController.PATH ); return; } } LOG.debug("doFilterInternal(): without redirect."); filterChain.doFilter(request, response); } public boolean isAuthenticated(){ return SecurityContextHolder.getContext().getAuthentication().isAuthenticated(); } private boolean hasAuthority(String checkedAuthority){ return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().anyMatch( authority -> checkedAuthority.equals(authority.getAuthority()) ); } } ``` **TwoFactorAuthenticationController** ``` @Controller @RequestMapping(TwoFactorAuthenticationController.PATH) public class TwoFactorAuthenticationController { private static final Logger LOG = LoggerFactory.getLogger(TwoFactorAuthenticationController.class); public static final String PATH = "/secure/two_factor_authentication"; @RequestMapping(method = RequestMethod.GET) public String auth(HttpServletRequest request, HttpSession session) { if (isAuthenticatedWithAuthority(TwoFactorAuthenticationFilter.ROLE_TWO_FACTOR_AUTHENTICATED)) { LOG.debug("User {} already has {} authority - no need to enter code again", TwoFactorAuthenticationFilter.ROLE_TWO_FACTOR_AUTHENTICATED); //throw ....; } else if (session.getAttribute(CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME) == null) { LOG.debug("Error while entering 2FA code - attribute {} not found in session.", CustomOAuth2RequestFactory.SAVED_AUTHORIZATION_REQUEST_SESSION_ATTRIBUTE_NAME); //throw ....; } LOG.debug("auth() HTML.Get"); return "loginSecret"; // Show the form to enter the 2FA secret } @RequestMapping(method = RequestMethod.POST) public String auth(@ModelAttribute(value="secret") String secret, BindingResult result, Model model) { LOG.debug("auth() HTML.Post"); if (userEnteredCorrect2FASecret(secret)) { addAuthority(TwoFactorAuthenticationFilter.ROLE_TWO_FACTOR_AUTHENTICATED); return "forward:/oauth/authorize"; // Continue with the OAuth flow } model.addAttribute("isIncorrectSecret", true); return "loginSecret"; // Show the form to enter the 2FA secret again } private boolean isAuthenticatedWithAuthority(String checkedAuthority){ return SecurityContextHolder.getContext().getAuthentication().getAuthorities().stream().anyMatch( authority -> checkedAuthority.equals(authority.getAuthority()) ); } private boolean addAuthority(String authority){ Collection<SimpleGrantedAuthority> oldAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities(); SimpleGrantedAuthority newAuthority = new SimpleGrantedAuthority(authority); List<SimpleGrantedAuthority> updatedAuthorities = new ArrayList<SimpleGrantedAuthority>(); updatedAuthorities.add(newAuthority); updatedAuthorities.addAll(oldAuthorities); SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken( SecurityContextHolder.getContext().getAuthentication().getPrincipal(), SecurityContextHolder.getContext().getAuthentication().getCredentials(), updatedAuthorities) ); return true; } private boolean userEnteredCorrect2FASecret(String secret){ /* later on, we need to pass a temporary secret for each user and control it here */ /* this is just a temporary way to check things are working */ if(secret.equals("123")) return true; else; return false; } } ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
Listening to the click event seems to work in my Fiddle: <http://jsfiddle.net/S5n84/1/> HTML ``` <input type="search" value="hello" /> <span id="status"></span> <!-- Just an example --> ``` Javascript ``` $("input").on("click keyup", function () { if ($(this).val() == "") { $("#status").text("WTF it's empty.."); } else { $("#status").text($(this).val()); } }); ```
At first, when it wasn't obvious that the OP thought of `<input type="search">` (how silly of me that I didn't read his mind) I thought it maybe the answer. I guess that the 'x' is not a standard part of the input field (HTML5 or not). It's probably some site element added externally, that's why you may be interested in this answer: <https://stackoverflow.com/a/6258628/2107024> **Edit:** After research I found out that clicking the `x` on Chrome fires the `click` event. Also the answers in this similar thread: [How do you detect the clearing of a "search" HTML5 input?](https://stackoverflow.com/questions/2977023/how-do-you-detect-the-clearing-of-a-search-html5-input) suggest that the `search` event is fired aswell.
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
Listening to the click event seems to work in my Fiddle: <http://jsfiddle.net/S5n84/1/> HTML ``` <input type="search" value="hello" /> <span id="status"></span> <!-- Just an example --> ``` Javascript ``` $("input").on("click keyup", function () { if ($(this).val() == "") { $("#status").text("WTF it's empty.."); } else { $("#status").text($(this).val()); } }); ```
You can use bind to capture multiple events as [Eric Warnke](http://www.twitter.com/EricWarnke) demonstrated in [jQuery .keyup() vs .change() vs .bind()](http://solicitingfame.com/2011/11/09/jquery-keyup-vs-bind/) [Here's a forked fiddle](http://jsfiddle.net/rv2two92/) based on [Emre Erkan](https://stackoverflow.com/users/84042/emre-erkan)'s: ``` $('#search').bind("change keyup input", function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [`oninput`](http://help.dottoro.com/ljhxklln.php). > > Occurs when the text content of an element is changed through the user > interface. > > > The oninput is useful if you want to detect when the contents of a > textarea, input:text, input:password or input:search element have > changed, because the onchange event on these elements fires when the > element loses focus, not immediately after the modification. > > > Here is a working example; ```js $('#search').on('input', function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" name="search" id="search" placeholder="Search..." /> ```
You can use bind to capture multiple events as [Eric Warnke](http://www.twitter.com/EricWarnke) demonstrated in [jQuery .keyup() vs .change() vs .bind()](http://solicitingfame.com/2011/11/09/jquery-keyup-vs-bind/) [Here's a forked fiddle](http://jsfiddle.net/rv2two92/) based on [Emre Erkan](https://stackoverflow.com/users/84042/emre-erkan)'s: ``` $('#search').bind("change keyup input", function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [onsearch](http://help.dottoro.com/ljdvxmhr.php). Actions that invoke the onsearch event: > > Pressing the ENTER key or clicking the 'Erase search text' button in a search control. > > > Here is an example: **HTML:** ``` <input type="search" name="search" id="search" placeholder="Search..." /> ``` **jQuery:** ``` $('#search').on('search', function(e) { if('' == this.value) { alert("You either clicked the X or you searched for nothing."); } }); ```
At first, when it wasn't obvious that the OP thought of `<input type="search">` (how silly of me that I didn't read his mind) I thought it maybe the answer. I guess that the 'x' is not a standard part of the input field (HTML5 or not). It's probably some site element added externally, that's why you may be interested in this answer: <https://stackoverflow.com/a/6258628/2107024> **Edit:** After research I found out that clicking the `x` on Chrome fires the `click` event. Also the answers in this similar thread: [How do you detect the clearing of a "search" HTML5 input?](https://stackoverflow.com/questions/2977023/how-do-you-detect-the-clearing-of-a-search-html5-input) suggest that the `search` event is fired aswell.
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [`oninput`](http://help.dottoro.com/ljhxklln.php). > > Occurs when the text content of an element is changed through the user > interface. > > > The oninput is useful if you want to detect when the contents of a > textarea, input:text, input:password or input:search element have > changed, because the onchange event on these elements fires when the > element loses focus, not immediately after the modification. > > > Here is a working example; ```js $('#search').on('input', function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" name="search" id="search" placeholder="Search..." /> ```
There is an event for this: [onsearch](http://help.dottoro.com/ljdvxmhr.php). Actions that invoke the onsearch event: > > Pressing the ENTER key or clicking the 'Erase search text' button in a search control. > > > Here is an example: **HTML:** ``` <input type="search" name="search" id="search" placeholder="Search..." /> ``` **jQuery:** ``` $('#search').on('search', function(e) { if('' == this.value) { alert("You either clicked the X or you searched for nothing."); } }); ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [`oninput`](http://help.dottoro.com/ljhxklln.php). > > Occurs when the text content of an element is changed through the user > interface. > > > The oninput is useful if you want to detect when the contents of a > textarea, input:text, input:password or input:search element have > changed, because the onchange event on these elements fires when the > element loses focus, not immediately after the modification. > > > Here is a working example; ```js $('#search').on('input', function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" name="search" id="search" placeholder="Search..." /> ```
Here is an alternative to oninput which will monitor the field while it is focussed [DEMO](http://jsfiddle.net/mplungjan/dXHJ2/) ``` function tell(fld,id) { $("#"+id).html((fld.val()==""?"Clear":"Not clear")+" - "+new Date()) } $(function() { $("#search").on("focus",function() { var srch = $(this); var tId = setInterval(function() { tell(srch,"status") },100); $(this).data("tId",tId); }) .on("blur",function() { clearInterval($(this).data("tId")); }); tell($("#search"),"status"); }); ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [onsearch](http://help.dottoro.com/ljdvxmhr.php). Actions that invoke the onsearch event: > > Pressing the ENTER key or clicking the 'Erase search text' button in a search control. > > > Here is an example: **HTML:** ``` <input type="search" name="search" id="search" placeholder="Search..." /> ``` **jQuery:** ``` $('#search').on('search', function(e) { if('' == this.value) { alert("You either clicked the X or you searched for nothing."); } }); ```
Listening to the click event seems to work in my Fiddle: <http://jsfiddle.net/S5n84/1/> HTML ``` <input type="search" value="hello" /> <span id="status"></span> <!-- Just an example --> ``` Javascript ``` $("input").on("click keyup", function () { if ($(this).val() == "") { $("#status").text("WTF it's empty.."); } else { $("#status").text($(this).val()); } }); ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [`oninput`](http://help.dottoro.com/ljhxklln.php). > > Occurs when the text content of an element is changed through the user > interface. > > > The oninput is useful if you want to detect when the contents of a > textarea, input:text, input:password or input:search element have > changed, because the onchange event on these elements fires when the > element loses focus, not immediately after the modification. > > > Here is a working example; ```js $('#search').on('input', function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" name="search" id="search" placeholder="Search..." /> ```
Listening to the click event seems to work in my Fiddle: <http://jsfiddle.net/S5n84/1/> HTML ``` <input type="search" value="hello" /> <span id="status"></span> <!-- Just an example --> ``` Javascript ``` $("input").on("click keyup", function () { if ($(this).val() == "") { $("#status").text("WTF it's empty.."); } else { $("#status").text($(this).val()); } }); ```
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [`oninput`](http://help.dottoro.com/ljhxklln.php). > > Occurs when the text content of an element is changed through the user > interface. > > > The oninput is useful if you want to detect when the contents of a > textarea, input:text, input:password or input:search element have > changed, because the onchange event on these elements fires when the > element loses focus, not immediately after the modification. > > > Here is a working example; ```js $('#search').on('input', function(e) { if('' == this.value) { alert('Please enter a search criteria!'); } }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="search" name="search" id="search" placeholder="Search..." /> ```
At first, when it wasn't obvious that the OP thought of `<input type="search">` (how silly of me that I didn't read his mind) I thought it maybe the answer. I guess that the 'x' is not a standard part of the input field (HTML5 or not). It's probably some site element added externally, that's why you may be interested in this answer: <https://stackoverflow.com/a/6258628/2107024> **Edit:** After research I found out that clicking the `x` on Chrome fires the `click` event. Also the answers in this similar thread: [How do you detect the clearing of a "search" HTML5 input?](https://stackoverflow.com/questions/2977023/how-do-you-detect-the-clearing-of-a-search-html5-input) suggest that the `search` event is fired aswell.
16,190,871
I wonder if anyone could assist me? Within my database I have two tables which have identical columns and contain the same type of data. My first table is one we have been maintaining for the last 6 years and have a few million records in it. My second table is one we have been given from elsewhere which contains over 100 million records. It is likely that some of the data in table two is already contained in table one. What I am trying to achieve is to add the unique records from table two in to table one. My PK is the same for both tables, and it is this column that would identify if it is a duplicate or not. The issue comes about, that I need to show at the end of the process the duplicate records so that these can be reviewed. I have a good basic knowledge of SQL but not advanced enough to achieve this. If anyone is able to assist it would be greatly appreciated.
2013/04/24
[ "https://Stackoverflow.com/questions/16190871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2315274/" ]
There is an event for this: [onsearch](http://help.dottoro.com/ljdvxmhr.php). Actions that invoke the onsearch event: > > Pressing the ENTER key or clicking the 'Erase search text' button in a search control. > > > Here is an example: **HTML:** ``` <input type="search" name="search" id="search" placeholder="Search..." /> ``` **jQuery:** ``` $('#search').on('search', function(e) { if('' == this.value) { alert("You either clicked the X or you searched for nothing."); } }); ```
Capture the 'change' event, rather than the 'keyup' event. When the value of the text field changes this fires, and you can check if the value is blank. ``` $('input[type="search"]').on('change', function() { if ($(this).val() == "") { alert('clear'); } }); ``` <http://jsfiddle.net/Ebg4M/>
16,839,708
I am writing a time\_t variable in a file like this (and also reading it in a same way, however, instead of write, now I use read): //Write time ``` file fd; time_t currentTime; currentTime = time(0); // current time fd.create(filepath); fd.open(filepath); fd.seek(SEEK_SET,0); fd.write(&currentTime,sizeof(time_t)); fd.close(); ``` // Read time ``` file fd; time_t timeFromFile; fd.open(filepath); fd.seek(SEEK_SET,0); fd.read(&timeFromFile,sizeof(time_t)); ``` Is there something wrong with above approach? (Besides that it is working as I checked). ps. I am writing for an embedded device, so I don't think portability etc. should be an issue. I think this will run mostly on similar type of devices.
2013/05/30
[ "https://Stackoverflow.com/questions/16839708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913604/" ]
[`time_t`](http://en.cppreference.com/w/cpp/chrono/c/time_t) is not guaranteed to be an integral type in C++. > > Although not defined, this is almost always a integral value holding the number of seconds since 00:00, Jan 1 1970 UTC, corresponding to POSIX time. > > > However, if you are always reading and writing from the same platform and compiler, it should be fine. It's worth noting whilst most systems represent time as an integral, some may have different sizes. Originally, `time_t` was frequently represented by a 32-bit number. However, this creates the [2038 problem](http://en.wikipedia.org/wiki/Year_2038_problem). These days, it is common to see `time_t` being represented with a 64-bit number. > > The year 2038 problem may cause some computer software to fail at some point near the year 2038. The problem affects all software and systems that both store system time as a signed 32-bit integer, and interpret this number as the number of seconds since 00:00:00 UTC on Thursday, 1 January 1970. > > > If you're compiling for different devices which use different header files (particulary `ctime`), you should be aware that there may be different sizes of `time_t`. If you write a `time_t` to a file that can be read from another build of your program, it is possible the size of the number will be different between the devices. The best way to prevent problems is at compile time. If you're able to use a C++11 compiler, you can use [`static_assert`](http://en.cppreference.com/w/cpp/language/static_assert). ``` static_assert( sizeof(time_t) == 8, "Unexpected time_t size" ); ``` If the target you're compiling against uses a different size your code won't compile and will prevent unexplained errors. If you think this is a likely issue then you should serialize time yourself in another way.
According to [POSIX](http://pubs.opengroup.org/onlinepubs/009696699/basedefs/sys/types.h.html): > > **time\_t** and **clock\_t** shall be integer or real-floating types. > > > So it's perfectly reasonable to write them to a file like that, as long as you don't need to read them on a different device.
14,436,724
I've used the following code in my application to exit from it when the user clicks the button. It is working. But the problem is, when I open the application again, it will not be started from the main activity. Instead, it will be started from the activity where i exited. ``` Intent i=new Intent(); i.setAction(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); FarmerDetails.this.startActivity(i); finish(); ``` Full code: ``` public class FarmerDetails extends Activity { Button ok,old,ok1,exit; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.labour); ok=(Button)findViewById(R.id.button1); ok1=(Button)findViewById(R.id.button2); exit=(Button)findViewById(R.id.btn_exit); exit.setOnClickListener(new OnClickListener(){ public void onClick(View v) { Intent i=new Intent(); i.setAction(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); FarmerDetails.this.startActivity(i); finish(); } }); ok1.setOnClickListener(new OnClickListener() { public void onClick(final View v) { Intent next=new Intent(FarmerDetails.this,Fetch.class); startActivity(next); } }); ok.setOnClickListener(new OnClickListener() { public void onClick(final View v) { Intent next=new Intent(FarmerDetails.this,newfarmer1.class); startActivity(next); } }); } public void onDestroy() { System.gc(); android.os.Process.killProcess(android.os.Process.myPid()); super.onDestroy(); } } ``` Can anyone tell what is the problem and how to avoid? I need to start the application from the main activity after exited.
2013/01/21
[ "https://Stackoverflow.com/questions/14436724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954492/" ]
I've found the answer. When the user pressed the exit button it loads the first Activity that runs when your app starts, in my case "main". ``` Intent i = new Intent(getApplicationContext(), main.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra("EXIT", true); startActivity(i); ``` The above code clears all the activities except for main. main is the first activity that is brought up when the user runs the program. Then put this code inside the main's onCreate, to signal when it should self destruct when the 'Exit' message is passed. ``` if (getIntent().getBooleanExtra("EXIT", false)) { finish(); } ```
Use startActivityForResult from callerActivity A while starting this Activity B and before calling finish() setResult(someint) and onActivityResult of A if resultcode==someint finish the activity A and so on..You need to destroy your main activity to re launch from main activity
47,280,499
I want to merge two list into one eg: ``` A B 3 7 1 8 9 2 31 4 ``` Desired answer: ``` A 3 8 9 4 ``` It would be helpful if you anyone can tell me Code of this query?
2017/11/14
[ "https://Stackoverflow.com/questions/47280499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7844977/" ]
If `A` and `B` are vectors: ``` A[c(FALSE, TRUE)] <- B[c(FALSE, TRUE)] A ``` > > > ``` > [1] 3 8 9 4 > > ``` > > If `A` and `B` are columns of a data frmae (which appears to be the case judging from the printed output) ``` DF$A[c(FALSE, TRUE)] <- DF$B[c(FALSE, TRUE)] DF ``` > > > ``` > A B > 1 3 7 > 2 8 8 > 3 9 2 > 4 4 4 > > ``` > >
``` A[seq(1:(length(A)/2))*2] <- B[seq(1:(length(A)/2))*2] ```
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Just so this isn't an 'answer in a comment' Before you give up, try VueScan - specifically reverse-engineered older drivers to run on Big Sur. I haven't used it myself, but a lot of people have been talking about it this past year - <https://www.hamrick.com>
Since I don’t own a scanner and don’t run a Mac, this is a little out of left field...why not just keep the old computer and scanner as dedicated hardware for scanning film? It works now. It will continue to work if you buy another computer. It’s not terribly hard to network a couple of computers together so files can be shared. The analogy I would use is to a darkroom. A darkroom has dedicated equipment. If you buy a new enlarger, you can still keep the old one. You don’t have to replace the sink either. In the worst case it doesn’t work for your needs and six months from now you buy another scanner and repurpose the old Mac. Or maybe it all works out fine because it isn’t broken.
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Since I don’t own a scanner and don’t run a Mac, this is a little out of left field...why not just keep the old computer and scanner as dedicated hardware for scanning film? It works now. It will continue to work if you buy another computer. It’s not terribly hard to network a couple of computers together so files can be shared. The analogy I would use is to a darkroom. A darkroom has dedicated equipment. If you buy a new enlarger, you can still keep the old one. You don’t have to replace the sink either. In the worst case it doesn’t work for your needs and six months from now you buy another scanner and repurpose the old Mac. Or maybe it all works out fine because it isn’t broken.
Sorry, not an answer to the exact question, but it is a possible workaround to keep using your old scanner, software and reduce you impact on the environment as no new scanner is bought. Mac's can boot from an [external harddrive](https://support.apple.com/en-gb/guide/mac-help/mchlp1034/mac). By following these (rough) steps you can create an environment where you can keep using your old scanner: 1. Set-up an external harddrive with the last macOS that your scanner supports. 2. Reboot from the external harddrive. 3. Use the scanner and store the output on the internal disk 4. After use, reboot to your daily OS. 5. As you've stored the photos on the internal drive, you can directly edit and use the scans. I've used this in your exact scenario a few years back when my film scanner was only supported until Snow Leopard (10.6), and I upgraded my Mac to Mountain Lion (10.8)
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Since I don’t own a scanner and don’t run a Mac, this is a little out of left field...why not just keep the old computer and scanner as dedicated hardware for scanning film? It works now. It will continue to work if you buy another computer. It’s not terribly hard to network a couple of computers together so files can be shared. The analogy I would use is to a darkroom. A darkroom has dedicated equipment. If you buy a new enlarger, you can still keep the old one. You don’t have to replace the sink either. In the worst case it doesn’t work for your needs and six months from now you buy another scanner and repurpose the old Mac. Or maybe it all works out fine because it isn’t broken.
Taking the lead @Tetsujin and not leaving my comment as an answer According to Epson the [V500](https://epson.com/Support/Scanners/Perfection-Series/Epson-Perfection-V500-Photo/s/SPT_B11B189011) is supported under macOS 11.x And the commercial scanning software package [Silverfast](https://www.silverfast.com) supports both the V500 and maxOS 11.0 (but I don't know if that means 11.0 or 11.x) So that is a theoretical set of drivers and scanning software that is supported under Big Sur. I haven't tried this combination myself, but if I was shooting a lot more film than I am now, I was considering a V850 and Silverfast combination. --- Now regarding the M1 based Macs, I wouldn't be going there just yet as I wouldn't trust the driver software to be compatible with those new chips. OTOH I would recommend them as a general purpose computer. However note that the iMac (no matter how sweet it looks) has a $$$ premium over the equivalent Mac mini
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Since I don’t own a scanner and don’t run a Mac, this is a little out of left field...why not just keep the old computer and scanner as dedicated hardware for scanning film? It works now. It will continue to work if you buy another computer. It’s not terribly hard to network a couple of computers together so files can be shared. The analogy I would use is to a darkroom. A darkroom has dedicated equipment. If you buy a new enlarger, you can still keep the old one. You don’t have to replace the sink either. In the worst case it doesn’t work for your needs and six months from now you buy another scanner and repurpose the old Mac. Or maybe it all works out fine because it isn’t broken.
Slight change of gears here, but my desk sits firmly in the center of a rather large filing area full of 4x5 and 120mm transparencies and older photographic prints (primarily B&W) of antique paintings. When the older prosumer scanner I used for book publishing lost OS support, I switched to using a light box with the slide-holder template from that scanner for transparencies: I use my camera with macro on a tripod, zoomed to full-frame. The results are frankly superior to the flatbed(s) I had been using, and is very much faster when batch scanning. I also use the camera and studio lights for the 8x10 prints. 35mm is harder, but if you can fill the frame, its worth a try. I shoot them in RAW, and any software that handles negatives can handle your output. Note the lightbox was made for color-proofing etc., so it has consistent diffusion and color temp. No Newton ring problems on scans either.
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Just so this isn't an 'answer in a comment' Before you give up, try VueScan - specifically reverse-engineered older drivers to run on Big Sur. I haven't used it myself, but a lot of people have been talking about it this past year - <https://www.hamrick.com>
Sorry, not an answer to the exact question, but it is a possible workaround to keep using your old scanner, software and reduce you impact on the environment as no new scanner is bought. Mac's can boot from an [external harddrive](https://support.apple.com/en-gb/guide/mac-help/mchlp1034/mac). By following these (rough) steps you can create an environment where you can keep using your old scanner: 1. Set-up an external harddrive with the last macOS that your scanner supports. 2. Reboot from the external harddrive. 3. Use the scanner and store the output on the internal disk 4. After use, reboot to your daily OS. 5. As you've stored the photos on the internal drive, you can directly edit and use the scans. I've used this in your exact scenario a few years back when my film scanner was only supported until Snow Leopard (10.6), and I upgraded my Mac to Mountain Lion (10.8)
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Just so this isn't an 'answer in a comment' Before you give up, try VueScan - specifically reverse-engineered older drivers to run on Big Sur. I haven't used it myself, but a lot of people have been talking about it this past year - <https://www.hamrick.com>
Taking the lead @Tetsujin and not leaving my comment as an answer According to Epson the [V500](https://epson.com/Support/Scanners/Perfection-Series/Epson-Perfection-V500-Photo/s/SPT_B11B189011) is supported under macOS 11.x And the commercial scanning software package [Silverfast](https://www.silverfast.com) supports both the V500 and maxOS 11.0 (but I don't know if that means 11.0 or 11.x) So that is a theoretical set of drivers and scanning software that is supported under Big Sur. I haven't tried this combination myself, but if I was shooting a lot more film than I am now, I was considering a V850 and Silverfast combination. --- Now regarding the M1 based Macs, I wouldn't be going there just yet as I wouldn't trust the driver software to be compatible with those new chips. OTOH I would recommend them as a general purpose computer. However note that the iMac (no matter how sweet it looks) has a $$$ premium over the equivalent Mac mini
124,671
With **Apple's** recent rollout of [their new **iMac** line](https://www.apple.com/imac/), I have been considering upgrading my 2011 computer to something more modern. However, I know that my scanner, **Epson V500**, doesn't work with **macOS Big Sur** as of May 2021\* (I have tried on another computer running **Big Sur**) - and what good would a new computer be if I can't scan pictures with it? So upgrading computers would also mean having to purchase a new scanner. I have been looking for articles comparing currently available scanners that would be able to scan the formats I shoot - **110, 16mm, 35mm half-frame, 35mm, 120, and 6x10**, and have been struggling to find a review that wasn't [mostly](https://www.digitalcameraworld.com/au/buying-guides/the-best-film-scanners) oriented [towards 35mm film](https://fixthephoto.com/best-film-scanners.html) scanning or very expensive professional gear. **What are good, consumer-level film scanners that are Big Sur compatible and can scan a variety of formats?** \*: *The only macOS app I found for Big Sur on the Epson website is called "Easy Photo Scan" (I use "Epson Scan" on High Sierra). "Easy Photo Scan" couldn't connect to the scanner and I also got the "Cannot find a driver" error message and a "Couldn't communicate with helper application"*.
2021/04/29
[ "https://photo.stackexchange.com/questions/124671", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39700/" ]
Just so this isn't an 'answer in a comment' Before you give up, try VueScan - specifically reverse-engineered older drivers to run on Big Sur. I haven't used it myself, but a lot of people have been talking about it this past year - <https://www.hamrick.com>
Slight change of gears here, but my desk sits firmly in the center of a rather large filing area full of 4x5 and 120mm transparencies and older photographic prints (primarily B&W) of antique paintings. When the older prosumer scanner I used for book publishing lost OS support, I switched to using a light box with the slide-holder template from that scanner for transparencies: I use my camera with macro on a tripod, zoomed to full-frame. The results are frankly superior to the flatbed(s) I had been using, and is very much faster when batch scanning. I also use the camera and studio lights for the 8x10 prints. 35mm is harder, but if you can fill the frame, its worth a try. I shoot them in RAW, and any software that handles negatives can handle your output. Note the lightbox was made for color-proofing etc., so it has consistent diffusion and color temp. No Newton ring problems on scans either.
45,314,628
Suppose you have some structs like: ``` struct Tattoo { var imageTorso:UIImage? var imageTorsoURL:URL? var imageArms:UIImage? var imageArmsURL:URL? } struct Player { var name:String = "" var tattoos:[Tattoo] = [] } struct Team { var name:String = "" var players:[Player] = [] } ``` Now imagine that you have a method that was passed in a Team value with some players. You have to iterate thru the players and their tattoos, then download the images and add them into the images variables on the tattoos. If you use a `for in` loop, then it won't work because each part of the loop gets a **copy of** the members of the array it's iterating over. I.e.: ``` for player in team.players { for tattoo in player.tattoos { if let url = tattoo.imageTorsoURL { MyNetFramework.requestImage(from: url, completion: { image in tattoo.imageTorso = image } } } } ``` After doing all the iterations and completion blocks, still, the original `team` variable is identical to what it was prior to doing any of this. Because each tattoo that the inner loop got was a copy of what is in the player's tattoos array. Now I know you can use `&` to pass structs by reference in Swift but it's highly discouraged. As well I know you can use `inout` so they don't get copied when they come into functions, which is also discouraged. I also know these could be made classes to avoid this behavior. But supposing I don't have a choice in the matter -- they are structs -- it seems the only way to do this is something like: ``` for p in 0...team.players.count-1 { for t in 0...team.players[p].tattoos.count-1 { if let url = team.players[p].tattoos[t].imageTorsoURL { MyNetFramework.requestImage(from: url, completion: { image in team.players[p].tattoos[t].imageTorso = image } } } } ``` This feels ugly and awkward, but I don't know how else to get around this thing where `for in` loops give you a copy of the thing you're iterating through. Can anyone enlighten me, or is this just *how it is* in Swift?
2017/07/25
[ "https://Stackoverflow.com/questions/45314628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811519/" ]
I think you already got the point: "When your requirement will be modifying the data, you better to use `class` instead." Here is the question reference link for you. [Why choose struct over class](https://stackoverflow.com/questions/24232799/why-choose-struct-over-class "Why choose struct over class") `struct` is fast and you can use them to prevent creating a huge, messy class. `struct` provided the immutable feature and make us easier to follow the [Function Programming](https://www.raywenderlich.com/114456/introduction-functional-programming-swift) The most significant benefit of immutable data is free of race-condition and deadlocks. That because you only read the data and no worries about the problems caused by changing data. However, to answer your question, I have few ways to solve it. 1. Renew whole data. -------------------- ```swift // First, we need to add constructors for creating instances more easier. struct Tattoo { var imageTorso:UIImage? var imageTorsoURL:URL? var imageArms:UIImage? var imageArmsURL:URL? init(imageTorso: UIImage? = nil, imageTorsoURL: URL? = nil, imageArms: UIImage? = nil, imageArmsURL: URL? = nil) { self.imageTorso = imageTorso self.imageTorsoURL = imageTorsoURL self.imageArms = imageArms self.imageArmsURL = imageArmsURL } } struct Player { var name:String var tattoos:[Tattoo] init() { self.init(name: "", tattoos: []) } init(name: String, tattoos: [Tattoo]) { self.name = name self.tattoos = tattoos } } struct Team { var name:String var players:[Player] init() { self.init(name: "", players: []) } init(name: String, players: [Player]) { self.name = name self.players = players } } for player in team.players { for tattoo in player.tattoos { if let url = tattoo.imageTorsoURL { // Catch old UIImage for matching which Tattoo need to be updated. ({ (needChangeImage: UIImage?) -> Void in MyNetFramework.requestImage(from: url, completion: { image in // Reconstruct whole team data structure. let newPlayers = team.players.map { (player) -> Player in let newTattos = player.tattoos.map { (tattoo) -> Tattoo in if needChangeImage == tattoo.imageTorso { return Tattoo(imageTorso: image) } else { return tattoo } } return Player(name: player.name, tattoos: newTattos) } team = Team(name: team.name, players: newPlayers) }) })(tattoo.imageTorso) } } } ``` These codes are ugly, right? And there will not only be awful performance issue caused by going through whole data every network response; another problem is that might causes the retain cycle. 2. Don't hold UIImage in the data array. ---------------------------------------- Redesign your data structure, and use [Kingfisher](https://github.com/onevcat/Kingfisher) to help us download image synchronously. [Kingfisher](https://github.com/onevcat/Kingfisher) is useful third party library. It provides clean and simple methods to use, and it's highly flexible. ```swift let url = URL(string: "url_of_your_image") imageView.kf.setImage(with: url) ``` However, I think the best way for you if you don't want to use `Kingfisher` is to change your declaration from `struct` to `class`.
Unfortunately that's the nature of `struct` and Swift doesn't offer a way for you modify the collection in-place while iterating over it. But can user `enumerated()` to get both the index and the element when iterating: ``` for (p, player) in team.players.enumerated() { for (t, tattoo) in player.tattoos.enumerated() { if let url = tattoo.imageTorsoURL { MyNetFramework.requestImage(from: url, completion: { image in team.players[p].tattoos[t].imageTorso = image } } } } ```
61,463,116
I have a layout with white background and big textViews with darkblue background and white text. I want to give some space to the text from the start of the darkblue background rectangle. I already tried but only can set start, center, end, top, etc; and I want to specify it numerically. How I can meet that goal?
2020/04/27
[ "https://Stackoverflow.com/questions/61463116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745347/" ]
I think what you are looking for can be achieved by specifying the padding value on the TextView. Look for `android:padding` attribute. If you want to give some space from the start, you can use `android:paddingStart` attribute on the TextView. Hope this helps.
Probably setting margin to your layout might help ``` TextView tv = (TextView)findViewById(R.id.my_text_view); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams(); params.setMargins(10, 0, 0, 0); //move 10 px to right (increase left margin)substitute parameters for left, top, right, bottom tv.setLayoutParams(params);//tv.setMargins(left, top, right, bottom); ``` im not sure if this is excatly what you are looking for
70,464,187
``` > data(dune) > data(dune.env) > str(dune.env) 'data.frame': 20 obs. of 5 variables: $ A1 : num 2.8 3.5 4.3 4.2 6.3 4.3 2.8 4.2 3.7 3.3 ... $ Moisture : Ord.factor w/ 4 levels "1"<"2"<"4"<"5": 1 1 2 2 1 1 1 4 3 2 ... $ Management: Factor w/ 4 levels "BF","HF","NM",..: 4 1 4 4 2 2 2 2 2 1 ... $ Use : Ord.factor w/ 3 levels "Hayfield"<"Haypastu"<..: 2 2 2 2 1 2 3 3 1 1 ... $ Manure : Ord.factor w/ 5 levels "0"<"1"<"2"<"3"<..: 5 3 5 5 3 3 4 4 2 2 ... ``` As shown above, Moisture has four groups and Management has four groups, Manure has five groups when I run: ``` adonis(dune ~ Manure*Management*A1*Moisture, data=dune.env, permutations=99) Call: adonis(formula = dune ~ Manure * Management * A1 * Moisture, data = dune.env, permutations = 99) Permutation: free Number of permutations: 99 Terms added sequentially (first to last) Df SumsOfSqs MeanSqs F.Model R2 Pr(>F) Manure 4 1.5239 0.38097 2.03088 0.35447 0.13 Management 2 0.6118 0.30592 1.63081 0.14232 0.16 A1 1 0.3674 0.36743 1.95872 0.08547 0.21 Moisture 3 0.6929 0.23095 1.23116 0.16116 0.33 Manure:Management 1 0.1091 0.10906 0.58138 0.02537 0.75 Manure:A1 4 0.3964 0.09909 0.52826 0.09220 0.91 Management:A1 1 0.1828 0.18277 0.97431 0.04251 0.50 Manure:Moisture 1 0.0396 0.03963 0.21126 0.00922 0.93 Residuals 2 0.3752 0.18759 0.08727 Total 19 4.2990 1.00000 ``` Why is DF of Management not 3(4-1)?
2021/12/23
[ "https://Stackoverflow.com/questions/70464187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17749451/" ]
Handling text in columns is what [Visual-Block mode](https://vimhelp.org/visual.txt.html#visual-block) is made for! You can create a blockwise Visual selection for all your text with: * `gg` to go to the Top; then * `Ctrl`+`V` to start Visual Block mode. (You might see `-- VISUAL BLOCK --` at the last line of the screen.) * `G` to go to the last line of the buffer. * `$` to select until the end of each line. This is pretty important! Since lines might have different number of characters, the `$` behaves in a special way, in that instead of forcing a rectangle format to the selection, it extends it to the longest line, whatever number of columns it has. Once you got everything selected in a Visual Block, you can use `y` to yank it into the unnamed register. At that point, when you put it, it will come back as a block, as a column. Go back to the first line, using `gg`, then append a certain number of spaces to get you to the column where you want your second copy to appear. For example, for 20 spaces, you can use `20A` then `Space` and `Esc`. At that point, you can go to the end of that line with `$` and simply put with `p`. Sine the register was yanked in Visual Block mode, Vim will remember that and put the contents as a column. Lines that need to be extended with spaces to make it to allow for the pasted text to start in the later column will get extended automatically. Also useful (with the Visual Block mode) is the [`'virtualedit'`](https://vimhelp.org/options.txt.html#%27virtualedit%27) option, which lets you navigate the cursor past the end of lines. If you enable it with `:set virtualedit=all`, then you can skip the part about adding enough spaces to the first line, since you can simply navigate to the appropriate column and the act of pasting the Visual Block contents with `p` will extend the first line with spaces as well.
`:%s/^\(.*\)$/\1 \1` * `%` - whole file * `s/^\(.*\)$` - match line from the beginning to end * `/\1 \1` - replace it with matched text two times. There may be a problem with formatting those lines in columns. Here is an example: ``` hello hello hello hello world world ! ! ``` This can be solved with addition of trailing spaces, the the shorter lines, like this: (`.` - denotes trailing space) ``` hello hello hello hello world world !.... !.... ``` As mentioned by @mattb in the comment, column formatting issue can be fixed with `column` command (it has to be on your PATH though): `:%s/^\(.*\)$/\1 \1/ | %!column -t`
16,865,457
This is my code : HTML ``` <html> <body> <div id="id"> <div class="one"> <img> </div> <div class="two"> <img> </div> <div class="one"> <img> </div> </div> </body> </html> ``` CSS ``` div{ float : left; width : 33,3% height : 100%; } img{ max-width : 100%; max-height : 100%; } div#id{ position : fixed; top : 0; bottom : 0; left : 0; right : 0; } ``` I have been looking for this for ages and can't figure it out... **Unknown height of divs and images** images can change. How can I vertical align the images inside the divs class="one"? as this is an adaptive layout, images must be scaled to prevent overflow. table-cell or line-height = 100% doen't seem to work. Do I realy need javascript here? I have tried a jquery code but it is above my knowledge and ends up changing the margin of all the images in my website... here it is : ``` $(document).ready(function() { $(".one").each(function(){ var wrapH = $(".one").outerHeight(); var imgH = $("img").outerHeight(); var padTop = (wrapH-(imgH))/2; if (padTop>0){ $("img").css("margin-top", padTop + "px"); } }); }); ```
2013/05/31
[ "https://Stackoverflow.com/questions/16865457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1811992/" ]
You can do this easily enough with the following HTML: ``` <div class="wrap"> <div class="image-panel"> <img src="http://placekitten.com/300/300"> </div> <div class="image-panel"> <img src="http://placekitten.com/400/600"> </div> <div class="image-panel"> <img src="http://placekitten.com/200/600"> </div> </div> ``` and apply the following CSS styling: ``` .wrap { border: 1px dotted blue; display: table; width: 100%; } .image-panel { display: table-cell; vertical-align: middle; text-align: center; border: 1px dashed blue; width: 33.3333%; padding: 10px; } .image-panel img { width: 100%; display: block; } ``` In this particular layout, I assumed that each panel has 33.3% of the total width and that the images auto scale to fit the width of the table-cell div. Demo Fiddle: <http://jsfiddle.net/audetwebdesign/ZBNh7/>
Yes. I think at this point you'll need jQuery / javaScript. You can only really align img's or inline / inline-block elements to one another. ``` .block img { /* display: inline; (default) */ display: inline-block; vertical-align: middle; } ``` fiddle: [HERE](http://jsfiddle.net/sheriffderek/zRtFY/) It would be great if you figure it out! We all need this. You could use table-cell as mentioned... but in a responsive setting, this isn't going to cut it - especially if these blocks are in a responsive grid. Once you need to float, which is pretty much *always* - things are going to get really messy. Mystery.
16,865,457
This is my code : HTML ``` <html> <body> <div id="id"> <div class="one"> <img> </div> <div class="two"> <img> </div> <div class="one"> <img> </div> </div> </body> </html> ``` CSS ``` div{ float : left; width : 33,3% height : 100%; } img{ max-width : 100%; max-height : 100%; } div#id{ position : fixed; top : 0; bottom : 0; left : 0; right : 0; } ``` I have been looking for this for ages and can't figure it out... **Unknown height of divs and images** images can change. How can I vertical align the images inside the divs class="one"? as this is an adaptive layout, images must be scaled to prevent overflow. table-cell or line-height = 100% doen't seem to work. Do I realy need javascript here? I have tried a jquery code but it is above my knowledge and ends up changing the margin of all the images in my website... here it is : ``` $(document).ready(function() { $(".one").each(function(){ var wrapH = $(".one").outerHeight(); var imgH = $("img").outerHeight(); var padTop = (wrapH-(imgH))/2; if (padTop>0){ $("img").css("margin-top", padTop + "px"); } }); }); ```
2013/05/31
[ "https://Stackoverflow.com/questions/16865457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1811992/" ]
Ok I finaly found a solution using jquery thx to bdmoura in this post : <https://stackoverflow.com/users/2442497/bdmoura> He showed me how to set an adaptive margin to the images according to image and div height. here is th jquery code : ``` $(document).ready(function() { $(".one").each(function(){ var wrap = $(this), wrapH = wrap.outerHeight(), img = wrap.find('img'), image = new Image(), imgH = 0, padTop = 0; image.onload = function () { imgH = img.outerHeight(); padTop = ( wrapH - ( imgH ) )/2; if ( padTop > 0 ){ img.css("margin-top", padTop + "px"); } } image.src = img.attr('src'); }); }); ``` thx to him!
Yes. I think at this point you'll need jQuery / javaScript. You can only really align img's or inline / inline-block elements to one another. ``` .block img { /* display: inline; (default) */ display: inline-block; vertical-align: middle; } ``` fiddle: [HERE](http://jsfiddle.net/sheriffderek/zRtFY/) It would be great if you figure it out! We all need this. You could use table-cell as mentioned... but in a responsive setting, this isn't going to cut it - especially if these blocks are in a responsive grid. Once you need to float, which is pretty much *always* - things are going to get really messy. Mystery.
29,142,777
I try to check this email already register or not. I want to check When user enter email in email text box during registration at that time if email is already register by other user then message will be display. **Aspx code** ``` protected void txtEmail_TextChanged(object sender, EventArgs e) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString); con.Open(); SqlCommand cmd = new SqlCommand("select count(Email) as Email from tblUsers where Email='"+txtEmail+"'",con); SqlDataReader dr; dr = cmd.ExecuteReader(); while (dr.Read()) { string iEmail = dr["Email"].ToString(); if (iEmail == "0") { Label1.Visible = true; Label1.Text = "This email already registered.."; } } } ```
2015/03/19
[ "https://Stackoverflow.com/questions/29142777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3309357/" ]
There is something to do for gain performance to this query, First: Count query returns only A "CELL" Not row or rows. So you can use `cmd.ExecuteScalar()` for this query but you should cast it to an integer like `int mailCount = (int)cmd.ExecuteScalar();` then you can compare mailCount with 0, if equal, the mail is not registered yet. Second: Instead of > > > ``` > SqlCommand cmd = new SqlCommand("select count(Email) as Email from tblUsers where Email='"+txtEmail+"'",con); > SqlDataReader dr; > > ``` > > this, you should use ``` SqlCommand cmd = new SqlCommand("select count(Email) as Email from tblUsers WHERE Email = @Email", con); cmd.Parameters.AddWithValue("@Email",txtEmail.Text.Trim()); ``` And I think your problem is "txtEmail", you should use `txtEmail.Text.Trim()`
Make sure you enable `AutoPostBack="true"` for that textbox like this:- ``` <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox> ``` Hope this will Help?
43,555
In 1978, a Pacific Southwest Airlines aircraft collided with a Cessna 172 while approaching the San Diego airport in California. The GA aircraft was piloted by a student, and crossed the approach trajectory of the B727, killing 144 people. [![enter image description here](https://i.stack.imgur.com/T4dob.png)](https://i.stack.imgur.com/T4dob.png) [Source](http://www.super70s.com/super70s/tech/aviation/disasters/78-09-25(PSA).asp) To my understanding, ATC was not aware of the Cessna actual location, The airliner crew didn't see the Cessna, and the Cessna was not wrong being in this airspace near a busy regional airport. What changed after this accident to make such situation impossible?
2017/09/06
[ "https://aviation.stackexchange.com/questions/43555", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/3201/" ]
The recommendations from the NTSB report are: > > * Implement a Terminal Radar Service Area (TRSA) at Lindbergh Airpot, San Diego, CA > * Review procedures at all airports which are used regularly by air carrier and general aviation aircraft to determine which other areas require either a terminal control area or a terminal control radar service area and establish the appropriate one. > * Use visual separation in terminal radar service areas only when a pilot requests it, except for sequencing on the final approach with radar monitoring. > * Re-evaluate its policy with regard to the use of visual separation in other terminal areas. > > > The most direct change stemming from this accident is the establishment of a TRSA at Lindbergh on May 1, 1979. (It is now a class B area). Also in 1979 the Lindbergh tower was equipped with some upgrades, including minimum safe altitude warning and conflict alert enhancements. The other recommendations are fairly vague and I find no indication what, if any action was taken on them. But as Gerry pointed out in comments, this accident put emphasis on the FAA's effort to create TCAS. From the TCAS II V7.1 Intro booklet: > > In 1978, the collision between a light aircraft and an airliner over San Diego served to increase FAA's efforts to complete development of an effective collision avoidance system. > > > The see-and-avoid system is still very much in use. Visual approaches are still used. There really were no immediate systemic changes made in response to the accident. Mostly it was just airspace configuration around KSAN and enhancements to the radar system there. But, like every accident, the NTSB and FAA learned from it and took steps to improve safety. The FAA releases pamphlets appropriately titled, "Lessons Learned," about what can be taken from different types of accidents.
In addition to TomMcW@'s answer, the FAA also installed ILS systems at both KMYF and KCRQ and implemented Class B airspace around KSAN. The Cessna wasn't just allowed near busy airspace, they were specifically doing ILS training at the airfield executing a missed approach under VFR. Adding ILS systems at GA airports didn't directly change ATC procedures or airspace definitions, but it result in fewer GA aircraft needing to use KSAN for training. Furthermore, PSA 182 *did* report traffic in sight but they continued their landing procedure anyway once they lost visuals. The fact that ATC didn't know precisely where the Cessna was and recognition that accidents happen even when aircraft report that they are maintaining visual separation also directly lead to Class B airspace being implemented at KSAN: > > As a result of the crash, the NTSB recommended the immediate implementation of a Terminal Radar Service Area around Lindbergh Field to provide for the separation of aircraft, as well as an immediate review of control procedures for all busy terminal areas. This initial rule did not include small, general-aviation aircraft. Therefore, on May 15, 1980, the Federal Aviation Administration, implemented what is called Class B airspace to provide for the separation of all aircraft operating in the area. Additionally, all aircraft, regardless of size, are required to operate under "positive radar control", a rule that allows only radar control from the ground for all aircraft operating in the airport's airspace. > > > ([Wikipedia: Pacific Southwest Airlines Flight 182](https://en.wikipedia.org/wiki/Pacific_Southwest_Airlines_Flight_182))
24,978,406
I am trying to run this query in the SSIS OLEDB COMMAND but for some reason I get this error(see shot) ``` update district set district.districtname=? from district inner join city on district.id=city.districtid where city.fdocode=? and city.taxcode=? ``` ![enter image description here](https://i.stack.imgur.com/VOMtd.gif)
2014/07/27
[ "https://Stackoverflow.com/questions/24978406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379059/" ]
Try: ``` update d set districtname = ? from district d inner join city c on d.id=c.districtid where c.fdocode=? and c.taxcode=? ```
0x80004005 messages usually imply some kind of access violation. Have you checked the identity that the command is running under can issue the command? This should be easy to check by running the SQL Profiler to confirm that the SQL Server gets the command. To determine this look at 1. how the connection manager is connecting to the db. Is that correct? 2. how are you running the package - manually or via SQL server? If via Sql Server then does it work if you run it manually in Visual Studio 3. You need to learn how to debug SSIS - this looks like a good beginners tutorial.
10,000,244
I'd like to condence the following code into fewer calls to `.replace()`. It doesn't look like `.replace()` will do this. Am I right or am I just reading the documentation wrong? ``` public void setBody(String body) { this.body = body.replace("“", "\"").replace("”", "\"").replace("—", "-").replace("’", "'").replace("‘", "'"); } ```
2012/04/03
[ "https://Stackoverflow.com/questions/10000244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
you have two options basically. Use mailto which will use the user's defined email application (could be outlook, yahoo, gmail, whatever). This is the fastest to program since you don't do a thing, just add the link and be done. The other is to create your own email page. The cons to this is that it's more work from you. The pros is that you can specify more fields that give you more info (for example, order #, phone, etc). This would use your email server though, not the client's, so make sure the client adds his email address in the form as mandatory (and maybe verification too)
I'd also give the user a choice to simply copy/paste: ``` <a href="mailto:homer@example.com">Email Homer</a> (homer@example.com) ```
10,000,244
I'd like to condence the following code into fewer calls to `.replace()`. It doesn't look like `.replace()` will do this. Am I right or am I just reading the documentation wrong? ``` public void setBody(String body) { this.body = body.replace("“", "\"").replace("”", "\"").replace("—", "-").replace("’", "'").replace("‘", "'"); } ```
2012/04/03
[ "https://Stackoverflow.com/questions/10000244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
I'd also give the user a choice to simply copy/paste: ``` <a href="mailto:homer@example.com">Email Homer</a> (homer@example.com) ```
I would create a separated web page (like Contact us) where I'd place a contact form (sender's name, email, subject and message). At this page you could also publish your email address with a link/button ["Copy to clipboard"](https://stackoverflow.com/questions/400212/how-to-copy-to-the-clipboard-in-javascript).
10,000,244
I'd like to condence the following code into fewer calls to `.replace()`. It doesn't look like `.replace()` will do this. Am I right or am I just reading the documentation wrong? ``` public void setBody(String body) { this.body = body.replace("“", "\"").replace("”", "\"").replace("—", "-").replace("’", "'").replace("‘", "'"); } ```
2012/04/03
[ "https://Stackoverflow.com/questions/10000244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
you have two options basically. Use mailto which will use the user's defined email application (could be outlook, yahoo, gmail, whatever). This is the fastest to program since you don't do a thing, just add the link and be done. The other is to create your own email page. The cons to this is that it's more work from you. The pros is that you can specify more fields that give you more info (for example, order #, phone, etc). This would use your email server though, not the client's, so make sure the client adds his email address in the form as mandatory (and maybe verification too)
I would create a separated web page (like Contact us) where I'd place a contact form (sender's name, email, subject and message). At this page you could also publish your email address with a link/button ["Copy to clipboard"](https://stackoverflow.com/questions/400212/how-to-copy-to-the-clipboard-in-javascript).
10,986,701
I'm learning SQL (using SQLite 3 and its *sqlite3* command-line tool) and I've noticed that I can do some things in several ways, and sometimes it is not clear which one is better. Here are three queries which do the same thing, one executed through `intersect`, another through `inner join` and `distinct`, the last one similar to the second one but it incorporates filtering through `where`. (The first one was written by the author of the book I'm reading, and the others I wrote myself.) The question is, **which of these queries is better and why**? And, more generally, ***how can I know* when one query is better than another**? Are there some guidelines I missed or perhaps I should learn SQLite internals despite the declarative nature of SQL? (In the following example, there are tables that describe food names that are mentioned in some TV series. Foods\_episodes is many-to-many linking table while others describe food names and episode names together with season number. Note that *all-time* ten top foods (based on the count of their appearances in *all* series) are being looked for, not just top foods in seasons 3..5) ```sql -- task -- find the all-time top ten foods that appear in seasons 3 through 5 -- schema -- CREATE TABLE episodes ( -- id integer primary key, -- season int, -- name text ); -- CREATE TABLE foods( -- id integer primary key, -- name text ); -- CREATE TABLE foods_episodes( -- food_id integer, -- episode_id integer ); select f.* from foods f inner join (select food_id, count(food_id) as count from foods_episodes group by food_id order by count(food_id) desc limit 10) top_foods on f.id=top_foods.food_id intersect select f.* from foods f inner join foods_episodes fe on f.id = fe.food_id inner join episodes e on fe.episode_id = e.id where e.season between 3 and 5 order by f.name; select distinct f.* from foods_episodes as fe inner join episodes as e on e.id = fe.episode_id inner join foods as f on fe.food_id = f.id inner join (select food_id from foods_episodes group by food_id order by count(*) desc limit 10) as lol on lol.food_id = fe.food_id where e.season between 3 and 5 order by f.name; select distinct f.* from foods_episodes as fe inner join episodes as e on e.id = fe.episode_id inner join foods as f on fe.food_id = f.id where fe.food_id in (select food_id from foods_episodes group by food_id order by count(*) desc limit 10) and e.season between 3 and 5 order by f.name; -- output (same for these thee): -- id name -- ---------- ---------- -- 4 Bear Claws -- 146 Decaf Capp -- 153 Hennigen's -- 55 Kasha -- 94 Ketchup -- 164 Naya Water -- 317 Pizza -- CPU Time: user 0.000000 sys 0.000000 ```
2012/06/11
[ "https://Stackoverflow.com/questions/10986701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1449683/" ]
Similar to MySQL, it looks like SQLlite has an EXPLAIN command. Prepend your select with the EXPLAIN keyword and it will return information about the query, including the number of rows scanned, and the indexes used. <http://www.sqlite.org/lang_explain.html> By running EXPLAIN on various selects you can determine which queries (and sub-queries) are more efficient than others. And here is a general overview of SQLlite's query planner and optimization: <http://sqlite.org/optoverview.html> SQLlite3 also supports a callback function to trace queries. You have to implement it though: <http://www.sqlite.org/c3ref/profile.html>
Generally, there is more than 1 way to solve a problem. If you are getting correct answers, the only other question is whether the process/script/statement needs to be improved, or if it works well now. In SQL generally, there may be a "best' way, but it's usually not the goal to find a canonical best way to do something - you want a way that efficiently blances your needs from the program, and your time. You can spend months optimizing a process, but if the process is used only weekly, and it only takes 5 minutes now, reducing it to 4 minutes isn't much help. it's weird to transition from a context where there are correct answers (like school,) to a context where the goal is to get something done well, and works well enough trumps perfect, because there are time constraints. It's something that took me a while to appreciate, but I'm not sure there is a better answer. Hope the perspective helps a bit!
3,625,569
I am using PDO and prepared statements, but i cannot seem to get any results when **comparing an ENUM field with an integer**. Example: ``` $db = new PDO('mysql:host=localhost;dbname=****', '***', '***'); $s = $db->prepare('SELECT id FROM t2 WHERE lang = ?'); $s->execute(array('en')); // Works print_r($s->fetchAll()); $s->execute(array(2)); // Does not work print_r($s->fetchAll()); ``` I Am testing against this table: ``` DROP TABLE IF EXISTS t2; CREATE TABLE t2 ( id int(10) NOT NULL AUTO_INCREMENT, lang enum('no','en','fr') NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO t2 (id, lang) VALUES (NULL , 'en'); ``` Any idea on how to get this to work? I am converting to PDO, and I'd prefer not to rewrite all constants, enums, and queries in my app :(
2010/09/02
[ "https://Stackoverflow.com/questions/3625569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168502/" ]
`2` is not a valid ENUM element. It's as simple as that. The reason it works in raw MySQL when you do `lang = 2`, is that it's exposing the underlying storage mechanism for the list (basically it's just a normalized value, but the normalization is hid from you by the ENUM column). I'd suggest not trying to do this. MySQL hides the implementation for a reason. Realize that using `2` for the comparison is nothing more than a [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming))...
language shouldn't be an enum, infact **don't use enums** at all instead use separate lookup/type tables: ``` create table languages ( lang_id tinyint unsigned not null auto_increment primary key, name varchar(255) unique not null ) engine=innodb; create table customers ( cust_id int unsigned not null auto_increment primary key, lang_id tinyint unsigned not null, foreign key (lang_id) references languages(lang_id) ) engine=innodb; ``` **you should also be aware that adding a new value to the ENUM definition will require MySQL to rebuild the entire table – less than optimal for large tables !!**
3,625,569
I am using PDO and prepared statements, but i cannot seem to get any results when **comparing an ENUM field with an integer**. Example: ``` $db = new PDO('mysql:host=localhost;dbname=****', '***', '***'); $s = $db->prepare('SELECT id FROM t2 WHERE lang = ?'); $s->execute(array('en')); // Works print_r($s->fetchAll()); $s->execute(array(2)); // Does not work print_r($s->fetchAll()); ``` I Am testing against this table: ``` DROP TABLE IF EXISTS t2; CREATE TABLE t2 ( id int(10) NOT NULL AUTO_INCREMENT, lang enum('no','en','fr') NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO t2 (id, lang) VALUES (NULL , 'en'); ``` Any idea on how to get this to work? I am converting to PDO, and I'd prefer not to rewrite all constants, enums, and queries in my app :(
2010/09/02
[ "https://Stackoverflow.com/questions/3625569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168502/" ]
`2` is not a valid ENUM element. It's as simple as that. The reason it works in raw MySQL when you do `lang = 2`, is that it's exposing the underlying storage mechanism for the list (basically it's just a normalized value, but the normalization is hid from you by the ENUM column). I'd suggest not trying to do this. MySQL hides the implementation for a reason. Realize that using `2` for the comparison is nothing more than a [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming))...
**Reasoning:** I agree that you should not have to select anything by enum index or even use database enums at all, but there are always exceptions and special cases. In my case, it's a legacy system that is of course meant to be replaced by a new system, but that will take at least one year, possibly way longer. Any database changes to the legacy system have a large impact and we try to keep them at a minimum. We do have a small table with users groups, and the group ids are also set as enums. So yes, adding a group does also require adding another enum value to that table's id column. I do have no knowledge about how this came to be and I don't question it, I just have to deal with it until we can completely replace it. I want to provide a simple user administration since any user changes right now have to go through a long process which results in a developer doing the changes directly in the database. The user groups are hierarchical by enum index and I wanted to filter the available groups in the administration to be less than or equal to the currently logged-in users group. Long story short; To make this work in a prepared statement, I did this: ```sql SELECT `groups`.*, `groups`.`id`+0 AS groupId FROM groups WHERE `groups`.`id`+0 <= ?; ``` **Explanation:** By adding `+0` to the column, MySQL automatically treats the column as an integer and uses the enum index instead of the value. It's a simple trick that may cause other problems, but I didn't encounter any so far.
3,625,569
I am using PDO and prepared statements, but i cannot seem to get any results when **comparing an ENUM field with an integer**. Example: ``` $db = new PDO('mysql:host=localhost;dbname=****', '***', '***'); $s = $db->prepare('SELECT id FROM t2 WHERE lang = ?'); $s->execute(array('en')); // Works print_r($s->fetchAll()); $s->execute(array(2)); // Does not work print_r($s->fetchAll()); ``` I Am testing against this table: ``` DROP TABLE IF EXISTS t2; CREATE TABLE t2 ( id int(10) NOT NULL AUTO_INCREMENT, lang enum('no','en','fr') NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO t2 (id, lang) VALUES (NULL , 'en'); ``` Any idea on how to get this to work? I am converting to PDO, and I'd prefer not to rewrite all constants, enums, and queries in my app :(
2010/09/02
[ "https://Stackoverflow.com/questions/3625569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168502/" ]
language shouldn't be an enum, infact **don't use enums** at all instead use separate lookup/type tables: ``` create table languages ( lang_id tinyint unsigned not null auto_increment primary key, name varchar(255) unique not null ) engine=innodb; create table customers ( cust_id int unsigned not null auto_increment primary key, lang_id tinyint unsigned not null, foreign key (lang_id) references languages(lang_id) ) engine=innodb; ``` **you should also be aware that adding a new value to the ENUM definition will require MySQL to rebuild the entire table – less than optimal for large tables !!**
**Reasoning:** I agree that you should not have to select anything by enum index or even use database enums at all, but there are always exceptions and special cases. In my case, it's a legacy system that is of course meant to be replaced by a new system, but that will take at least one year, possibly way longer. Any database changes to the legacy system have a large impact and we try to keep them at a minimum. We do have a small table with users groups, and the group ids are also set as enums. So yes, adding a group does also require adding another enum value to that table's id column. I do have no knowledge about how this came to be and I don't question it, I just have to deal with it until we can completely replace it. I want to provide a simple user administration since any user changes right now have to go through a long process which results in a developer doing the changes directly in the database. The user groups are hierarchical by enum index and I wanted to filter the available groups in the administration to be less than or equal to the currently logged-in users group. Long story short; To make this work in a prepared statement, I did this: ```sql SELECT `groups`.*, `groups`.`id`+0 AS groupId FROM groups WHERE `groups`.`id`+0 <= ?; ``` **Explanation:** By adding `+0` to the column, MySQL automatically treats the column as an integer and uses the enum index instead of the value. It's a simple trick that may cause other problems, but I didn't encounter any so far.
10,748,397
When I run the following code in *debug* mode, it'll successfully finish and exit. However, if I run the following code in *release* mode, it'll get stuck in an infinite loop and never finish. ``` static void Main(string[] args) { bool stop = false; new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ``` Which optimization is causing it to get stuck in an infinite loop?
2012/05/25
[ "https://Stackoverflow.com/questions/10748397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103791/" ]
My guess would be processor caching of the `stop` variable on the main thread. In debug mode the memory model is stricter because the debugger needs to be able to provide a sensible view of the variable's state across all threads. Try making a field and marking it as [volatile](http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx): ``` volatile bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ```
Because it's not thread safe you update the main thread variable `stop` inside the child thread. It will always be unpredictable. To work with any situation like this, have a look on [this article](http://www.albahari.com/threading/part4.aspx). > > The volatile keyword instructs the compiler to generate an > acquire-fence on every read from that field, and a release-fence on > every write to that field. An acquire-fence prevents other > reads/writes from being moved before the fence; a release-fence > prevents other reads/writes from being moved after the fence. These > “half-fences” are faster than full fences because they give the > runtime and hardware more scope for optimization. > > >
10,748,397
When I run the following code in *debug* mode, it'll successfully finish and exit. However, if I run the following code in *release* mode, it'll get stuck in an infinite loop and never finish. ``` static void Main(string[] args) { bool stop = false; new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ``` Which optimization is causing it to get stuck in an infinite loop?
2012/05/25
[ "https://Stackoverflow.com/questions/10748397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103791/" ]
Because it's not thread safe you update the main thread variable `stop` inside the child thread. It will always be unpredictable. To work with any situation like this, have a look on [this article](http://www.albahari.com/threading/part4.aspx). > > The volatile keyword instructs the compiler to generate an > acquire-fence on every read from that field, and a release-fence on > every write to that field. An acquire-fence prevents other > reads/writes from being moved before the fence; a release-fence > prevents other reads/writes from being moved after the fence. These > “half-fences” are faster than full fences because they give the > runtime and hardware more scope for optimization. > > >
Thread Unsafe code is unpredictable. Main problem is changing one thread variable from another thread. Make the variable global or volatile. You can do it by following ``` static volatile bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ```
10,748,397
When I run the following code in *debug* mode, it'll successfully finish and exit. However, if I run the following code in *release* mode, it'll get stuck in an infinite loop and never finish. ``` static void Main(string[] args) { bool stop = false; new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ``` Which optimization is causing it to get stuck in an infinite loop?
2012/05/25
[ "https://Stackoverflow.com/questions/10748397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103791/" ]
Because it's not thread safe you update the main thread variable `stop` inside the child thread. It will always be unpredictable. To work with any situation like this, have a look on [this article](http://www.albahari.com/threading/part4.aspx). > > The volatile keyword instructs the compiler to generate an > acquire-fence on every read from that field, and a release-fence on > every write to that field. An acquire-fence prevents other > reads/writes from being moved before the fence; a release-fence > prevents other reads/writes from being moved after the fence. These > “half-fences” are faster than full fences because they give the > runtime and hardware more scope for optimization. > > >
Looks like some sort of optimization for value of local variable - changing to a field make it terminate ok (note that volatile or correct locking should be used in actual code): ``` using System; using System.Threading; class Program { static bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } } ```
10,748,397
When I run the following code in *debug* mode, it'll successfully finish and exit. However, if I run the following code in *release* mode, it'll get stuck in an infinite loop and never finish. ``` static void Main(string[] args) { bool stop = false; new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ``` Which optimization is causing it to get stuck in an infinite loop?
2012/05/25
[ "https://Stackoverflow.com/questions/10748397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103791/" ]
My guess would be processor caching of the `stop` variable on the main thread. In debug mode the memory model is stricter because the debugger needs to be able to provide a sensible view of the variable's state across all threads. Try making a field and marking it as [volatile](http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx): ``` volatile bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ```
Thread Unsafe code is unpredictable. Main problem is changing one thread variable from another thread. Make the variable global or volatile. You can do it by following ``` static volatile bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ```
10,748,397
When I run the following code in *debug* mode, it'll successfully finish and exit. However, if I run the following code in *release* mode, it'll get stuck in an infinite loop and never finish. ``` static void Main(string[] args) { bool stop = false; new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ``` Which optimization is causing it to get stuck in an infinite loop?
2012/05/25
[ "https://Stackoverflow.com/questions/10748397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103791/" ]
My guess would be processor caching of the `stop` variable on the main thread. In debug mode the memory model is stricter because the debugger needs to be able to provide a sensible view of the variable's state across all threads. Try making a field and marking it as [volatile](http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx): ``` volatile bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } ```
Looks like some sort of optimization for value of local variable - changing to a field make it terminate ok (note that volatile or correct locking should be used in actual code): ``` using System; using System.Threading; class Program { static bool stop = false; static void Main(string[] args) { new Thread(() => { Thread.Sleep(1000); stop = true; Console.WriteLine("Set \"stop\" to true."); }).Start(); Console.WriteLine("Entering loop."); while (!stop) { } Console.WriteLine("Done."); } } ```
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
The phrase makes sense in English but the meaning it conveys is far too severe for the context you give. An "abuse of trust" in English would be a very serious matter and even describes some illegal acts - for example, the definition "*abuse of a position of trust*" is used in British law to describe sexual activity between a teacher and student, or a caregiver and care-recipient. Not quite the same thing as asking to borrow someone's car. I think the equivalent expression you are looking for is: > > Sorry for the *imposition*... > > > Preceding a polite request this normally implies that you are aware you are asking for slightly more than would normally be expected. Another alternative may be to say: > > I hope this isn't *presumptuous*, but... > > > This is another way that some may soften a request by apologising in advance for presuming that it is possible.
English uses the phrase *abuse of trust* as well, but it would not be used in the kind of sentence you proposed. Here are some examples of *abuse of trust* taken from English-language periodicals (compiled by *[The Free Dictionary](https://legal-dictionary.thefreedictionary.com/Abuse+of+trust)*) > > "Your actions in pursuing an emotional and sexual relationship, and in having sexual intercourse with [a patient receiving psychiatric care from you], were a gross abuse of trust." > > > "And a new offence, abuse of trust, will stop adults exploiting under- 18s in schools, the forces and places of care." > > > "In a gross abuse of trust, Pringle, one of a small number of people with access to the committee room, began taking cashed tickets and re-cashing them for himself." > > > The last example is perhaps the easiest to explain. Pringle was given access to the committee room, where something valuable was stored, because people trusted him. They trusted him not to steal the valuables. He abused their trust by stealing the tickets. Asking for a favor from someone may be an abuse of trust, but probably not in the case you described. If you convince someone to let you borrow their car by lying to them, that may be an abuse of trust. If you repeatedly ask to borrow someone's car, but are always honest about the reason, there is no abuse of trust, but it may be an *abuse of their goodwill*.
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
English uses the phrase *abuse of trust* as well, but it would not be used in the kind of sentence you proposed. Here are some examples of *abuse of trust* taken from English-language periodicals (compiled by *[The Free Dictionary](https://legal-dictionary.thefreedictionary.com/Abuse+of+trust)*) > > "Your actions in pursuing an emotional and sexual relationship, and in having sexual intercourse with [a patient receiving psychiatric care from you], were a gross abuse of trust." > > > "And a new offence, abuse of trust, will stop adults exploiting under- 18s in schools, the forces and places of care." > > > "In a gross abuse of trust, Pringle, one of a small number of people with access to the committee room, began taking cashed tickets and re-cashing them for himself." > > > The last example is perhaps the easiest to explain. Pringle was given access to the committee room, where something valuable was stored, because people trusted him. They trusted him not to steal the valuables. He abused their trust by stealing the tickets. Asking for a favor from someone may be an abuse of trust, but probably not in the case you described. If you convince someone to let you borrow their car by lying to them, that may be an abuse of trust. If you repeatedly ask to borrow someone's car, but are always honest about the reason, there is no abuse of trust, but it may be an *abuse of their goodwill*.
As others have said, in English "abuse of trust" is a rather strong statement. [This answer](https://ell.stackexchange.com/a/196327/1990) says that the expression better translates as "to take advantage of someone due to the trust they have in you." Have you considered an alternative like "abuse of your hospitality?" That seems a better translation of the sentiment. E.g. > > Sorry to abuse your hospitality, but I wonder if you'd do me a favor. Can I borrow your car for the weekend? > > > This would sound fine to me in American English. It does suggest that you are a guest of the person of whom you are making the request. You can replace [hospitality](https://www.merriam-webster.com/dictionary/hospitality) with other words, e.g. [generosity](https://www.merriam-webster.com/dictionary/generosity) would be more general. Or friendship (which would imply that the two of you are friends). Another possibility would be "Would it be too much to ask?" E.g. > > Would it be too much to ask if I could borrow your car for the weekend? > > > If the goal is to soften the request.
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
The phrase makes sense in English but the meaning it conveys is far too severe for the context you give. An "abuse of trust" in English would be a very serious matter and even describes some illegal acts - for example, the definition "*abuse of a position of trust*" is used in British law to describe sexual activity between a teacher and student, or a caregiver and care-recipient. Not quite the same thing as asking to borrow someone's car. I think the equivalent expression you are looking for is: > > Sorry for the *imposition*... > > > Preceding a polite request this normally implies that you are aware you are asking for slightly more than would normally be expected. Another alternative may be to say: > > I hope this isn't *presumptuous*, but... > > > This is another way that some may soften a request by apologising in advance for presuming that it is possible.
I don't mean **to take advantage of you** or our friendship, but could I borrow your car? The Spanish expression used in everyday language really means: **to take advantage of someone due to the trust they have in you.** It has nothing to do with the legal term, **breach of trust**. The idiomatic expression and legal expression are two different things in English. No quiero abusar de tu confianza: I don't want to take advantage of you [in the sense of: given the trust you have in me]
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
The phrase makes sense in English but the meaning it conveys is far too severe for the context you give. An "abuse of trust" in English would be a very serious matter and even describes some illegal acts - for example, the definition "*abuse of a position of trust*" is used in British law to describe sexual activity between a teacher and student, or a caregiver and care-recipient. Not quite the same thing as asking to borrow someone's car. I think the equivalent expression you are looking for is: > > Sorry for the *imposition*... > > > Preceding a polite request this normally implies that you are aware you are asking for slightly more than would normally be expected. Another alternative may be to say: > > I hope this isn't *presumptuous*, but... > > > This is another way that some may soften a request by apologising in advance for presuming that it is possible.
As a native (Scottish) speaker, I would use something like: ``` "I'm sorry to impose" ``` or simply: ``` "I'm sorry, but I wonder if you would mind doing me a favour?" ```
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
The phrase makes sense in English but the meaning it conveys is far too severe for the context you give. An "abuse of trust" in English would be a very serious matter and even describes some illegal acts - for example, the definition "*abuse of a position of trust*" is used in British law to describe sexual activity between a teacher and student, or a caregiver and care-recipient. Not quite the same thing as asking to borrow someone's car. I think the equivalent expression you are looking for is: > > Sorry for the *imposition*... > > > Preceding a polite request this normally implies that you are aware you are asking for slightly more than would normally be expected. Another alternative may be to say: > > I hope this isn't *presumptuous*, but... > > > This is another way that some may soften a request by apologising in advance for presuming that it is possible.
As others have said, in English "abuse of trust" is a rather strong statement. [This answer](https://ell.stackexchange.com/a/196327/1990) says that the expression better translates as "to take advantage of someone due to the trust they have in you." Have you considered an alternative like "abuse of your hospitality?" That seems a better translation of the sentiment. E.g. > > Sorry to abuse your hospitality, but I wonder if you'd do me a favor. Can I borrow your car for the weekend? > > > This would sound fine to me in American English. It does suggest that you are a guest of the person of whom you are making the request. You can replace [hospitality](https://www.merriam-webster.com/dictionary/hospitality) with other words, e.g. [generosity](https://www.merriam-webster.com/dictionary/generosity) would be more general. Or friendship (which would imply that the two of you are friends). Another possibility would be "Would it be too much to ask?" E.g. > > Would it be too much to ask if I could borrow your car for the weekend? > > > If the goal is to soften the request.
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
I don't mean **to take advantage of you** or our friendship, but could I borrow your car? The Spanish expression used in everyday language really means: **to take advantage of someone due to the trust they have in you.** It has nothing to do with the legal term, **breach of trust**. The idiomatic expression and legal expression are two different things in English. No quiero abusar de tu confianza: I don't want to take advantage of you [in the sense of: given the trust you have in me]
As others have said, in English "abuse of trust" is a rather strong statement. [This answer](https://ell.stackexchange.com/a/196327/1990) says that the expression better translates as "to take advantage of someone due to the trust they have in you." Have you considered an alternative like "abuse of your hospitality?" That seems a better translation of the sentiment. E.g. > > Sorry to abuse your hospitality, but I wonder if you'd do me a favor. Can I borrow your car for the weekend? > > > This would sound fine to me in American English. It does suggest that you are a guest of the person of whom you are making the request. You can replace [hospitality](https://www.merriam-webster.com/dictionary/hospitality) with other words, e.g. [generosity](https://www.merriam-webster.com/dictionary/generosity) would be more general. Or friendship (which would imply that the two of you are friends). Another possibility would be "Would it be too much to ask?" E.g. > > Would it be too much to ask if I could borrow your car for the weekend? > > > If the goal is to soften the request.
196,274
In Spanish we use this expression **abuse of your trust** usually in formal writing to apologise in advance when we want to ask for something that one wouldn't do if wasn't because our trust. Example. > > Sorry for making **abuse of your trust** but I wonder you'd do a favour. Can I borrow your car for the weekend? > > > How would you express this in English? Thanks.
2019/02/11
[ "https://ell.stackexchange.com/questions/196274", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/12125/" ]
As a native (Scottish) speaker, I would use something like: ``` "I'm sorry to impose" ``` or simply: ``` "I'm sorry, but I wonder if you would mind doing me a favour?" ```
As others have said, in English "abuse of trust" is a rather strong statement. [This answer](https://ell.stackexchange.com/a/196327/1990) says that the expression better translates as "to take advantage of someone due to the trust they have in you." Have you considered an alternative like "abuse of your hospitality?" That seems a better translation of the sentiment. E.g. > > Sorry to abuse your hospitality, but I wonder if you'd do me a favor. Can I borrow your car for the weekend? > > > This would sound fine to me in American English. It does suggest that you are a guest of the person of whom you are making the request. You can replace [hospitality](https://www.merriam-webster.com/dictionary/hospitality) with other words, e.g. [generosity](https://www.merriam-webster.com/dictionary/generosity) would be more general. Or friendship (which would imply that the two of you are friends). Another possibility would be "Would it be too much to ask?" E.g. > > Would it be too much to ask if I could borrow your car for the weekend? > > > If the goal is to soften the request.
29,228,393
See this simple regexp code: ``` puts [ regexp -inline {^\-\-\S+?=\S+} "--tox=9.0" ] ``` The output is: ``` >--tox=9 ``` It would seem that the second \S+ is being non-greedy! Only 1 character is being matched In PERL, one can can see that the result is as I expected, see 1 line output: ``` perl -e '"--tox=9.0" =~/(^\-\-\S+?=\S+)/ ; print "${1}\n"' --tox=9.0 ``` How can I get the Perl behaviour in Tcl?
2015/03/24
[ "https://Stackoverflow.com/questions/29228393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134991/" ]
This is an inherent 'feature' of Tcl's regexp implementation. For instance, the [below](https://groups.google.com/forum/#!msg/comp.lang.tcl/FddeFPbTFw8/asoMuv7dWqIJ) is from Henry Spencer (the one who did most if not all of Tcl's regexp work I believe) > > It is very difficult to come up with an entirely satisfactory > definition of the behavior of mixed-greediness regular expressions. > Perl doesn't try: the Perl "specification" is a description of the > implementation, an inherently low-performance approach involving > trying one match at a time. This is unsatisfactory for a number of > reasons, not least being that it takes several pages of text merely to > describe it. (That implementation and its description are distant, > mutated descendants of one of my earlier regexp packages, so I share > some of the blame for this.) > > > When all quantifiers are greedy, the Tcl 8.2 regexp matches the > longest possible match (as specified in the POSIX standard's > regular-expression definition). When all are non-greedy, it matches > the shortest possible match. Neither of these desirable statements is > true of Perl. > > > The trouble is that it is very, very hard to write a generalization of > those statements which covers mixed-greediness regular expressions -- > a proper, implementation-independent definition of what > mixed-greediness regular expressions *should* match -- and makes them > do "what people expect". I've tried. I'm still trying. No luck so > far. > > > The rules in the Tcl 8.2 regexp, which basically give the whole regexp > a long/short preference based on its subexpressions, are the best I've > come up with so far. The code implements them accurately. I agree > that they fall short of what's really wanted. It's trickier than it > looks. > > > Basically, expressions with mixed greedy and non-greedy quantifiers impacts both the simplicity of the implementation and the performance. So, the implementation makes it so that the first 'type' of quantifier is passed on to all other quantifiers. In other words, if the first quantifier is greedy, all the others will be greedy. If the first is non-greedy, all the others will be non-greedy. And therefore, you cannot force a Tcl regexp to work like a Perl regexp (or maybe you can through `exec` and using the bash command version of perl, but I'm not familiar with this). I would advise using negated classes and/or anchors instead of non-greedy. Since I don't know the exact context of your question, I won't provide an alternative regexp, because that will depend on whether this is really the whole string you are trying to make a match on.
The Tcl regular expression engine is an automata-theoretic one instead of a stack-based one, so it has a *very* different approach to matching mixed greediness REs. In particular, for the sort of RE you're talking about, that will be interpreted as entirely non-greedy. The simplest method of fixing this is to use a different RE. Remembering that `\S` is just a shorthand for `[^\s]`, we can do this (excluding `=` from the first part): ``` puts [ regexp -inline {^--[^\s=]+=\S+} "--tox=9.0" ] ``` (I also changed `\-` to `-` as it's not a special character in Tcl's REs.)
29,228,393
See this simple regexp code: ``` puts [ regexp -inline {^\-\-\S+?=\S+} "--tox=9.0" ] ``` The output is: ``` >--tox=9 ``` It would seem that the second \S+ is being non-greedy! Only 1 character is being matched In PERL, one can can see that the result is as I expected, see 1 line output: ``` perl -e '"--tox=9.0" =~/(^\-\-\S+?=\S+)/ ; print "${1}\n"' --tox=9.0 ``` How can I get the Perl behaviour in Tcl?
2015/03/24
[ "https://Stackoverflow.com/questions/29228393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134991/" ]
This is an inherent 'feature' of Tcl's regexp implementation. For instance, the [below](https://groups.google.com/forum/#!msg/comp.lang.tcl/FddeFPbTFw8/asoMuv7dWqIJ) is from Henry Spencer (the one who did most if not all of Tcl's regexp work I believe) > > It is very difficult to come up with an entirely satisfactory > definition of the behavior of mixed-greediness regular expressions. > Perl doesn't try: the Perl "specification" is a description of the > implementation, an inherently low-performance approach involving > trying one match at a time. This is unsatisfactory for a number of > reasons, not least being that it takes several pages of text merely to > describe it. (That implementation and its description are distant, > mutated descendants of one of my earlier regexp packages, so I share > some of the blame for this.) > > > When all quantifiers are greedy, the Tcl 8.2 regexp matches the > longest possible match (as specified in the POSIX standard's > regular-expression definition). When all are non-greedy, it matches > the shortest possible match. Neither of these desirable statements is > true of Perl. > > > The trouble is that it is very, very hard to write a generalization of > those statements which covers mixed-greediness regular expressions -- > a proper, implementation-independent definition of what > mixed-greediness regular expressions *should* match -- and makes them > do "what people expect". I've tried. I'm still trying. No luck so > far. > > > The rules in the Tcl 8.2 regexp, which basically give the whole regexp > a long/short preference based on its subexpressions, are the best I've > come up with so far. The code implements them accurately. I agree > that they fall short of what's really wanted. It's trickier than it > looks. > > > Basically, expressions with mixed greedy and non-greedy quantifiers impacts both the simplicity of the implementation and the performance. So, the implementation makes it so that the first 'type' of quantifier is passed on to all other quantifiers. In other words, if the first quantifier is greedy, all the others will be greedy. If the first is non-greedy, all the others will be non-greedy. And therefore, you cannot force a Tcl regexp to work like a Perl regexp (or maybe you can through `exec` and using the bash command version of perl, but I'm not familiar with this). I would advise using negated classes and/or anchors instead of non-greedy. Since I don't know the exact context of your question, I won't provide an alternative regexp, because that will depend on whether this is really the whole string you are trying to make a match on.
The answer can be found [here](https://groups.google.com/forum/#!msg/comp.lang.tcl/FddeFPbTFw8/asoMuv7dWqIJ): > > Unfortunately, the answer is that to get the same answer Perl gives, > you have to use Perl's exact regexp implementation. > > > In your case, I'd use both anchors, `^` and `$`: ``` puts [ regexp -inline {^\-\-\S+?=\S+$} "--tox=9.0" ] ``` The result is: `--tox=9.0`