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
|
---|---|---|---|---|---|
16,430,373 | I'm trying to implement OpenCV into my application but every time I call a function there is a memory leak. I guess it has something to do with how I have used the library with Visual Studio but I tested it with a blank project and it seemed to work fine with the same settings.
The code I'm trying to implement into:
```
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize Microsoft Foundation Classes, and print an error if failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// Application starts here...
// Time the application's execution time.
TIMER start;
// CODE TO GO HERE!
TIMER end;
TIMER elapsed;
elapsed = end - start;
__int64 ticks_per_second = start.get_frequency();
// Display the resulting time...
double elapsed_seconds = (double)elapsed.get_time() / (double)ticks_per_second;
cout << "Elapsed time (seconds): " << elapsed_seconds;
cout << endl;
cout << "Press a key to continue" << endl;
char c;
cin >> c;
}
return nRetCode;
}
```
If I implement something as simple as:
```
cv::Mat aVar;
```
in the space where I have put "CODE TO GO HERE!" Visual Studio says there is a memory leak once the program has terminated. Any ideas what the problem could be? | 2013/05/07 | [
"https://Stackoverflow.com/questions/16430373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1145456/"
]
| Like I said in your last post, the details are important. The non-MFC dll loads before MFC dll and if there is any data not freed before MFC exits, MFC falsely reports this as a memory leak. This is a [known issue](http://comments.gmane.org/gmane.comp.lib.opencv/43423) which is a problem when using opencv with mfc. The solution is to:
1. Static link MFC library (most common way)
2. Try the workaround to force mfc dll to be loaded first in the link above
3. Delay loading dlls as seen in [this question](https://stackoverflow.com/questions/9232837/how-to-remove-memory-leaks-between-opencv-1-1-and-mfc-6-0-without-linking-mfc-as). | I've noticed in the debug version that the combination of MFC and OpenCV can also result in strange behavior when you additionally use fopen and fread. fread might return error 9 (The storage control block address is invalid).
Again, delayed loading the OpenCV dlls might solve the problem. |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| To interact with data model (call its invoke method?), you could build a rest service inside the driver. This service listens for requests, and invokes model's predict method with input from the request, and returns result.
http4s (<https://github.com/http4s/http4s>) could be used for this purpose.
Spark SQL is not relevant, as it is to handle data analytics (which you have done already), with sql capabilities.
Hope this helps. | For this kind of situation was developed a REST interface for lunching and sharing the context of spark jobs
Give a look at the documentation here :
<https://github.com/spark-jobserver/spark-jobserver> |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| To interact with data model (call its invoke method?), you could build a rest service inside the driver. This service listens for requests, and invokes model's predict method with input from the request, and returns result.
http4s (<https://github.com/http4s/http4s>) could be used for this purpose.
Spark SQL is not relevant, as it is to handle data analytics (which you have done already), with sql capabilities.
Hope this helps. | For isolating the user sessions and showing the results in an isolated manner, you may need to use queues with a binded user identity. Incase the the results takes time, with this identity you can show the respective results to the user. |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| just pass the spark context and session as a bean in Spring
```
@Bean
public SparkConf sparkConf() {
SparkConf sparkConf = new SparkConf()
.setAppName(appName)
.setSparkHome(sparkHome)
.setMaster(masterUri);
return sparkConf;
}
@Bean
public JavaSparkContext javaSparkContext() {
return new JavaSparkContext(sparkConf());
}
@Bean
public SparkSession sparkSession() {
return SparkSession
.builder()
.sparkContext(javaSparkContext().sc())
.appName("Java Spark Ravi")
.getOrCreate();
}
```
Similarly for xml based configuration
Fully working code with spring and spark is present here
<https://github.com/ravi-code-ranjan/spark-spring-seed-project> | To interact with data model (call its invoke method?), you could build a rest service inside the driver. This service listens for requests, and invokes model's predict method with input from the request, and returns result.
http4s (<https://github.com/http4s/http4s>) could be used for this purpose.
Spark SQL is not relevant, as it is to handle data analytics (which you have done already), with sql capabilities.
Hope this helps. |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| To interact with data model (call its invoke method?), you could build a rest service inside the driver. This service listens for requests, and invokes model's predict method with input from the request, and returns result.
http4s (<https://github.com/http4s/http4s>) could be used for this purpose.
Spark SQL is not relevant, as it is to handle data analytics (which you have done already), with sql capabilities.
Hope this helps. | I am a bit late , but this can help other users.
If the requirement is to fetch data from Spark remotely, then you can consider using HiveThriftServer2.
This server exposes the Spark SQL (cached and temporary tables) as JDBC/ODBC Database.
So, you can connect to Spark by using a JDBC/ODBC driver, and access data from the SQL tables.
To do the above:
1. Include this code in your Spark application:
A. Create Spark conf with following properties:
```
config.set("hive.server2.thrift.port","10015");
config.set("spark.sql.hive.thriftServer.singleSession", "true");
```
B.Then , pass the SQL context to the thrift server , and start it as below:
```
HiveThriftServer2.startWithContext(session.sqlContext());
```
This will start the Thrift server with the SQL context of your application. So it will be able to return data from the tables created in this context
2. On the client side, you can use below code to connect to Spark SQL:
```
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10015/default", "", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select count(1) from ABC");
``` |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| just pass the spark context and session as a bean in Spring
```
@Bean
public SparkConf sparkConf() {
SparkConf sparkConf = new SparkConf()
.setAppName(appName)
.setSparkHome(sparkHome)
.setMaster(masterUri);
return sparkConf;
}
@Bean
public JavaSparkContext javaSparkContext() {
return new JavaSparkContext(sparkConf());
}
@Bean
public SparkSession sparkSession() {
return SparkSession
.builder()
.sparkContext(javaSparkContext().sc())
.appName("Java Spark Ravi")
.getOrCreate();
}
```
Similarly for xml based configuration
Fully working code with spring and spark is present here
<https://github.com/ravi-code-ranjan/spark-spring-seed-project> | For this kind of situation was developed a REST interface for lunching and sharing the context of spark jobs
Give a look at the documentation here :
<https://github.com/spark-jobserver/spark-jobserver> |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| just pass the spark context and session as a bean in Spring
```
@Bean
public SparkConf sparkConf() {
SparkConf sparkConf = new SparkConf()
.setAppName(appName)
.setSparkHome(sparkHome)
.setMaster(masterUri);
return sparkConf;
}
@Bean
public JavaSparkContext javaSparkContext() {
return new JavaSparkContext(sparkConf());
}
@Bean
public SparkSession sparkSession() {
return SparkSession
.builder()
.sparkContext(javaSparkContext().sc())
.appName("Java Spark Ravi")
.getOrCreate();
}
```
Similarly for xml based configuration
Fully working code with spring and spark is present here
<https://github.com/ravi-code-ranjan/spark-spring-seed-project> | For isolating the user sessions and showing the results in an isolated manner, you may need to use queues with a binded user identity. Incase the the results takes time, with this identity you can show the respective results to the user. |
30,795,960 | I am trying to build a Movie Recommender System Using Apache Spark MLlib.
I have written a code for recommender in java and its working fine when run using `spark-submit` command.
My run command looks like this
`bin/spark-submit --jars /opt/poc/spark-1.3.1-bin-hadoop2.6/mllib/spark-mllib_2.10-1.0.0.jar --class "com.recommender.MovieLensALSExtended" --master local[4] /home/sarvesh/Desktop/spark-test/recommender.jar /home/sarvesh/Desktop/spark-test/ml-latest-small/ratings.csv /home/sarvesh/Desktop/spark-test/ml-latest-small/movies.csv`
Now I want to use my recommender in real world scenario, as a web application in which I can query recommender to give some result.
I want to build a Spring MVC web application which can interact with Apache Spark Context and give me results when asked.
My question is that how I can build an application which interacts with Apache Spark which is running on a cluster. So that when a request comes to controller it should take user query and fetch the same result as the `spark-submit` command outputs on console.
As far as I have searched, I found that we can use Spark SQL, integrate with JDBC. But I did not find any good example.
Thanks in advance. | 2015/06/12 | [
"https://Stackoverflow.com/questions/30795960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2381737/"
]
| just pass the spark context and session as a bean in Spring
```
@Bean
public SparkConf sparkConf() {
SparkConf sparkConf = new SparkConf()
.setAppName(appName)
.setSparkHome(sparkHome)
.setMaster(masterUri);
return sparkConf;
}
@Bean
public JavaSparkContext javaSparkContext() {
return new JavaSparkContext(sparkConf());
}
@Bean
public SparkSession sparkSession() {
return SparkSession
.builder()
.sparkContext(javaSparkContext().sc())
.appName("Java Spark Ravi")
.getOrCreate();
}
```
Similarly for xml based configuration
Fully working code with spring and spark is present here
<https://github.com/ravi-code-ranjan/spark-spring-seed-project> | I am a bit late , but this can help other users.
If the requirement is to fetch data from Spark remotely, then you can consider using HiveThriftServer2.
This server exposes the Spark SQL (cached and temporary tables) as JDBC/ODBC Database.
So, you can connect to Spark by using a JDBC/ODBC driver, and access data from the SQL tables.
To do the above:
1. Include this code in your Spark application:
A. Create Spark conf with following properties:
```
config.set("hive.server2.thrift.port","10015");
config.set("spark.sql.hive.thriftServer.singleSession", "true");
```
B.Then , pass the SQL context to the thrift server , and start it as below:
```
HiveThriftServer2.startWithContext(session.sqlContext());
```
This will start the Thrift server with the SQL context of your application. So it will be able to return data from the tables created in this context
2. On the client side, you can use below code to connect to Spark SQL:
```
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10015/default", "", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select count(1) from ABC");
``` |
7,344,674 | I'm a little confused as to why this isn't the default behaviour?
So, how do I detect the enter key being pressed on my button and fire the click event handler? (For example on a TextInput field there is an 'enter' event)
Thanks | 2011/09/08 | [
"https://Stackoverflow.com/questions/7344674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112549/"
]
| 1. Create a service to download the content from the server.
2. Add your activity to it for custom event listening
3. Broadcast event [Completion, Part-Completion] to the registered listener when the service is able to do the job.
4. Till that time either show a splash screen or a download screen with progress bar indicating download progress.
5. On listening to "Completion" notification you can show the main activity.
Hope this helps | You should make a `Splash` `Activity` for your application. So this will be an `Activity` that displays only a picture, let say your application logo or something similar. Then check if your app has all ready downloaded the videos and photos, you can do this by keeping a boolean field in `SharedPreferences` let say `DATA_DOWNLOADED`. If the data is not downloaded then you will need to start s `Service` that will download all the data, also display a `ProgressIndicator` and a message for the user, that data is being downloaded.
Once the data is downloaded you mark the `DATA_DOWNLOADED` field in your `SharedPreferences` and you start the next `Activity`.
Good luck. |
2,572,624 | I have a VB6 program which I've been maintaining for ten years. There is a subroutine in the program called "Prepare Copy", which looks like this (Edited to add changes):
```
Public Sub PrepareCopy()
On Local Error GoTo PrepareCopyError
MsgBox "in modeldescription preparecopy"
Set CopiedShapes = New Collection
MsgBox "leaving preparecopy"
Exit Sub
PrepareCopyError:
MsgBox Err.Description, , Err.Number
Resume Next
End Sub
```
Where `CopiedShapes` is dimmed out as a VB6 Collection.
That code is now kicking out a Runtime Error 5 -- Invalid Procedure Call or Argument. It appears from the interstitial debugging code that the error arises *between* the `MsgBox "in modeldescription preparecopy"` and the `MsgBox "leaving preparecopy"` lines, and that the `On Error` code path never executes.
Once the Error 5 dialog box is cleared, *then* the `MsgBox "leaving preparecopy"` dialog appears, after which the program closes out.
It's behaving this way on my development machine and two client computers.
It is only happening in runtime code, and does not appear to make a difference whether I compile it or use P-Code
What I'm asking for here is speculation as to what causes this sort of thing to happen. | 2010/04/03 | [
"https://Stackoverflow.com/questions/2572624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/252710/"
]
| Your recent comment says that the variable is `Public CopiedShapes as New Collection`.
1. Could you try removing the `new` in the declaration?
2. Are there any instances in the Collection with a `Sub Class_Terminate()` which are being called when the old Collection is garbage collected along with its contents? | Does the error occur only on machine/s different than where the code was compiled? It may be that some DLLs are missing in the runtime environment (like MSVBRT.dll or the like).
Easiest way to figure it out: run on the build machine.
If it doesn't happen there, you can create a deployable version (an installer) through VB6) that will include all that's needed. OR, use [SysInternals' Procmon](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to monitor the process as it runs and see which resource (file, DLL, reg key) it's attempting to access at the time of the error. |
2,572,624 | I have a VB6 program which I've been maintaining for ten years. There is a subroutine in the program called "Prepare Copy", which looks like this (Edited to add changes):
```
Public Sub PrepareCopy()
On Local Error GoTo PrepareCopyError
MsgBox "in modeldescription preparecopy"
Set CopiedShapes = New Collection
MsgBox "leaving preparecopy"
Exit Sub
PrepareCopyError:
MsgBox Err.Description, , Err.Number
Resume Next
End Sub
```
Where `CopiedShapes` is dimmed out as a VB6 Collection.
That code is now kicking out a Runtime Error 5 -- Invalid Procedure Call or Argument. It appears from the interstitial debugging code that the error arises *between* the `MsgBox "in modeldescription preparecopy"` and the `MsgBox "leaving preparecopy"` lines, and that the `On Error` code path never executes.
Once the Error 5 dialog box is cleared, *then* the `MsgBox "leaving preparecopy"` dialog appears, after which the program closes out.
It's behaving this way on my development machine and two client computers.
It is only happening in runtime code, and does not appear to make a difference whether I compile it or use P-Code
What I'm asking for here is speculation as to what causes this sort of thing to happen. | 2010/04/03 | [
"https://Stackoverflow.com/questions/2572624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/252710/"
]
| Procmon was not helpful. Microsoft took a deep-dive image of the system at the point the problem was occurring.
They found a bad HRESULT failure code. Something deep in the VB6 runtime was attempting to access a late-bound but undeclared object through an IDispatch interface. They swiftly scheduled a call with me. I asked which object was being called through IDispatch; there are no late-bound calls in the VB6 portions of my project. ("option explicit")
In the call, they told me to go away. They refused to help identify further root causes, because VB6 code was involved and the support department is forbidden to troubleshoot VB6 problems. I countered that this was clearly a problem in the supported runtime, to no avail.
Instead, I got a 20 minute lecture on the economies of supporting something when there was no money to be made. I replied with a war story about a thrice-virtualized application still running after 35 years at a phone company.
They were good guys; they wanted to help me solve the problem but their policies forbade it. I'm no closer to a root cause today than I was when I posted the question.
However, if you call MsgBox from the VB6 runtimes, it sends `WM_USER` messages to other VB6 forms in the project. That, in turn, in my case, triggered `MDIForm_Activate` in which there was this code:
```
Me.TreeView1.SetFocus
```
And that, in spite of the fact that TreeView1 was by definition declared explicitly, was what they declared as the cause of the failed late-bind IDispatch call, all the while refusing to explain how that could be. The guy on the phone even went so far as to say that he absolutely could figure it out, but Microsoft policy forbade it, because that's VB6, there.
Removing the `SetFocus` call removed the circumstance which produced the error. | Does the error occur only on machine/s different than where the code was compiled? It may be that some DLLs are missing in the runtime environment (like MSVBRT.dll or the like).
Easiest way to figure it out: run on the build machine.
If it doesn't happen there, you can create a deployable version (an installer) through VB6) that will include all that's needed. OR, use [SysInternals' Procmon](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to monitor the process as it runs and see which resource (file, DLL, reg key) it's attempting to access at the time of the error. |
2,572,624 | I have a VB6 program which I've been maintaining for ten years. There is a subroutine in the program called "Prepare Copy", which looks like this (Edited to add changes):
```
Public Sub PrepareCopy()
On Local Error GoTo PrepareCopyError
MsgBox "in modeldescription preparecopy"
Set CopiedShapes = New Collection
MsgBox "leaving preparecopy"
Exit Sub
PrepareCopyError:
MsgBox Err.Description, , Err.Number
Resume Next
End Sub
```
Where `CopiedShapes` is dimmed out as a VB6 Collection.
That code is now kicking out a Runtime Error 5 -- Invalid Procedure Call or Argument. It appears from the interstitial debugging code that the error arises *between* the `MsgBox "in modeldescription preparecopy"` and the `MsgBox "leaving preparecopy"` lines, and that the `On Error` code path never executes.
Once the Error 5 dialog box is cleared, *then* the `MsgBox "leaving preparecopy"` dialog appears, after which the program closes out.
It's behaving this way on my development machine and two client computers.
It is only happening in runtime code, and does not appear to make a difference whether I compile it or use P-Code
What I'm asking for here is speculation as to what causes this sort of thing to happen. | 2010/04/03 | [
"https://Stackoverflow.com/questions/2572624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/252710/"
]
| Procmon was not helpful. Microsoft took a deep-dive image of the system at the point the problem was occurring.
They found a bad HRESULT failure code. Something deep in the VB6 runtime was attempting to access a late-bound but undeclared object through an IDispatch interface. They swiftly scheduled a call with me. I asked which object was being called through IDispatch; there are no late-bound calls in the VB6 portions of my project. ("option explicit")
In the call, they told me to go away. They refused to help identify further root causes, because VB6 code was involved and the support department is forbidden to troubleshoot VB6 problems. I countered that this was clearly a problem in the supported runtime, to no avail.
Instead, I got a 20 minute lecture on the economies of supporting something when there was no money to be made. I replied with a war story about a thrice-virtualized application still running after 35 years at a phone company.
They were good guys; they wanted to help me solve the problem but their policies forbade it. I'm no closer to a root cause today than I was when I posted the question.
However, if you call MsgBox from the VB6 runtimes, it sends `WM_USER` messages to other VB6 forms in the project. That, in turn, in my case, triggered `MDIForm_Activate` in which there was this code:
```
Me.TreeView1.SetFocus
```
And that, in spite of the fact that TreeView1 was by definition declared explicitly, was what they declared as the cause of the failed late-bind IDispatch call, all the while refusing to explain how that could be. The guy on the phone even went so far as to say that he absolutely could figure it out, but Microsoft policy forbade it, because that's VB6, there.
Removing the `SetFocus` call removed the circumstance which produced the error. | Your recent comment says that the variable is `Public CopiedShapes as New Collection`.
1. Could you try removing the `new` in the declaration?
2. Are there any instances in the Collection with a `Sub Class_Terminate()` which are being called when the old Collection is garbage collected along with its contents? |
10,328,238 | I have to add an Upload file functionality using Kendo ui in my grails application. also i have to know how to change the upload location.
thnks | 2012/04/26 | [
"https://Stackoverflow.com/questions/10328238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727079/"
]
| Here is the solution that we came up with to dynamically change the saveUrl on the Kendo UI Upload widget.
Controller code:
```
public class MediaController : ApiControllerBase
{
public Task<HttpResponseMessage> Post()
{
var queryVals = Request.RequestUri.ParseQueryString();
string idValue = queryVals["id"].ToString();
... CODE REMOVE FOR BREVITY
}
}
```
And the Script code:
```
<div style="width:45%">
<input class="upload" name="files" id="files" type="file" upload-id="02ebeebf-98aa-459b-b41f-49028fa37e9c" />
<input class="upload" name="files2" id="file1" type="file" upload-id="499499D3-1C80-4930-8C8D-C87F17884D3F" />
</div>
<script>
$(document).ready(function () {
$(".upload").kendoUpload({
async: {
saveUrl: "/API/Media",
autoUpload: true
},
upload: function onUpload(e) {
var uploadId = e.sender.wrapper.prevObject.attr("upload-id");
e.sender.options.async.saveUrl = "/api/media?id=" + uploadId;
},
});
});
</script>
``` | Check out the KendoUI Upload configuration documentation here: <http://www.kendoui.com/documentation/ui-widgets/upload/configuration.aspx>
The saveUrl option on the async object allows you to set the handler for the submitted file(s) with ease. |
10,328,238 | I have to add an Upload file functionality using Kendo ui in my grails application. also i have to know how to change the upload location.
thnks | 2012/04/26 | [
"https://Stackoverflow.com/questions/10328238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727079/"
]
| Here is the solution that we came up with to dynamically change the saveUrl on the Kendo UI Upload widget.
Controller code:
```
public class MediaController : ApiControllerBase
{
public Task<HttpResponseMessage> Post()
{
var queryVals = Request.RequestUri.ParseQueryString();
string idValue = queryVals["id"].ToString();
... CODE REMOVE FOR BREVITY
}
}
```
And the Script code:
```
<div style="width:45%">
<input class="upload" name="files" id="files" type="file" upload-id="02ebeebf-98aa-459b-b41f-49028fa37e9c" />
<input class="upload" name="files2" id="file1" type="file" upload-id="499499D3-1C80-4930-8C8D-C87F17884D3F" />
</div>
<script>
$(document).ready(function () {
$(".upload").kendoUpload({
async: {
saveUrl: "/API/Media",
autoUpload: true
},
upload: function onUpload(e) {
var uploadId = e.sender.wrapper.prevObject.attr("upload-id");
e.sender.options.async.saveUrl = "/api/media?id=" + uploadId;
},
});
});
</script>
``` | You can just change the saveUrl property. The code should look like this:
```
this.documentUpload.options.async.saveUrl = '/newUrlStr';
``` |
1,257,636 | Need to do a proof by mathematical induction using 4 steps to show that the following statement is true for every positive integer n and to help use the weak principle of mathematical induction.
$2 + 6 + 18 + ... + 2\times{3^{n-1}} = 3^n-1$
1. show that the base step is true
2. What is the inductive hypothesis?
3. what do we have to show?
4. proof proper (Justify each step): | 2015/04/29 | [
"https://math.stackexchange.com/questions/1257636",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/224929/"
]
| Base Step: $2 \cdot 3^{1-1} = 2 = 3^1 - 1$
The inductive hypothesis is: $\sum\_{n=1}^{k} 2 \cdot 3^{n-1} = 3^k - 1$
We must show that under the assumption of the inductive hypothesis that $$3^k - 1 + 2 \cdot 3^k = 3^{k + 1} - 1$$
We verify this as $$3^k - 1 + 2 \cdot 3^k = 3^k(1 + 2) - 1$$
$$= 3^{k+1} - 1$$ | **Hint** $\ $ By a very simple transformation we can reduce the induction to a very trivial induction, namely if $\,g(n)\,$ is constant $\,g(n\!+\!1)=g(n)\,$ then $\,g(n) = g(0)\,$
The $\rm\ RHS$ and $\rm LHS$ have equal first difference $\,f(n\!+\!1)-f(n) = 2\cdot 3^n,\,$ therefore defining $\,g(n) := \rm RHS - LHS$ $\Rightarrow$ $\,\color{#c00}{g(n\!+\!1)-g(n) = 0},\ g(0) = 0,\,$ so an obvious induction shows that $\,g(n) = 0\,$ for all $\,n,\,$ i.e. $\,\color{#0a0}{g(n)=0}\,\Rightarrow\,$ $\,g(n\!+\!1) = \color{#c00}{g(n\!+\!1)-g(n)} + \color{#0a0}{g(n)} = \color{#c00}0 + \color{#0a0}0 = 0.\ $ Therefore, for all $\,n\,$ we have $\,g(n) =\rm RHS - LHS = 0,\,$ i.e. $\rm RHS = LHS.\ $ **QED**
**Remark** $\ $ This is a prototypical case of *telescopic* induction, which often serves to greatly simplify inductive proofs. The above transformation essentially shows that both sides equal $\,\sum 2\cdot 3^k,\,$ by rewriting them as a (telescopic) sum of their first differences $\,\sum\,(f\_{k+1}\!-f\_k).\,$ For many further examples of telescopy [see here.](https://math.stackexchange.com/search?q=user%3A242+telescopy) |
183,105 | I have two accepted papers X and Y. I listed X as a reference for Y. I used "To appear" in front of X in the reference section of Y. But it has not published yet. How can I add volume details of X, while it seems that X will be published after publishing Y? | 2022/03/09 | [
"https://academia.stackexchange.com/questions/183105",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/49646/"
]
| I think it is possible under one of the following options:
1. If possible and allowed by the publisher, you publish a preprint of X (e.g. arXiv or PubMed) and you cite the preprint (which is a very common practice nowadays). When X will be published by the publisher, most of the bibliographic indices/platforms will link it to its preprint and make two versions of the same paper.
2. You cite X without mentioning the volume and page range, which is also normal and common. There is no standard rule telling authors how to cite and up to my knowledge, no publisher has specific requirements on how to cite. E.g. for the sake of space, I abreviate journals and conferences' names.
Please refer also to [I have two papers in an up-coming conference. Is it appropriate to cite one in another?](https://academia.stackexchange.com/questions/8443/i-have-two-papers-in-an-up-coming-conference-is-it-appropriate-to-cite-one-in-a) and [How could two papers which were both published in the same year and same conference cite each other?](https://www.quora.com/How-could-two-papers-which-were-both-published-in-the-same-year-and-same-conference-cite-each-other) | I don’t know what your field is. I did my PhD in Molecular Biophysics ten years ago. It was customary to just list your paper X as “in press” and the corresponding journal name, if it’s cited in your paper Y reference. |
14,358,499 | I would like to know if there is some way in Swing to turn an ImageIcon to gray scale in a way like:
```
component.setIcon(greyed(imageIcon));
``` | 2013/01/16 | [
"https://Stackoverflow.com/questions/14358499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308202/"
]
| One limitation of `GrayFilter.createDisabledImage()` is that it is designed to create a *disabled* appearance for icons across diverse Look & Feel implementations. Using this `ColorConvertOp` [example](https://stackoverflow.com/a/12228640/230513), the following images contrast the effect:
`GrayFilter.createDisabledImage()`: `com.apple.laf.AquaLookAndFeel`

`ColorConvertOp#filter()`: `com.apple.laf.AquaLookAndFeel`

`GrayFilter.createDisabledImage()`: `com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel`

`ColorConvertOp#filter()`: `com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel`

```
/**
* @see https://stackoverflow.com/q/14358499/230513
* @see https://stackoverflow.com/a/12228640/230513
*/
private Icon getGray(Icon icon) {
final int w = icon.getIconWidth();
final int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g2d = image.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
Image gray = GrayFilter.createDisabledImage(image);
return new ImageIcon(gray);
}
``` | You can use the following:
```
ImageIcon icon = new ImageIcon("yourFile.gif");
Image normalImage = icon.getImage();
Image grayImage = GrayFilter.createDisabledImage(normalImage);
``` |
52,541,481 | 1. Is it possible to create & submit an PWA launcher icon to a website marketplace?
2. The launcher icon should work like a "Add to home screen" PWA function.
What I am trying to achieve is a PWA store making it easy for users to Add an icon to their homescreen for launching a PWA website. Please advice. | 2018/09/27 | [
"https://Stackoverflow.com/questions/52541481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10425302/"
]
| If you mean that in your web marketplace, you want to get the icons of submitted PWA then, you can get the `PWA` launch icons from either the link tags:
```
<link rel="icon" sizes="192x192" href="nice-highres.png"> (recommended)
<link rel="icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon-precomposed" sizes="128x128" href="niceicon.png">
```
or from the `manifest.json` icons section:
```
{
"short_name": "Maps",
"name": "Google Maps",
"icons": [
{
"src": "/images/icons-192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/images/icons-512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": "/maps/?source=pwa",
"background_color": "#3367D6",
"display": "standalone",
"scope": "/maps/",
"theme_color": "#3367D6"
}
``` | This is posible neither in iOS nor in Android:
### Regarding the icons
1. *Android* depends on the `manifest.json` file at the root of your domain to handle the information about the PWA.
2. *iOS:* You may be able to change the icon and launch screen at the top of the page holding the link to the PWA, but this will not help you in any way, because Safari iOS does not allow you to generate a bookmark programmatically.
### Regarding the actual link saved to the desktop
1. *Android Chrome* checks the status of both the manifest and the certificate in the site before popping up the option to save a PWA to the Home Screen. If the popup appears in your site it will be for your PWA, not for the linked PWA.
2. *iOS* [does not have a way to programmatically add bookmarks](https://stackoverflow.com/questions/1141979/javascript-for-add-to-home-screen-on-iphone). This seems to be on purpose, as a security measure. The only way to add the bookmark to the desktop is using the Safari Share button. Safari does validate your certificate at that moment before downloading the custom icon.
I understand that [Android now lets you install PWAs from the Play Store](https://www.quora.com/Can-you-put-a-PWA-progressive-web-app-onto-the-Google-Play-store-app-store), but the process to publish them there is convoluted.
### What you can do
1. Provide great information for users on how to install the PWAs listed in your site.
2. Provide code to generate an install popup system in iOS for the developers publishing in your store, branded. We [had to do that screen for this website](https://licitaciones.chilediseno.org) and it took quite some time to get it right. |
52,541,481 | 1. Is it possible to create & submit an PWA launcher icon to a website marketplace?
2. The launcher icon should work like a "Add to home screen" PWA function.
What I am trying to achieve is a PWA store making it easy for users to Add an icon to their homescreen for launching a PWA website. Please advice. | 2018/09/27 | [
"https://Stackoverflow.com/questions/52541481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10425302/"
]
| You can set the icon to be displayed according to sizes on home screen in manifest.json file.
<https://developers.google.com/web/fundamentals/web-app-manifest/>
```
"icons": [
{
"src": "/images/icons-192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/images/icons-512.png",
"type": "image/png",
"sizes": "512x512"
}
]
``` | This is posible neither in iOS nor in Android:
### Regarding the icons
1. *Android* depends on the `manifest.json` file at the root of your domain to handle the information about the PWA.
2. *iOS:* You may be able to change the icon and launch screen at the top of the page holding the link to the PWA, but this will not help you in any way, because Safari iOS does not allow you to generate a bookmark programmatically.
### Regarding the actual link saved to the desktop
1. *Android Chrome* checks the status of both the manifest and the certificate in the site before popping up the option to save a PWA to the Home Screen. If the popup appears in your site it will be for your PWA, not for the linked PWA.
2. *iOS* [does not have a way to programmatically add bookmarks](https://stackoverflow.com/questions/1141979/javascript-for-add-to-home-screen-on-iphone). This seems to be on purpose, as a security measure. The only way to add the bookmark to the desktop is using the Safari Share button. Safari does validate your certificate at that moment before downloading the custom icon.
I understand that [Android now lets you install PWAs from the Play Store](https://www.quora.com/Can-you-put-a-PWA-progressive-web-app-onto-the-Google-Play-store-app-store), but the process to publish them there is convoluted.
### What you can do
1. Provide great information for users on how to install the PWAs listed in your site.
2. Provide code to generate an install popup system in iOS for the developers publishing in your store, branded. We [had to do that screen for this website](https://licitaciones.chilediseno.org) and it took quite some time to get it right. |
77,191 | I have a [YubiKey NEO](https://www.yubico.com/products/yubikey-hardware/yubikey-neo/) which has a lot of amazing capabilities such as OTP, U2F, and PGP smart card for PGP/GPG and even SSH keys. One of the applications I've discovered recently for the device is [a PIV applet](https://developers.yubico.com/yubico-piv-tool/) which you can use to securely store a SSL certificate's private RSA key.
I find this pretty fascinating, as it makes it much more difficult without physical access to steal a SSL certificate.
Is it possible to use a smart card like this for a SSL server's private key? I've never seen configuration in Apache or nginx which would seem to indicate support for anything other than file-based SSL private keys.
Also, [the demo given for the PIV applet](https://developers.yubico.com/yubico-piv-tool/Certificate_Authority_with_NEO.html) shows how to create a local file-based private key and then send it to the smart card; is there a way to create the key securely on the card, so that it is never stored anywhere? I know I could just store it in a RAM disk/filesystem so that it's never written to disk, but is there a way to generate it on-device as is possible using OpenPGP for PGP keys? | 2014/12/31 | [
"https://security.stackexchange.com/questions/77191",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/2374/"
]
| >
> I've never seen configuration in Apache or nginx which would seem to
> indicate support for anything other than file-based SSL private keys.
>
>
>
You are using the Yubikey as a Hardware Security Module (HSM). They key is stored on and never leaves the HSM and all encryption and decryption is done on the HSM. The Yubikey seems to fulfill such the requirements.
You might need to write your own PKCS#11 driver since there isn't one out there. For the server side, you would have to use `mod_nss` instead of `mod_ssl`. `mod_nss` allows you to use a custom PKCS#11 driver whereas `mod_ssl` uses the default openssl engine.
Compared with other purpose built HSMs, I am unsure of the stability of using the Yubikey as a HSM. This is because the main use case of a yubikey is for applications which require one-time access, e.g. authentication, encrypting an email and not for applications which require continuous access. A server under load might overwhelm the Yubikey and result in sluggish performance. | Apache supports specifying the crypto device. The directive is called [SSLCryptoDevice](https://httpd.apache.org/docs/2.4/mod/mod_ssl.html#sslcryptodevice). You can specify
Pkcs11 as the device. Update: according to [this answer](https://serverfault.com/a/711611/81387) it's not supported with mod\_ssl. That answer suggests mod\_nss, which supports it. According to <https://mod.gnutls.org/> mod\_gnutls also supports pkcs11. |
19,777,395 | i have a database like this

it have content of a site i grabbed with a php script and linux cron jobs
after i got all pages of the sites it goes to work slowly
and server load is:

now i cant run a small query like this
```
SELECT * FROM `content` WHERE `html` LIKE '%%simple%%'
```
i think 3gb is not to much for mysql!
the server have dual 5620 cpu with 32 g of ram
with this hardware i think ed it can handle up to 2tb of db!!
UPDATE 1 :
my content table is like this

i have one index and its the id but a query like this need a lot of time to run too
```
<?php echo mysql_num_rows(mysql_query("SELECT * FROM pages where `update_date`!='0000-00-00 00:00:00' and `type`='page';")); ?>
```
you mean i just change the `html` field to full text!? | 2013/11/04 | [
"https://Stackoverflow.com/questions/19777395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149172/"
]
| Using `LIKE` as you are with wildcards on both sides does not allow MySQL to utilize an index (if the field is indexed) so 3GB of database to slog through would actually take quite a while. I would recommend removing the left hand wildcards and (potentially) taking a look at `MATCH AGAINST` using a `FULLTEXT` index.
For more: <http://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html>
It is worth noting that in MySQL **PRIOR** to version 5.6 you will need to convert your table to MyISAM to utilize the `FULLTEXT` engine. In 5.6 and up you can use them in InnoDB as well as MyISAM. If for some reason you can't upgrade or use 5.6+, then you could always setup a MyISAM table with only the information you need to have stored for `FULLTEXT` purposes. Then setup triggers to duplicate/remove information from the MyISAM table as it gets deleted from the InnoDB. This may not work within your project goals, but it is one solution. | Every time that query runs you're searching through *3 billion* characters for a string match.
[You need to use an index](http://use-the-index-luke.com/sql/where-clause/searching-for-ranges/like-performance-tuning).
I also think you're using the wrong query predicate and should use a [full-text-search](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html) which is designed for this sort of thing. You also want to index the full-text-search. |
3,637,553 | The code below returns `none`. How can I fix it? I'm using Python 2.6.
```
import urllib
URL = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=sl1t1v&e=.csv"
symbols = ('GGP', 'JPM', 'AIG', 'AMZN','GGP', 'JPM', 'AIG', 'AMZN')
#symbols = ('GGP')
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
def main():
data_fp = fetch_quote(symbols)
# print data_fp
if __name__ =='__main__':
main()
``` | 2010/09/03 | [
"https://Stackoverflow.com/questions/3637553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428862/"
]
| You have to explicitly `return` the `data` from `fetch_quote` function. Something like this:
```
def fetch_quote(symbols):
url = URL % '+'.join(symbols)
fp = urllib.urlopen(url)
try:
data = fp.read()
finally:
fp.close()
return data # <======== Return
```
In the absence of an explicit return statement Python returns `None` which is what you are seeing. | Your method doesn't explicitly `return` anything, so it `returns` `None` |
16,938,113 | I have a form like this:
```
<form method="post" enctype="multipart/form-data">
<input type="text" id="title" placeholder="Project Title"/><br />
<input type="text" id="vurl" placeholder="If You have any video about project write your video url path here" style="width:435px;"/><br />
<textarea id="prjdesc" name="prjdesc" rows="20" cols="80" style="border-style:groove;box-shadow: 10px 10px 10px 10px #888888;"placeholder="Please describe Your Project"></textarea>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br>
<input type="button" name="submit" value="Submit" id="update"/>
</form>
```
On click submit the data is storing in database and displaying using Ajax call
this is my js code:
```
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var dataString = 'param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
```
here i am storing data using insert.php and displaying using another.php
but when coming to the image part i dont understand how to store image in folder and path in db, i mean i am bit confused to integrate code in insert.php
insert.php
```
$host="localhost";
$username="root";
$password="";
$db_name="geny";
$tbl_name="project_details";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$name = $_POST['param'];
$video = $_POST['param1'];
$title = $_POST['param2'];
$sql="INSERT INTO $tbl_name (title, content, video_url) VALUES ('$title','$name','$video')";
if(mysql_query($sql)) {
echo mysql_insert_id();
} else {
echo "Cannot Insert";
}
```
if i do separate then the image is storing in folder..
if i do separate then the form code is:
```
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
```
upload\_file.php:
```
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 50000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]);
// echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$tmp = "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"];
echo $tmp;
}
}
}
else
{
echo "Invalid file";
}
?>
```
this is working perfectly...
my question is how to integrate this code in insert.php...
please help me... | 2013/06/05 | [
"https://Stackoverflow.com/questions/16938113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2330772/"
]
| This code would work fine without the use of javascript. But make sure to change the directory and the table name and fields on line "2" and "66" resp.
We will create a hidden textarea which will create the datastring and we will get all the params using $\_GET
```
<script>
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var textareastring = $('#string').val();
var dataString = 'textareastring' = textareastring;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php?param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
</script>
<textarea id="string" style="display:none;">aa</textarea>
<?php
$name = $_GET['param3'];
// The name.n ow replacing all the $file_name with $name
$url = $_GET['param1'];
$text = $_GET['param'];
$title = $_GET['param2'];
$upload_dir = $url;
$num_files = 1;
//the file size in bytes.
$size_bytes =104857600; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".tif",".gif",".png",".jpeg",".jpg");
//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist. ");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> . ");
}
if (isset($_POST['upload_form'])){
echo "<h3>Upload results:</h3><br>";
//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {
//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$name = str_replace(' ', '_', $name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];
#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#
if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File: Not selected.<br><br>";
}else{
#-----------------------------------------------------------#
# this code will check file extension #
#-----------------------------------------------------------#
$ext = strrchr($name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($name) Wrong file extension. <br><br>";
}else{
#-----------------------------------------------------------#
# this code will check file size is correct #
#-----------------------------------------------------------#
if ($file_size > $size_bytes){
echo "File : ($name) Faild to upload. File must be no larger than <b>100 MB</b> in size.";
}else{
#-----------------------------------------------------------#
# this code check if file is Already EXISTS. #
#-----------------------------------------------------------#
if(file_exists($upload_dir.$name)){
echo "File: ($name) already exists. <br><br>";
}else{
#-------------------------------#
# this function will upload the files. #
#-------------------------------#
if (move_uploaded_file($file_tmp,$upload_dir.$name)) {
$sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
echo "File: ($name) has been uploaded successfully." . "<img src='uploads/$name'/>";
}else{
echo "File: Faild to upload. <br><br>";
}#end of (move_uploaded_file).
}#end of (file_exists).
}#end of (file_size).
}#end of (limitedext).
}#end of (!is_uploaded_file).
}#end of (for loop).
# print back button.
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo "<form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form- data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "<b>Image: </b><input type=\"file\" size=\"70\" name=\"file". $i ."\" style=\"width:45%\">";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload\">
</form>";
}
?>
``` | ```
<?php
/*dont use path like this C:/wamp/www/WebsiteTemplate4/upload/ becuase you are working at localhost server*/
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
$file = $_FILES["file"]["name"]
$filePath = "upload/" . $file;
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filePath)){
/*prepare sql query here and insert*/
$sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
if(mysql_query($sql)){
echo "File saved in database successfully <strong>{$filePath}</strong>";
}else{
echo "File not uploaded there are an error <strong>{$filePath}</strong>";
}
}else{
echo "File not uploaded there are an error <strong>{$file}</strong>";
}
} ?>
```
try this code if you have any doubt or code not working fine then ask me again.
Thanks |
16,938,113 | I have a form like this:
```
<form method="post" enctype="multipart/form-data">
<input type="text" id="title" placeholder="Project Title"/><br />
<input type="text" id="vurl" placeholder="If You have any video about project write your video url path here" style="width:435px;"/><br />
<textarea id="prjdesc" name="prjdesc" rows="20" cols="80" style="border-style:groove;box-shadow: 10px 10px 10px 10px #888888;"placeholder="Please describe Your Project"></textarea>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br>
<input type="button" name="submit" value="Submit" id="update"/>
</form>
```
On click submit the data is storing in database and displaying using Ajax call
this is my js code:
```
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var dataString = 'param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
```
here i am storing data using insert.php and displaying using another.php
but when coming to the image part i dont understand how to store image in folder and path in db, i mean i am bit confused to integrate code in insert.php
insert.php
```
$host="localhost";
$username="root";
$password="";
$db_name="geny";
$tbl_name="project_details";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$name = $_POST['param'];
$video = $_POST['param1'];
$title = $_POST['param2'];
$sql="INSERT INTO $tbl_name (title, content, video_url) VALUES ('$title','$name','$video')";
if(mysql_query($sql)) {
echo mysql_insert_id();
} else {
echo "Cannot Insert";
}
```
if i do separate then the image is storing in folder..
if i do separate then the form code is:
```
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
```
upload\_file.php:
```
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 50000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]);
// echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$tmp = "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"];
echo $tmp;
}
}
}
else
{
echo "Invalid file";
}
?>
```
this is working perfectly...
my question is how to integrate this code in insert.php...
please help me... | 2013/06/05 | [
"https://Stackoverflow.com/questions/16938113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2330772/"
]
| If you mean how to call insert.php after submit button was clicked, in this line
```php
<form method="post" enctype="multipart/form-data">
```
you have to add this
```php
<form method="post" enctype="multipart/form-data" action="insert.php">
``` | ```
<?php
/*dont use path like this C:/wamp/www/WebsiteTemplate4/upload/ becuase you are working at localhost server*/
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
$file = $_FILES["file"]["name"]
$filePath = "upload/" . $file;
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filePath)){
/*prepare sql query here and insert*/
$sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
if(mysql_query($sql)){
echo "File saved in database successfully <strong>{$filePath}</strong>";
}else{
echo "File not uploaded there are an error <strong>{$filePath}</strong>";
}
}else{
echo "File not uploaded there are an error <strong>{$file}</strong>";
}
} ?>
```
try this code if you have any doubt or code not working fine then ask me again.
Thanks |
16,938,113 | I have a form like this:
```
<form method="post" enctype="multipart/form-data">
<input type="text" id="title" placeholder="Project Title"/><br />
<input type="text" id="vurl" placeholder="If You have any video about project write your video url path here" style="width:435px;"/><br />
<textarea id="prjdesc" name="prjdesc" rows="20" cols="80" style="border-style:groove;box-shadow: 10px 10px 10px 10px #888888;"placeholder="Please describe Your Project"></textarea>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br>
<input type="button" name="submit" value="Submit" id="update"/>
</form>
```
On click submit the data is storing in database and displaying using Ajax call
this is my js code:
```
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var dataString = 'param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
```
here i am storing data using insert.php and displaying using another.php
but when coming to the image part i dont understand how to store image in folder and path in db, i mean i am bit confused to integrate code in insert.php
insert.php
```
$host="localhost";
$username="root";
$password="";
$db_name="geny";
$tbl_name="project_details";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$name = $_POST['param'];
$video = $_POST['param1'];
$title = $_POST['param2'];
$sql="INSERT INTO $tbl_name (title, content, video_url) VALUES ('$title','$name','$video')";
if(mysql_query($sql)) {
echo mysql_insert_id();
} else {
echo "Cannot Insert";
}
```
if i do separate then the image is storing in folder..
if i do separate then the form code is:
```
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
```
upload\_file.php:
```
<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 50000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"]);
// echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
$tmp = "C:/wamp/www/WebsiteTemplate4/upload/" . $_FILES["file"]["name"];
echo $tmp;
}
}
}
else
{
echo "Invalid file";
}
?>
```
this is working perfectly...
my question is how to integrate this code in insert.php...
please help me... | 2013/06/05 | [
"https://Stackoverflow.com/questions/16938113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2330772/"
]
| This code would work fine without the use of javascript. But make sure to change the directory and the table name and fields on line "2" and "66" resp.
We will create a hidden textarea which will create the datastring and we will get all the params using $\_GET
```
<script>
$("#update").click(function(e) {
alert("update");
e.preventDefault();
var ttle = $("#title").val();
alert(ttle);
var text = $("#prjdesc").val();
var vurl = $("#vurl").val();
var img = $("#file").val();
alert(vurl);
var textareastring = $('#string').val();
var dataString = 'textareastring' = textareastring;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php?param='+text+'¶m1='+vurl+'¶m2='+ttle+'¶m3='+img',
success:function(id) {
alert(id);
window.location ="another.php?id="+id;;
}
});
});
</script>
<textarea id="string" style="display:none;">aa</textarea>
<?php
$name = $_GET['param3'];
// The name.n ow replacing all the $file_name with $name
$url = $_GET['param1'];
$text = $_GET['param'];
$title = $_GET['param2'];
$upload_dir = $url;
$num_files = 1;
//the file size in bytes.
$size_bytes =104857600; //51200 bytes = 50KB.
//Extensions you want files uploaded limited to.
$limitedext = array(".tif",".gif",".png",".jpeg",".jpg");
//check if the directory exists or not.
if (!is_dir("$upload_dir")) {
die ("Error: The directory <b>($upload_dir)</b> doesn't exist. ");
}
//check if the directory is writable.
if (!is_writeable("$upload_dir")){
die ("Error: The directory <b>($upload_dir)</b> . ");
}
if (isset($_POST['upload_form'])){
echo "<h3>Upload results:</h3><br>";
//do a loop for uploading files based on ($num_files) number of files.
for ($i = 1; $i <= $num_files; $i++) {
//define variables to hold the values.
$new_file = $_FILES['file'.$i];
$name = $new_file['name'];
//to remove spaces from file name we have to replace it with "_".
$name = str_replace(' ', '_', $name);
$file_tmp = $new_file['tmp_name'];
$file_size = $new_file['size'];
#-----------------------------------------------------------#
# this code will check if the files was selected or not. #
#-----------------------------------------------------------#
if (!is_uploaded_file($file_tmp)) {
//print error message and file number.
echo "File: Not selected.<br><br>";
}else{
#-----------------------------------------------------------#
# this code will check file extension #
#-----------------------------------------------------------#
$ext = strrchr($name,'.');
if (!in_array(strtolower($ext),$limitedext)) {
echo "File $i: ($name) Wrong file extension. <br><br>";
}else{
#-----------------------------------------------------------#
# this code will check file size is correct #
#-----------------------------------------------------------#
if ($file_size > $size_bytes){
echo "File : ($name) Faild to upload. File must be no larger than <b>100 MB</b> in size.";
}else{
#-----------------------------------------------------------#
# this code check if file is Already EXISTS. #
#-----------------------------------------------------------#
if(file_exists($upload_dir.$name)){
echo "File: ($name) already exists. <br><br>";
}else{
#-------------------------------#
# this function will upload the files. #
#-------------------------------#
if (move_uploaded_file($file_tmp,$upload_dir.$name)) {
$sql = "INSERT INTO table_name(field1, field2) VALUES('$field1', '$field2');";
echo "File: ($name) has been uploaded successfully." . "<img src='uploads/$name'/>";
}else{
echo "File: Faild to upload. <br><br>";
}#end of (move_uploaded_file).
}#end of (file_exists).
}#end of (file_size).
}#end of (limitedext).
}#end of (!is_uploaded_file).
}#end of (for loop).
# print back button.
////////////////////////////////////////////////////////////////////////////////
//else if the form didn't submitted then show it.
}else{
echo "<form method=\"post\" action=\"$_SERVER[PHP_SELF]\" enctype=\"multipart/form- data\">";
// show the file input field based on($num_files).
for ($i = 1; $i <= $num_files; $i++) {
echo "<b>Image: </b><input type=\"file\" size=\"70\" name=\"file". $i ."\" style=\"width:45%\">";
}
echo " <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$size_bytes\">
<input type=\"submit\" name=\"upload_form\" value=\"Upload\">
</form>";
}
?>
``` | If you mean how to call insert.php after submit button was clicked, in this line
```php
<form method="post" enctype="multipart/form-data">
```
you have to add this
```php
<form method="post" enctype="multipart/form-data" action="insert.php">
``` |
10,621,471 | I isolated the most I can my code into this : <http://jsfiddle.net/uXVWu/>
HTML :
```
<a id="stopHere" >Hi !</a>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
```
JS :
```
var theAnchor=document.getElementById("stopHere");
var tempX,tempY;
function stopScroll(e)
{
var c=parseInt(document.getElementById('stopHere').offsetWidth);
var d=parseInt(document.getElementById('stopHere').offsetHeight);
if(tempX<=c&&tempY<=300+d&&0<=tempX&&300<=tempY)window.scrollTo(0,200);
}
function update(e)
{
var doc=document.documentElement;
var body=document.body;
tempX=(e.pageX)?e.pageX:e.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0);
tempY=(e.pageY)?e.pageY:e.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0);
}
window.onscroll=stopScroll;
window.onmousemove=update;
```
CSS :
```
#stopHere
{
float:left;
width:100%;
border:1px solid black;
text-align:center;
}
```
What does the program is that if the cursor is on the `<a>`, then you scroll, the `<a>` will be on the top. What I want is that you scroll over it and it goes on the top. How can it works? | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365010/"
]
| Do you mean something like this: <http://jsfiddle.net/GTSaz/1/>
So that if, when you are scrolling, your mouse is over the element the scrolling will jump down to have the element at the top of the viewport (0,300 in this case).
Also, if you don't want to hardcode the position (0,300) then you can detect in in the script, see <http://www.quirksmode.org/js/findpos.html> | I am not really sure what do you want . Do you want a `fixed` div or `window.scroll(0,0)`
But, I have combined your's and Adam's code, to workaround the situation.
<http://jsfiddle.net/c3CJF/1/>
**Markup:**
```
<a id="stopHere" >Hi !</a>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
```
**CSS:**
```
#stopHere
{
position:absolute;
top:300px;
left:0px;
width:100%;
border:1px solid black;
text-align:center;
}
```
**Javascript:**
```
var theAnchor=document.getElementById("stopHere");
var tempX,tempY;
var docBody = document.body,
docEl = document.documentElement,
scrollElement = /WebKit/.test(navigator.userAgent) || document.compatMode == 'BackCompat' ? docBody : docEl;
var lastScrollTop = scrollElement.scrollTop;
function stopScroll(e)
{
// Extra check to make if your scroll passes the element on its movement
if((scrollElement.scrollTop - lastScrollTop + tempY) >= 300){
window.scrollTo(0,300);
}
lastScrollTop = scrollElement.scrollTop;
var c=parseInt(document.getElementById('stopHere').offsetWidth);
var d=parseInt(document.getElementById('stopHere').offsetHeight);
/* the if is to test if the mouse is over the anchor */
if(tempX<=c&&tempY<=300+d&&0<=tempX&&300<=tempY)window.scrollTo(0,300);
}
function update(e)//to have the x and y of the mouse
{
var doc=document.documentElement;
var body=document.body;
tempX=(e.pageX)?e.pageX:e.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0);
tempY=(e.pageY)?e.pageY:e.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0);
}
window.onscroll=stopScroll;
window.onmousemove=update;
``` |
10,621,471 | I isolated the most I can my code into this : <http://jsfiddle.net/uXVWu/>
HTML :
```
<a id="stopHere" >Hi !</a>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
```
JS :
```
var theAnchor=document.getElementById("stopHere");
var tempX,tempY;
function stopScroll(e)
{
var c=parseInt(document.getElementById('stopHere').offsetWidth);
var d=parseInt(document.getElementById('stopHere').offsetHeight);
if(tempX<=c&&tempY<=300+d&&0<=tempX&&300<=tempY)window.scrollTo(0,200);
}
function update(e)
{
var doc=document.documentElement;
var body=document.body;
tempX=(e.pageX)?e.pageX:e.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0);
tempY=(e.pageY)?e.pageY:e.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0);
}
window.onscroll=stopScroll;
window.onmousemove=update;
```
CSS :
```
#stopHere
{
float:left;
width:100%;
border:1px solid black;
text-align:center;
}
```
What does the program is that if the cursor is on the `<a>`, then you scroll, the `<a>` will be on the top. What I want is that you scroll over it and it goes on the top. How can it works? | 2012/05/16 | [
"https://Stackoverflow.com/questions/10621471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365010/"
]
| If I'm understanding correctly, you could set it up at top of the page simpler using something like:
```
document.getElementById('stopHere').style.position="fixed"
document.getElementById('stopHere').style.top="0"
``` | I am not really sure what do you want . Do you want a `fixed` div or `window.scroll(0,0)`
But, I have combined your's and Adam's code, to workaround the situation.
<http://jsfiddle.net/c3CJF/1/>
**Markup:**
```
<a id="stopHere" >Hi !</a>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
```
**CSS:**
```
#stopHere
{
position:absolute;
top:300px;
left:0px;
width:100%;
border:1px solid black;
text-align:center;
}
```
**Javascript:**
```
var theAnchor=document.getElementById("stopHere");
var tempX,tempY;
var docBody = document.body,
docEl = document.documentElement,
scrollElement = /WebKit/.test(navigator.userAgent) || document.compatMode == 'BackCompat' ? docBody : docEl;
var lastScrollTop = scrollElement.scrollTop;
function stopScroll(e)
{
// Extra check to make if your scroll passes the element on its movement
if((scrollElement.scrollTop - lastScrollTop + tempY) >= 300){
window.scrollTo(0,300);
}
lastScrollTop = scrollElement.scrollTop;
var c=parseInt(document.getElementById('stopHere').offsetWidth);
var d=parseInt(document.getElementById('stopHere').offsetHeight);
/* the if is to test if the mouse is over the anchor */
if(tempX<=c&&tempY<=300+d&&0<=tempX&&300<=tempY)window.scrollTo(0,300);
}
function update(e)//to have the x and y of the mouse
{
var doc=document.documentElement;
var body=document.body;
tempX=(e.pageX)?e.pageX:e.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc&&doc.clientLeft||body&&body.clientLeft||0);
tempY=(e.pageY)?e.pageY:e.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc&&doc.clientTop||body&&body.clientTop||0);
}
window.onscroll=stopScroll;
window.onmousemove=update;
``` |
562,511 | How do I calculate the size of a filter capacitor to reduce the ripple when I have a microcontroller on the same regulated power supply as a high current load like a motor?
[](https://i.stack.imgur.com/xHeuw.jpg)
**My parameters:**
Motor: DC 5V; 0.82W; 180 mA (with PWM up to 200 mA)
PWM with 70%-100% Duty Cycle
Vdd = 5V = Vmax
PWM: 20kHz
f = 1/20kHz = 50 μs
All the searches I've done lead me to articles about filtering ripple on AC power supplies. However, I'm not trying to smooth ripple from a rectified AC supply. I'm trying to smooth out variations in an already regulated 5V supply as the load to the supply changes.
How do I calculate the rating of a filter capacitor to put on the 5V rail that feeds the microcontroller to smooth its input voltage as the load to the power supply changes? Maybe my calculations are correct? | 2021/04/28 | [
"https://electronics.stackexchange.com/questions/562511",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/56749/"
]
| Since this is homework, I'll rather "hint" you in the right direction to help you employ the right methods than solve it completely, I think you'll enjoy that more!
This gets doable if you start with your first schematic, and apply the Y-Delta transformation on the "inner" three R (those who connect to C). Afterwards, you will have two parallel triangles, and can d simplify the "double edges" individually. | Looking at your redrawn circuit, I can see that
* I5 and I9 are the same current, labelled twice.
* By symmetry, I3 = I4 = I5 = I8
* By symmetry, I6 = I7 = 0 |
17,599,276 | At work we have a web application that is pretty old. So we have a hodge-podge of form-validation solutions. There is a lot of duplicated validation logic, a lot of custom validation logic, some stuff that has been implemented with jQuery validation, some stuff from the bassistance.de validator, and some of the new code even has HTML validation, etc. You get the picture.
We're doing a huge cleanup and refactor on the client side and my task is to figure out ONE WAY to do all the validation. Initially I was going to go with one of the solutions we are already using like jQuery validation, or the bassistance validation plugin. But then I was looking at HTML5 validation and I really like how you can tell from looking at the element what validation rules apply to it. So I decided to go this route. But then I realized that for custom validation, I kind of still have to write them out in Javascript and then there is no easy way to tell if that custom validation rule applies to the element. Basically, I want to do something like this:
```
<input type="text" required="true" customValidationRule="true" />
```
Or something like that. But it gets more complicated than that. Some of our custom validation rules require certain parameters and it would be awesome if I could do something like this:
```
<input type="text" required="true" customValidationRule="true" customValidationRuleParamOne="5" customValidationRuleParamTwo="6" />
```
I also want to validate certain things as groups, like a person's address details, or credit card details, or things like that. For example, it would be useful to do something like this:
```
<input type="text" name="street" required="true" group="addressGroup" />
<input type="text" name="city" required="true" group="addressGroup" />
<input type="text" name="state" required="true" group="addressGroup" />
<input type="text" name="zip" required="true" group="addressGroup" />
```
Then I can just validate everything in "addressGroup" and it would automatically validate all those elements.
To make things more complicated, we also have server-side validation that we do using JSR-303. We currently make AJAX calls for this but I would like to somehow attach that to the element as well using an attribute like *asyncValidationRule="true"* or something. Can you do something like that in HTML5?
I understand if I am asking for too much. But is there a validation library that has at least *some* of these features? What I am going for most is the ability to specify validation rules on the element itself. It is ok if it doesn't have any of the other requirements. I can work around that somehow. | 2013/07/11 | [
"https://Stackoverflow.com/questions/17599276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2573549/"
]
| Some points that you should consider:
1-not all browsers support html5.
2-you can't customize default error messages for required fields.
3-you could use the pattern attribute and validate with a regular expression. [External Resource](http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_pattern)
My suggestion: Take a look at a MVVM library such Backbone or Knockout.
<http://backbonejs.org/#Model-validate> | HTML5 data-\* attributes are useful for this kind of problems.
<http://www.slideshare.net/lensco/html5-data-attributes>
They don't work well with XHTML doctypes, but they do on more lax ones, like HTML 4.01.
jQuery 1.9 (and I think prior versions too) allow you to do things like this:
```
$(someInput).data()
```
which will return an object with all data-\* properties (in camelCase) and their respective values. |
17,599,276 | At work we have a web application that is pretty old. So we have a hodge-podge of form-validation solutions. There is a lot of duplicated validation logic, a lot of custom validation logic, some stuff that has been implemented with jQuery validation, some stuff from the bassistance.de validator, and some of the new code even has HTML validation, etc. You get the picture.
We're doing a huge cleanup and refactor on the client side and my task is to figure out ONE WAY to do all the validation. Initially I was going to go with one of the solutions we are already using like jQuery validation, or the bassistance validation plugin. But then I was looking at HTML5 validation and I really like how you can tell from looking at the element what validation rules apply to it. So I decided to go this route. But then I realized that for custom validation, I kind of still have to write them out in Javascript and then there is no easy way to tell if that custom validation rule applies to the element. Basically, I want to do something like this:
```
<input type="text" required="true" customValidationRule="true" />
```
Or something like that. But it gets more complicated than that. Some of our custom validation rules require certain parameters and it would be awesome if I could do something like this:
```
<input type="text" required="true" customValidationRule="true" customValidationRuleParamOne="5" customValidationRuleParamTwo="6" />
```
I also want to validate certain things as groups, like a person's address details, or credit card details, or things like that. For example, it would be useful to do something like this:
```
<input type="text" name="street" required="true" group="addressGroup" />
<input type="text" name="city" required="true" group="addressGroup" />
<input type="text" name="state" required="true" group="addressGroup" />
<input type="text" name="zip" required="true" group="addressGroup" />
```
Then I can just validate everything in "addressGroup" and it would automatically validate all those elements.
To make things more complicated, we also have server-side validation that we do using JSR-303. We currently make AJAX calls for this but I would like to somehow attach that to the element as well using an attribute like *asyncValidationRule="true"* or something. Can you do something like that in HTML5?
I understand if I am asking for too much. But is there a validation library that has at least *some* of these features? What I am going for most is the ability to specify validation rules on the element itself. It is ok if it doesn't have any of the other requirements. I can work around that somehow. | 2013/07/11 | [
"https://Stackoverflow.com/questions/17599276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2573549/"
]
| **Disclaimer:** I have a horse in this race; I'm the author of the following library.
I've answered a similar question [previously](https://stackoverflow.com/questions/4751780/best-javascript-solution-for-client-side-form-validation-and-interaction?rq=1) that you might want to check out. I'd like to suggest a framework that I've designed called [Regula](https://github.com/vivin/regula/). It does most of what you're asking. Validation rules (or constraints) can be attached directly on the element using the `data-constraints` attribute.
For example, you can do something like this:
```
<input type="text" name="something" data-constraints='@Required' />
```
You can even set things like the error message or labels:
```
<input type="text" name="something" data-constraints='@Required(label="something" message="{label} is required.")' />
```
Custom validation is also easy. You do need to define a validator in JavaScript *once*, but then you can use it after that:
```
regula.custom({
name: "MustBe42",
defaultMessage: "The answer must be equal to 42",
validator: function() {
return this.value == 42;
}
});
```
And then:
```
<input type="text" name="something" data-constraints='@MustBe42' />
```
Parameters are also supported:
```
regula.custom({
name: "MustBeSpecifiedNumber",
params: ["number"],
defaultMessage: "The answer must be equal to {number}",
validator: function(params) {
return this.value === params.number;
}
});
```
And then:
```
<input type="text" name="something" data-constraints='@MustBeSpecifiedNumber(number=10)' />
```
You asked about validation groups, and that can be done in Regula as well:
```
<input type="text" name="street" data-constraints='@Required(groups=[AddressGroup])' />
<input type="text" name="city" data-constraints='@Required(groups=[AddressGroup])' />
<input type="text" name="state" data-constraints='@Required(groups=[AddressGroup])' />
<input type="text" name="zip" data-constraints='@Required(groups=[AddressGroup])' />
```
Then you can validate with:
```
var constraintViolations = regula.validate({
groups: [regula.Group.AddressGroup] //AddressGroup property is automatically added
});
```
As far as HTML5 support and Asynchronous Validation, those features will be available in version 1.3 of Regula, which is currently in Alpha. I have a few minor features and documentation to update, but you should be able to checkout what is in on GitHub currently and it should work for you. HTML5 and Asynchronous Validation is mostly done.
With regard to HTML5 constraints, you can use the native attributes, or use Regula-wrapped versions which provide you more options like assignment to groups and custom messages. For example:
```
<input type="text" name="something" required="true" />
```
Will be recognized by Regula and validated. But you can also do this:
```
<input type="text" name="something" data-constraints='@HTML5Required(groups=[MyGroup], message="{label} is required!", label="something")' />
<input type="text" name="somethingElse" data-constraints='@HTML5Required(groups=[MyGroup], message="{label} is required!", label="somethingElse")' />
```
You can't normally do that with just the native HTML5 validation. An important thing to note however, is that the browser must support HTML5 validation for this to be able to work. Regula doesn't attempt to emulate HTML5 functionality since it involves more than just simple validation; it involves specific UI components as well. So for cross-browser compatibility you will need to use a polyfill or shim of some sort.
Asynchronous validation is also possible:
```
regula.custom({
name: "AsyncConstraint",
async: true,
defaultMessage: "{label} did not validate properly.",
validator: function(params, validator, callback) {
jQuery.ajax({
url: "myurl",
dataType: "json",
data: someData,
success: function(data) {
callback(data.successful)
}
});
}
});
```
Then you can annotate your element with:
```
<input type="text" name="something" data-constraints='@AsynchronousConstraint' />
```
and validate with:
```
//Simply calling validate will validate all constraints on all elements
regula.validate(function(constraintViolations) {
//do stuff with constraintViolations
});
```
It is also easy to do conditional validation and use pre-existing validators:
```
regula.custom({
name: "ConditionalRequired",
defaultMessage: "The answer must be equal to {number}",
validator: function(params, validator) {
var result = true;
if(some condition is true) {
result = validator.required(this, params, validator);
}
return result;
}
});
```
The `validator` object basically gives you access to the raw validator-functions for each of the constraints.
Regula has a bunch of other features as well, such as compound constraints (basically like in JSR-303).
Regula doesn't have any UI-related logic, like displaying error messages as such. It is *only* a validation engine and so it only does that. How you want to display the error messages is up to you.
Hopefully you find this useful! As I mentioned before, the current version is 1.3.0; it is in alpha and you can get it from [here](https://github.com/vivin/regula/). | HTML5 data-\* attributes are useful for this kind of problems.
<http://www.slideshare.net/lensco/html5-data-attributes>
They don't work well with XHTML doctypes, but they do on more lax ones, like HTML 4.01.
jQuery 1.9 (and I think prior versions too) allow you to do things like this:
```
$(someInput).data()
```
which will return an object with all data-\* properties (in camelCase) and their respective values. |
17,599,276 | At work we have a web application that is pretty old. So we have a hodge-podge of form-validation solutions. There is a lot of duplicated validation logic, a lot of custom validation logic, some stuff that has been implemented with jQuery validation, some stuff from the bassistance.de validator, and some of the new code even has HTML validation, etc. You get the picture.
We're doing a huge cleanup and refactor on the client side and my task is to figure out ONE WAY to do all the validation. Initially I was going to go with one of the solutions we are already using like jQuery validation, or the bassistance validation plugin. But then I was looking at HTML5 validation and I really like how you can tell from looking at the element what validation rules apply to it. So I decided to go this route. But then I realized that for custom validation, I kind of still have to write them out in Javascript and then there is no easy way to tell if that custom validation rule applies to the element. Basically, I want to do something like this:
```
<input type="text" required="true" customValidationRule="true" />
```
Or something like that. But it gets more complicated than that. Some of our custom validation rules require certain parameters and it would be awesome if I could do something like this:
```
<input type="text" required="true" customValidationRule="true" customValidationRuleParamOne="5" customValidationRuleParamTwo="6" />
```
I also want to validate certain things as groups, like a person's address details, or credit card details, or things like that. For example, it would be useful to do something like this:
```
<input type="text" name="street" required="true" group="addressGroup" />
<input type="text" name="city" required="true" group="addressGroup" />
<input type="text" name="state" required="true" group="addressGroup" />
<input type="text" name="zip" required="true" group="addressGroup" />
```
Then I can just validate everything in "addressGroup" and it would automatically validate all those elements.
To make things more complicated, we also have server-side validation that we do using JSR-303. We currently make AJAX calls for this but I would like to somehow attach that to the element as well using an attribute like *asyncValidationRule="true"* or something. Can you do something like that in HTML5?
I understand if I am asking for too much. But is there a validation library that has at least *some* of these features? What I am going for most is the ability to specify validation rules on the element itself. It is ok if it doesn't have any of the other requirements. I can work around that somehow. | 2013/07/11 | [
"https://Stackoverflow.com/questions/17599276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2573549/"
]
| **Disclaimer:** I have a horse in this race; I'm the author of the following library.
I've answered a similar question [previously](https://stackoverflow.com/questions/4751780/best-javascript-solution-for-client-side-form-validation-and-interaction?rq=1) that you might want to check out. I'd like to suggest a framework that I've designed called [Regula](https://github.com/vivin/regula/). It does most of what you're asking. Validation rules (or constraints) can be attached directly on the element using the `data-constraints` attribute.
For example, you can do something like this:
```
<input type="text" name="something" data-constraints='@Required' />
```
You can even set things like the error message or labels:
```
<input type="text" name="something" data-constraints='@Required(label="something" message="{label} is required.")' />
```
Custom validation is also easy. You do need to define a validator in JavaScript *once*, but then you can use it after that:
```
regula.custom({
name: "MustBe42",
defaultMessage: "The answer must be equal to 42",
validator: function() {
return this.value == 42;
}
});
```
And then:
```
<input type="text" name="something" data-constraints='@MustBe42' />
```
Parameters are also supported:
```
regula.custom({
name: "MustBeSpecifiedNumber",
params: ["number"],
defaultMessage: "The answer must be equal to {number}",
validator: function(params) {
return this.value === params.number;
}
});
```
And then:
```
<input type="text" name="something" data-constraints='@MustBeSpecifiedNumber(number=10)' />
```
You asked about validation groups, and that can be done in Regula as well:
```
<input type="text" name="street" data-constraints='@Required(groups=[AddressGroup])' />
<input type="text" name="city" data-constraints='@Required(groups=[AddressGroup])' />
<input type="text" name="state" data-constraints='@Required(groups=[AddressGroup])' />
<input type="text" name="zip" data-constraints='@Required(groups=[AddressGroup])' />
```
Then you can validate with:
```
var constraintViolations = regula.validate({
groups: [regula.Group.AddressGroup] //AddressGroup property is automatically added
});
```
As far as HTML5 support and Asynchronous Validation, those features will be available in version 1.3 of Regula, which is currently in Alpha. I have a few minor features and documentation to update, but you should be able to checkout what is in on GitHub currently and it should work for you. HTML5 and Asynchronous Validation is mostly done.
With regard to HTML5 constraints, you can use the native attributes, or use Regula-wrapped versions which provide you more options like assignment to groups and custom messages. For example:
```
<input type="text" name="something" required="true" />
```
Will be recognized by Regula and validated. But you can also do this:
```
<input type="text" name="something" data-constraints='@HTML5Required(groups=[MyGroup], message="{label} is required!", label="something")' />
<input type="text" name="somethingElse" data-constraints='@HTML5Required(groups=[MyGroup], message="{label} is required!", label="somethingElse")' />
```
You can't normally do that with just the native HTML5 validation. An important thing to note however, is that the browser must support HTML5 validation for this to be able to work. Regula doesn't attempt to emulate HTML5 functionality since it involves more than just simple validation; it involves specific UI components as well. So for cross-browser compatibility you will need to use a polyfill or shim of some sort.
Asynchronous validation is also possible:
```
regula.custom({
name: "AsyncConstraint",
async: true,
defaultMessage: "{label} did not validate properly.",
validator: function(params, validator, callback) {
jQuery.ajax({
url: "myurl",
dataType: "json",
data: someData,
success: function(data) {
callback(data.successful)
}
});
}
});
```
Then you can annotate your element with:
```
<input type="text" name="something" data-constraints='@AsynchronousConstraint' />
```
and validate with:
```
//Simply calling validate will validate all constraints on all elements
regula.validate(function(constraintViolations) {
//do stuff with constraintViolations
});
```
It is also easy to do conditional validation and use pre-existing validators:
```
regula.custom({
name: "ConditionalRequired",
defaultMessage: "The answer must be equal to {number}",
validator: function(params, validator) {
var result = true;
if(some condition is true) {
result = validator.required(this, params, validator);
}
return result;
}
});
```
The `validator` object basically gives you access to the raw validator-functions for each of the constraints.
Regula has a bunch of other features as well, such as compound constraints (basically like in JSR-303).
Regula doesn't have any UI-related logic, like displaying error messages as such. It is *only* a validation engine and so it only does that. How you want to display the error messages is up to you.
Hopefully you find this useful! As I mentioned before, the current version is 1.3.0; it is in alpha and you can get it from [here](https://github.com/vivin/regula/). | Some points that you should consider:
1-not all browsers support html5.
2-you can't customize default error messages for required fields.
3-you could use the pattern attribute and validate with a regular expression. [External Resource](http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_pattern)
My suggestion: Take a look at a MVVM library such Backbone or Knockout.
<http://backbonejs.org/#Model-validate> |
46,133,699 | I am a cave man in terms of web ui - I like it all without npm/nodejs and other nice infrastructure. I want it all in text files like in old days: include/link stuff from/to a HTML page and it's done. Is such cave approach possible for semantic-ui+ReactJS combination, meaning to have no npm/nodes/other server code for my front end to work? | 2017/09/09 | [
"https://Stackoverflow.com/questions/46133699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1973207/"
]
| A way to do this is to use dataframes with pandas.
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.read_csv("D:\Programmes Python\Data\Data_csv.txt",sep=";") #Reads the csv
df.index = pd.to_datetime(df["DateTime"]) #Set the index of the dataframe to the DateTime column
del df["DateTime"] #The DateTime column is now useless
fig, ax = plt.subplots()
ax.plot(df.index,df["Issue_Type"])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m')) #This will only show the month number on the graph
```
This assumes that Issue1/2/3 are integers, I assumed they were as I didn't really understand what they were supposed to be.
**Edit:** This should do the trick then, it's not pretty and can probably be optimised, but it works well:
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.read_csv("D:\Programmes Python\Data\Data_csv.txt",sep=";")
df.index = pd.to_datetime(df["DateTime"])
del df["DateTime"]
list=[]
for Issue in df["Issue_Type"]:
list.append(int(Issue[5:]))
df["Issue_number"]=list
fig, ax = plt.subplots()
ax.plot(df.index,df["Issue_number"])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m'))
plt.show()
``` | The first thing you need to do is to parse the datetime fields as dates/times. Try using [`dateutil.parser`](http://dateutil.readthedocs.io/en/stable/parser.html) for that.
Next, you will need to count the number of issues of each type in each month. The naive way to do that would be to maintain lists of lists for each issue type, and just iterate through each column, see which month and which issue type it is, and then increment the appropriate counter.
When you have such a frequency count of issues, sorted by issue types, you can simply plot them against dates like this:
```
import matplotlib.pyplot as plt
import datetime as dt
dates = []
for year in range(starting_year, ending_year):
for month in range(1, 12):
dates.append(dt.datetime(year=year, month=month, day=1))
formatted_dates = dates.DateFormatter('%b') # Format dates to only show month names
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(issues[0], dates) # To plot just issues of type 1
ax.plot(issues[1], dates) # To plot just issues of type 2
ax.plot(issues[2], dates) # To plot just issues of type 3
ax.xaxis.set_major_formatter(formatted_dates) # Format X tick labels
plt.show()
plt.close()
``` |
46,133,699 | I am a cave man in terms of web ui - I like it all without npm/nodejs and other nice infrastructure. I want it all in text files like in old days: include/link stuff from/to a HTML page and it's done. Is such cave approach possible for semantic-ui+ReactJS combination, meaning to have no npm/nodes/other server code for my front end to work? | 2017/09/09 | [
"https://Stackoverflow.com/questions/46133699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1973207/"
]
| A way to do this is to use dataframes with pandas.
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.read_csv("D:\Programmes Python\Data\Data_csv.txt",sep=";") #Reads the csv
df.index = pd.to_datetime(df["DateTime"]) #Set the index of the dataframe to the DateTime column
del df["DateTime"] #The DateTime column is now useless
fig, ax = plt.subplots()
ax.plot(df.index,df["Issue_Type"])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m')) #This will only show the month number on the graph
```
This assumes that Issue1/2/3 are integers, I assumed they were as I didn't really understand what they were supposed to be.
**Edit:** This should do the trick then, it's not pretty and can probably be optimised, but it works well:
```
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.read_csv("D:\Programmes Python\Data\Data_csv.txt",sep=";")
df.index = pd.to_datetime(df["DateTime"])
del df["DateTime"]
list=[]
for Issue in df["Issue_Type"]:
list.append(int(Issue[5:]))
df["Issue_number"]=list
fig, ax = plt.subplots()
ax.plot(df.index,df["Issue_number"])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m'))
plt.show()
``` | honestly, I would just use R. [check this link out](http://www.ics.uci.edu/~jutts/110/InstallingRandRStudio.pdf) on downloading / setting up R & RStudio.
```
data <- read.csv(file="c:/yourdatafile.csv", header=TRUE, sep=",")
attach(data)
data$Month <- format(as.Date(data$DateTime), "%m")
plot(DateTime, Issue_Type)
``` |
231,507 | I am trying to build a fast cryptography algorithm. The algorithm works fine, but I am worried if there are any potential flaws that might make the algorithm vulnerable to any kind of attack. Here is my code.
`Encryptor.cpp`
---------------
```cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Encryptor
{
private:
unsigned char *key; //256 byte
unsigned char key16[16]; //16 byte
public:
Encryptor(unsigned char *k)
{
key = k;
for (int i = 0; i < 256; i += 16)
{
for (int j = 0; j < 16; j++)
{
if (i < 16)
{
key16[j] = key[j];
}
else
{
key16[j] = key16[j] ^ key[i + j];
}
}
}
srand(time(0));
}
string encrypt(string txt)
{
int totalRounds = (txt.size() / 256);
if (txt.size() % 256)
totalRounds++;
string cipher(totalRounds * 16 + txt.size(), 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? txt.size() % 256 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = random(1, 254);
cipher[cipherIndex] = key16[j] ^ randKey[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
cipher[cipherIndex] = key[j] ^ randKey[j % 16] ^ txt[txtIndex];
cipherIndex++;
txtIndex++;
}
}
return cipher;
}
string decrypt(string cipher)
{
int totalRounds = (cipher.size() / (256 + 16));
if (cipher.size() % (256 + 16))
totalRounds++;
string txt(cipher.size() - totalRounds * 16, 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? (cipher.size() % (256 + 16)) - 16 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = cipher[cipherIndex] ^ key16[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
txt[txtIndex] = cipher[cipherIndex] ^ key[j] ^ randKey[j % 16];
cipherIndex++;
txtIndex++;
}
}
return txt;
}
int random(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
};
```
`main.cpp`
----------
```cpp
#include <iostream>
#include "Encryptor.cpp"
using namespace std;
int main()
{
unsigned char key[256] = {239, 222, 80, 163, 48, 26, 182, 101, 123, 51, 145, 28, 106, 157, 105, 1, 51, 129, 222, 124, 80, 254, 118, 220, 208, 75, 225, 127, 180, 192, 125, 149, 22, 140, 218, 162, 89, 45, 237, 250, 71, 85, 245, 75, 59, 122, 146, 95, 68, 130, 33, 62, 124, 11, 203, 252, 72, 141, 140, 12, 241, 218, 89, 147, 58, 124, 209, 177, 71, 254, 201, 3, 166, 10, 179, 89, 194, 72, 150, 32, 97, 197, 119, 50, 185, 11, 202, 164, 175, 115, 239, 113, 146, 7, 84, 62, 49, 124, 25, 108, 111, 107, 250, 168, 75, 137, 87, 219, 115, 242, 237, 23, 79, 53, 95, 45, 180, 59, 243, 138, 37, 219, 174, 13, 188, 19, 62, 104, 176, 154, 183, 242, 177, 19, 215, 42, 197, 88, 149, 246, 40, 54, 184, 31, 187, 9, 115, 152, 128, 165, 116, 105, 179, 242, 145, 195, 250, 153, 139, 247, 96, 51, 225, 237, 86, 97, 97, 196, 146, 67, 73, 88, 30, 135, 192, 29, 64, 189, 123, 95, 152, 22, 31, 5, 71, 38, 136, 6, 68, 247, 93, 206, 200, 229, 243, 140, 11, 137, 60, 197, 22, 92, 118, 44, 3, 47, 121, 249, 88, 27, 101, 242, 222, 36, 112, 45, 188, 46, 170, 201, 244, 90, 115, 224, 88, 157, 109, 136, 228, 134, 186, 124, 154, 3, 78, 49, 225, 57, 249, 172, 103, 44, 74, 84, 158, 48, 139, 185, 207, 9, 58, 143, 211, 177, 62, 32};
Encryptor e(key);
for (int i = 0; i < 100; i++)
{
string c = e.encrypt("my secret");
cout << "cipher: " << c << endl;
cout << "After decryption: " << e.decrypt(c) << endl;
}
return 0;
}
```
---
Algorithm:
==========
* user provides 256 byte key where the value of any byte can't be 0 or 255
* 16 byte internal key is generated from the user provided key
encryption:
===========
* plain text is processed in 256-byte blocks (same as the key length) except the last one which depends on the length of the plain text.
* 16-byte random key is generated for every block where the value of each byte is between 1,254.
* for each plain text block additional 16 byte is added in the beginning of cipher text block that increases the cipher text block size to 256+16 byte
* the first 16 bytes of each cipher text block contains the XOR result of the block random key and the internal key
* the 17th byte of the cipher text = key[first byte] xor random key[first byte] xor plain text block[first byte]
* the 18th byte of the cipher text = key[second byte] xor random key[second byte] xor plain text block[second byte]
....
* when the random key reaches its last byte, as it is shorter than the block size, it repeats from the beginning.
The decryption process is reverse of the encryption process. | 2019/10/30 | [
"https://codereview.stackexchange.com/questions/231507",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/-1/"
]
| Here are a number of things you could do to improve the code.
Separate interface from implementation
--------------------------------------
The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate `.cpp` file. The reason is that you might have multiple source files including the `.h` file but only one instance of the corresponding `.cpp` file. In other words, split your existing `Encryptor.cpp` file into a `.h` file and a `.cpp` file.
Use C++-style includes
----------------------
Instead of including `stdio.h` you should instead use `#include <cstdio>`. The difference is in namespaces as you can [read about in this question](http://stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace).
Don't abuse `using namespace std`
---------------------------------
Putting `using namespace std` at the top of every program is [a bad habit](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) that you'd do well to avoid. Know when to use it and when not to (as when writing include headers).
Make sure you have all required `#include`s
-------------------------------------------
The code uses `std::string` but doesn't `#include <string>`. Also, carefully consider which `#include`s are part of the interface (and belong in the `.h` file) and which are part of the implementation per the earlier advice.
Don't use unnecessary `#include`s
---------------------------------
The code has `#include <stdio.h>` but nothing from that include file is actually in the code. For that reason, that `#include` should be eliminated.
Don't use `std::endl` if you don't really need it
-------------------------------------------------
The difference betweeen `std::endl` and `'\n'` is that `'\n'` just emits a newline character, while `std::endl` actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to *only* use `std::endl` when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using `std::endl` when `'\n'` will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Use a better random number generator
------------------------------------
You are currently using
```
(rand() % (upper - lower + 1)) + lower;
```
There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution. Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result. On my machine, there's a slight but measurable bias toward 0 with that. See [this answer](http://stackoverflow.com/questions/2999075/generate-a-random-number-within-range/2999130#2999130) for details.
Study cryptography
------------------
If you're interested in this sort of thing, it would be good for you to study cryptography. One book you might like is *Modern Cryptanalysis* by Christopher Swenson. It's quite understandable and may help you answer your own questions. Here's a brief analysis of your scheme:
First, some nomenclature. I'm going to be referring to *blocks* (16-byte chunks) hereafter. Let \$m\$ be a single block message we're encrypting, and the 256-byte key is \$k[0] \cdots k[15]\$. Let's also say the random key is \$r\$ and your `key16` is \$b\$. Using standard notation, \$\oplus\$ is the block-sized exclusive or operator. Your scheme does this:
$$ b = k[0] \oplus k[1] \oplus \cdots \oplus k[14] \oplus k[15] $$
The generated message has two parts which I'll call \$p\$ and \$q\$:
$$ p = b \oplus r $$
$$ q = k[0] \oplus r \oplus m $$
If we combine those into a new quantity \$m'\$, we get this:
$$ m' = p \oplus q = b \oplus r \oplus k[0] \oplus r \oplus m $$
$$ m' = p \oplus q = b \oplus k[0] \oplus m $$
So we can easily already see that the random key has no useful effect. Further, we can say that \$b' = b \oplus k[0]\$, so from the definition of \$b\$ we get:
$$ b' = k[1] \oplus k[2] \oplus \cdots \oplus k[14] \oplus k[15] $$
And so \$m' = b' \oplus m\$ and we can now see that the first block of the key also doesn't need to be derived. All that we need to get is \$b'\$ and we can decode any message encrypted with that key. If we know or can guess that the encrypted text is ASCII, for example, it's not at all hard to guess at the top few bits of each of the bytes of \$b'\$ and in essence, your scheme is no better (and no different) than choosing a randomly generated single key and exclusive-or-ing it with the message. That's a very, very weak scheme that even amateur cryptographers like me would have little difficulty breaking. | File naming
===========
It's a long-standing convention in C++, as in C, that files meant to be included as part of another translation unit (headers) are given names with a `.h` suffix. It's a good idea to follow such conventions, as it makes the code easier for everyone to understand.
Includes
========
Don't use the C compatibility headers in new code; use the C++ versions, which declare their identifiers in the `std` namespace, whence they can be used unambiguously:
```
#include <cstdio>
#include <cstdlib>
#include <ctime>
```
`using` directive
=================
Don't bring the whole of `std` into the global namespace - especially not in a header file, which will inflict the harm onto the entire translation unit. Just use the minimum set of identifiers you need into the smallest reasonable scope, and fully qualify names where reasonable.
Use initializers
================
Instead of writing `key = k;` in the body of the constructor, it's much better practice to use an initializer for this. That makes it easier for the compiler to determine whether the class is properly initialized:
```
Encryptor(unsigned char *k)
: key{k}
```
Mark conversion constructor as explicit
=======================================
We don't want `Encryptor` to be considered as an implicit promotion from `unsigned char*`, so it should be marked `explicit`.
Avoid mutable non-owning pointers
=================================
We never modify the values in `k[]`, so don't store a mutable pointer:
```
class Encryptor
{
unsigned char const *key;
public:
explicit Encryptor(unsigned char const *k)
: key{k}
{
```
Validate arguments
==================
There's a documented constraint that `k[n]` is not 0 or 255, but this is never checked. The constructor should validate that constraint and throw `std::invalid_argument` if it's violated. However, there's no justification for that constraint - I see no reason not to accept all values from 0 to `UCHAR_MAX`.
Use the full keyspace
=====================
The `key16` array contains only values from 1 to 254. We actually need it to be uniformly distributed across the full range 0 to `UCHAR_MAX`.
Initialise the random seed only once
====================================
`std::srand()` doesn't give very good randomness if reseeded every time we create a new `Encryptor` - it's best called exactly once per process (generally in `main()`, where we can't accidentally link in another call).
Don't pass `std::string` by value
=================================
We can pass inputs by reference to `const`:
```
std::string encrypt(const std::string& txt);
std::string decrypt(const std::string& cipher);
```
Don't pass mutable `this` unnecessarily
=======================================
`encrypt()` and `decrypt()` require only read access; `random()` doesn't use any members at all:
```
std::string encrypt(const std::string& txt) const;
std::string decrypt(const std::string& cipher) const;
private:
static int random(int lower, int upper);
```
Don't mix signed and unsigned arithmetic
========================================
Strings are measured and indexed using `std::size_t`, which is unsigned, so don't access them using `int`, which is signed and may be too small.
Scrub key data after use
========================
Don't leave secrets in memory unnecessarily, as they could be exposed to an attacker (e.g. in core dumps).
```
~Encryptor()
{
std::fill(std::begin(key16), std::end(key16), 0u);
}
```
Improve the encryption
======================
The encryption algorithm is extremely weak, as some elementary cryptanalysis would reveal. Avoid any encryption that isn't based on proven mathematical difficulty.
The only positive thing I could find is that the code doesn't seem to have any obvious data dependencies in its timing or power consumption.
Ciphertexts are more than 6% larger than plaintexts, making this algorithm inefficient for storage or transmission of secret data. |
231,507 | I am trying to build a fast cryptography algorithm. The algorithm works fine, but I am worried if there are any potential flaws that might make the algorithm vulnerable to any kind of attack. Here is my code.
`Encryptor.cpp`
---------------
```cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Encryptor
{
private:
unsigned char *key; //256 byte
unsigned char key16[16]; //16 byte
public:
Encryptor(unsigned char *k)
{
key = k;
for (int i = 0; i < 256; i += 16)
{
for (int j = 0; j < 16; j++)
{
if (i < 16)
{
key16[j] = key[j];
}
else
{
key16[j] = key16[j] ^ key[i + j];
}
}
}
srand(time(0));
}
string encrypt(string txt)
{
int totalRounds = (txt.size() / 256);
if (txt.size() % 256)
totalRounds++;
string cipher(totalRounds * 16 + txt.size(), 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? txt.size() % 256 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = random(1, 254);
cipher[cipherIndex] = key16[j] ^ randKey[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
cipher[cipherIndex] = key[j] ^ randKey[j % 16] ^ txt[txtIndex];
cipherIndex++;
txtIndex++;
}
}
return cipher;
}
string decrypt(string cipher)
{
int totalRounds = (cipher.size() / (256 + 16));
if (cipher.size() % (256 + 16))
totalRounds++;
string txt(cipher.size() - totalRounds * 16, 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? (cipher.size() % (256 + 16)) - 16 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = cipher[cipherIndex] ^ key16[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
txt[txtIndex] = cipher[cipherIndex] ^ key[j] ^ randKey[j % 16];
cipherIndex++;
txtIndex++;
}
}
return txt;
}
int random(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
};
```
`main.cpp`
----------
```cpp
#include <iostream>
#include "Encryptor.cpp"
using namespace std;
int main()
{
unsigned char key[256] = {239, 222, 80, 163, 48, 26, 182, 101, 123, 51, 145, 28, 106, 157, 105, 1, 51, 129, 222, 124, 80, 254, 118, 220, 208, 75, 225, 127, 180, 192, 125, 149, 22, 140, 218, 162, 89, 45, 237, 250, 71, 85, 245, 75, 59, 122, 146, 95, 68, 130, 33, 62, 124, 11, 203, 252, 72, 141, 140, 12, 241, 218, 89, 147, 58, 124, 209, 177, 71, 254, 201, 3, 166, 10, 179, 89, 194, 72, 150, 32, 97, 197, 119, 50, 185, 11, 202, 164, 175, 115, 239, 113, 146, 7, 84, 62, 49, 124, 25, 108, 111, 107, 250, 168, 75, 137, 87, 219, 115, 242, 237, 23, 79, 53, 95, 45, 180, 59, 243, 138, 37, 219, 174, 13, 188, 19, 62, 104, 176, 154, 183, 242, 177, 19, 215, 42, 197, 88, 149, 246, 40, 54, 184, 31, 187, 9, 115, 152, 128, 165, 116, 105, 179, 242, 145, 195, 250, 153, 139, 247, 96, 51, 225, 237, 86, 97, 97, 196, 146, 67, 73, 88, 30, 135, 192, 29, 64, 189, 123, 95, 152, 22, 31, 5, 71, 38, 136, 6, 68, 247, 93, 206, 200, 229, 243, 140, 11, 137, 60, 197, 22, 92, 118, 44, 3, 47, 121, 249, 88, 27, 101, 242, 222, 36, 112, 45, 188, 46, 170, 201, 244, 90, 115, 224, 88, 157, 109, 136, 228, 134, 186, 124, 154, 3, 78, 49, 225, 57, 249, 172, 103, 44, 74, 84, 158, 48, 139, 185, 207, 9, 58, 143, 211, 177, 62, 32};
Encryptor e(key);
for (int i = 0; i < 100; i++)
{
string c = e.encrypt("my secret");
cout << "cipher: " << c << endl;
cout << "After decryption: " << e.decrypt(c) << endl;
}
return 0;
}
```
---
Algorithm:
==========
* user provides 256 byte key where the value of any byte can't be 0 or 255
* 16 byte internal key is generated from the user provided key
encryption:
===========
* plain text is processed in 256-byte blocks (same as the key length) except the last one which depends on the length of the plain text.
* 16-byte random key is generated for every block where the value of each byte is between 1,254.
* for each plain text block additional 16 byte is added in the beginning of cipher text block that increases the cipher text block size to 256+16 byte
* the first 16 bytes of each cipher text block contains the XOR result of the block random key and the internal key
* the 17th byte of the cipher text = key[first byte] xor random key[first byte] xor plain text block[first byte]
* the 18th byte of the cipher text = key[second byte] xor random key[second byte] xor plain text block[second byte]
....
* when the random key reaches its last byte, as it is shorter than the block size, it repeats from the beginning.
The decryption process is reverse of the encryption process. | 2019/10/30 | [
"https://codereview.stackexchange.com/questions/231507",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/-1/"
]
| Here are a number of things you could do to improve the code.
Separate interface from implementation
--------------------------------------
The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate `.cpp` file. The reason is that you might have multiple source files including the `.h` file but only one instance of the corresponding `.cpp` file. In other words, split your existing `Encryptor.cpp` file into a `.h` file and a `.cpp` file.
Use C++-style includes
----------------------
Instead of including `stdio.h` you should instead use `#include <cstdio>`. The difference is in namespaces as you can [read about in this question](http://stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace).
Don't abuse `using namespace std`
---------------------------------
Putting `using namespace std` at the top of every program is [a bad habit](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) that you'd do well to avoid. Know when to use it and when not to (as when writing include headers).
Make sure you have all required `#include`s
-------------------------------------------
The code uses `std::string` but doesn't `#include <string>`. Also, carefully consider which `#include`s are part of the interface (and belong in the `.h` file) and which are part of the implementation per the earlier advice.
Don't use unnecessary `#include`s
---------------------------------
The code has `#include <stdio.h>` but nothing from that include file is actually in the code. For that reason, that `#include` should be eliminated.
Don't use `std::endl` if you don't really need it
-------------------------------------------------
The difference betweeen `std::endl` and `'\n'` is that `'\n'` just emits a newline character, while `std::endl` actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to *only* use `std::endl` when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using `std::endl` when `'\n'` will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Use a better random number generator
------------------------------------
You are currently using
```
(rand() % (upper - lower + 1)) + lower;
```
There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution. Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result. On my machine, there's a slight but measurable bias toward 0 with that. See [this answer](http://stackoverflow.com/questions/2999075/generate-a-random-number-within-range/2999130#2999130) for details.
Study cryptography
------------------
If you're interested in this sort of thing, it would be good for you to study cryptography. One book you might like is *Modern Cryptanalysis* by Christopher Swenson. It's quite understandable and may help you answer your own questions. Here's a brief analysis of your scheme:
First, some nomenclature. I'm going to be referring to *blocks* (16-byte chunks) hereafter. Let \$m\$ be a single block message we're encrypting, and the 256-byte key is \$k[0] \cdots k[15]\$. Let's also say the random key is \$r\$ and your `key16` is \$b\$. Using standard notation, \$\oplus\$ is the block-sized exclusive or operator. Your scheme does this:
$$ b = k[0] \oplus k[1] \oplus \cdots \oplus k[14] \oplus k[15] $$
The generated message has two parts which I'll call \$p\$ and \$q\$:
$$ p = b \oplus r $$
$$ q = k[0] \oplus r \oplus m $$
If we combine those into a new quantity \$m'\$, we get this:
$$ m' = p \oplus q = b \oplus r \oplus k[0] \oplus r \oplus m $$
$$ m' = p \oplus q = b \oplus k[0] \oplus m $$
So we can easily already see that the random key has no useful effect. Further, we can say that \$b' = b \oplus k[0]\$, so from the definition of \$b\$ we get:
$$ b' = k[1] \oplus k[2] \oplus \cdots \oplus k[14] \oplus k[15] $$
And so \$m' = b' \oplus m\$ and we can now see that the first block of the key also doesn't need to be derived. All that we need to get is \$b'\$ and we can decode any message encrypted with that key. If we know or can guess that the encrypted text is ASCII, for example, it's not at all hard to guess at the top few bits of each of the bytes of \$b'\$ and in essence, your scheme is no better (and no different) than choosing a randomly generated single key and exclusive-or-ing it with the message. That's a very, very weak scheme that even amateur cryptographers like me would have little difficulty breaking. | Please do not roll your own encryption outside of an academic context.
If you would like a fast algorithm that can be easily implemented in C/C++ take a look at [ChaCha or Salsa](https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant). Runs great on most general purpose CPUs and has been verified by the cryptographic community at large. I've seen it outpace AES accelerators in constrained devices. |
231,507 | I am trying to build a fast cryptography algorithm. The algorithm works fine, but I am worried if there are any potential flaws that might make the algorithm vulnerable to any kind of attack. Here is my code.
`Encryptor.cpp`
---------------
```cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Encryptor
{
private:
unsigned char *key; //256 byte
unsigned char key16[16]; //16 byte
public:
Encryptor(unsigned char *k)
{
key = k;
for (int i = 0; i < 256; i += 16)
{
for (int j = 0; j < 16; j++)
{
if (i < 16)
{
key16[j] = key[j];
}
else
{
key16[j] = key16[j] ^ key[i + j];
}
}
}
srand(time(0));
}
string encrypt(string txt)
{
int totalRounds = (txt.size() / 256);
if (txt.size() % 256)
totalRounds++;
string cipher(totalRounds * 16 + txt.size(), 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? txt.size() % 256 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = random(1, 254);
cipher[cipherIndex] = key16[j] ^ randKey[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
cipher[cipherIndex] = key[j] ^ randKey[j % 16] ^ txt[txtIndex];
cipherIndex++;
txtIndex++;
}
}
return cipher;
}
string decrypt(string cipher)
{
int totalRounds = (cipher.size() / (256 + 16));
if (cipher.size() % (256 + 16))
totalRounds++;
string txt(cipher.size() - totalRounds * 16, 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? (cipher.size() % (256 + 16)) - 16 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = cipher[cipherIndex] ^ key16[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
txt[txtIndex] = cipher[cipherIndex] ^ key[j] ^ randKey[j % 16];
cipherIndex++;
txtIndex++;
}
}
return txt;
}
int random(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
};
```
`main.cpp`
----------
```cpp
#include <iostream>
#include "Encryptor.cpp"
using namespace std;
int main()
{
unsigned char key[256] = {239, 222, 80, 163, 48, 26, 182, 101, 123, 51, 145, 28, 106, 157, 105, 1, 51, 129, 222, 124, 80, 254, 118, 220, 208, 75, 225, 127, 180, 192, 125, 149, 22, 140, 218, 162, 89, 45, 237, 250, 71, 85, 245, 75, 59, 122, 146, 95, 68, 130, 33, 62, 124, 11, 203, 252, 72, 141, 140, 12, 241, 218, 89, 147, 58, 124, 209, 177, 71, 254, 201, 3, 166, 10, 179, 89, 194, 72, 150, 32, 97, 197, 119, 50, 185, 11, 202, 164, 175, 115, 239, 113, 146, 7, 84, 62, 49, 124, 25, 108, 111, 107, 250, 168, 75, 137, 87, 219, 115, 242, 237, 23, 79, 53, 95, 45, 180, 59, 243, 138, 37, 219, 174, 13, 188, 19, 62, 104, 176, 154, 183, 242, 177, 19, 215, 42, 197, 88, 149, 246, 40, 54, 184, 31, 187, 9, 115, 152, 128, 165, 116, 105, 179, 242, 145, 195, 250, 153, 139, 247, 96, 51, 225, 237, 86, 97, 97, 196, 146, 67, 73, 88, 30, 135, 192, 29, 64, 189, 123, 95, 152, 22, 31, 5, 71, 38, 136, 6, 68, 247, 93, 206, 200, 229, 243, 140, 11, 137, 60, 197, 22, 92, 118, 44, 3, 47, 121, 249, 88, 27, 101, 242, 222, 36, 112, 45, 188, 46, 170, 201, 244, 90, 115, 224, 88, 157, 109, 136, 228, 134, 186, 124, 154, 3, 78, 49, 225, 57, 249, 172, 103, 44, 74, 84, 158, 48, 139, 185, 207, 9, 58, 143, 211, 177, 62, 32};
Encryptor e(key);
for (int i = 0; i < 100; i++)
{
string c = e.encrypt("my secret");
cout << "cipher: " << c << endl;
cout << "After decryption: " << e.decrypt(c) << endl;
}
return 0;
}
```
---
Algorithm:
==========
* user provides 256 byte key where the value of any byte can't be 0 or 255
* 16 byte internal key is generated from the user provided key
encryption:
===========
* plain text is processed in 256-byte blocks (same as the key length) except the last one which depends on the length of the plain text.
* 16-byte random key is generated for every block where the value of each byte is between 1,254.
* for each plain text block additional 16 byte is added in the beginning of cipher text block that increases the cipher text block size to 256+16 byte
* the first 16 bytes of each cipher text block contains the XOR result of the block random key and the internal key
* the 17th byte of the cipher text = key[first byte] xor random key[first byte] xor plain text block[first byte]
* the 18th byte of the cipher text = key[second byte] xor random key[second byte] xor plain text block[second byte]
....
* when the random key reaches its last byte, as it is shorter than the block size, it repeats from the beginning.
The decryption process is reverse of the encryption process. | 2019/10/30 | [
"https://codereview.stackexchange.com/questions/231507",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/-1/"
]
| Here are a number of things you could do to improve the code.
Separate interface from implementation
--------------------------------------
The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate `.cpp` file. The reason is that you might have multiple source files including the `.h` file but only one instance of the corresponding `.cpp` file. In other words, split your existing `Encryptor.cpp` file into a `.h` file and a `.cpp` file.
Use C++-style includes
----------------------
Instead of including `stdio.h` you should instead use `#include <cstdio>`. The difference is in namespaces as you can [read about in this question](http://stackoverflow.com/questions/10460250/cstdio-stdio-h-namespace).
Don't abuse `using namespace std`
---------------------------------
Putting `using namespace std` at the top of every program is [a bad habit](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) that you'd do well to avoid. Know when to use it and when not to (as when writing include headers).
Make sure you have all required `#include`s
-------------------------------------------
The code uses `std::string` but doesn't `#include <string>`. Also, carefully consider which `#include`s are part of the interface (and belong in the `.h` file) and which are part of the implementation per the earlier advice.
Don't use unnecessary `#include`s
---------------------------------
The code has `#include <stdio.h>` but nothing from that include file is actually in the code. For that reason, that `#include` should be eliminated.
Don't use `std::endl` if you don't really need it
-------------------------------------------------
The difference betweeen `std::endl` and `'\n'` is that `'\n'` just emits a newline character, while `std::endl` actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to *only* use `std::endl` when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using `std::endl` when `'\n'` will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
Use a better random number generator
------------------------------------
You are currently using
```
(rand() % (upper - lower + 1)) + lower;
```
There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution. Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result. On my machine, there's a slight but measurable bias toward 0 with that. See [this answer](http://stackoverflow.com/questions/2999075/generate-a-random-number-within-range/2999130#2999130) for details.
Study cryptography
------------------
If you're interested in this sort of thing, it would be good for you to study cryptography. One book you might like is *Modern Cryptanalysis* by Christopher Swenson. It's quite understandable and may help you answer your own questions. Here's a brief analysis of your scheme:
First, some nomenclature. I'm going to be referring to *blocks* (16-byte chunks) hereafter. Let \$m\$ be a single block message we're encrypting, and the 256-byte key is \$k[0] \cdots k[15]\$. Let's also say the random key is \$r\$ and your `key16` is \$b\$. Using standard notation, \$\oplus\$ is the block-sized exclusive or operator. Your scheme does this:
$$ b = k[0] \oplus k[1] \oplus \cdots \oplus k[14] \oplus k[15] $$
The generated message has two parts which I'll call \$p\$ and \$q\$:
$$ p = b \oplus r $$
$$ q = k[0] \oplus r \oplus m $$
If we combine those into a new quantity \$m'\$, we get this:
$$ m' = p \oplus q = b \oplus r \oplus k[0] \oplus r \oplus m $$
$$ m' = p \oplus q = b \oplus k[0] \oplus m $$
So we can easily already see that the random key has no useful effect. Further, we can say that \$b' = b \oplus k[0]\$, so from the definition of \$b\$ we get:
$$ b' = k[1] \oplus k[2] \oplus \cdots \oplus k[14] \oplus k[15] $$
And so \$m' = b' \oplus m\$ and we can now see that the first block of the key also doesn't need to be derived. All that we need to get is \$b'\$ and we can decode any message encrypted with that key. If we know or can guess that the encrypted text is ASCII, for example, it's not at all hard to guess at the top few bits of each of the bytes of \$b'\$ and in essence, your scheme is no better (and no different) than choosing a randomly generated single key and exclusive-or-ing it with the message. That's a very, very weak scheme that even amateur cryptographers like me would have little difficulty breaking. | Regarding the cryptographic algorithm only:
Important observations
======================
This is equivalent to an XOR cipher with a repeating 256-byte key. The key16 stuff adds no security. The randKey stuff adds no security. The following is working decryption code for one round (I'll use your terminology), if you know the key:
```
unsigned char key16[16] = {0};
for(int k = 0; k < 256; k++) key16[k % 16] ^= key[k];
for(int k = 0; k < 256; k++) key[k] ^= key16[k % 16];
// everything above this line adds no security,
// because we could just take the modified key HERE
// and pretend that's the real key.
// Then we wouldn't need key16.
string decrypted = encrypted.substr(16);
for(int i = 0; i < decrypted.length(); i++) {
// This line adds no security, because the attacker
// knows what encrypted[i % 16] is.
decrypted[i] ^= encrypted[i % 16];
// This is the only part where we need to know the key.
// It's a standard XOR cipher.
decrypted[i] ^= key[i % 256];
}
std::cout << decrypted << std::endl;
```
This does the same as your decryption code (try it and see), but I've rearranged it for easier analysis.
*In the rest of this answer, I will ignore key16 and randKey because they are easily reversed (see code above) and concentrate on the XOR cipher.*
So with that in mind, what are the problems?
It is vulnerable to statistical analysis, to get key16
======================================================
The bytes in randKey are never 0 or 255. This means that after you XOR them with key16, they'll never be equal to key16 or key16^255. If the attacker sees a lot of rounds, this means the attacker can guess the bytes in key16, by narrowing each byte down to 2 possibilities.
If you did discover key16, then you can combine it with 240 key bytes to work out the other 16. So it's not *much* of a breakthrough.
It might be vulnerable to statistical analysis, to get the message
==================================================================
Because the key bytes are never 0 or 255, once you have recovered key16 (see above), you can XOR that with the ciphertext (along with the randKey^key16) and then you'll never get bytes equal to the original message, or the message XOR 255. If you had enough copies of the same message encrypted with different keys, you could figure out which bytes you *aren't* getting, which is the message.
To use this attack, you'd need to have a very long message (so that it contains enough rounds to figure out key16 for each key) and you'd need to see it encrypted with a lot of different keys (so that you can figure out the message).
It is vulnerable to [known plaintext attacks](https://en.wikipedia.org/wiki/Known-plaintext_attack).
====================================================================================================
If you know the plaintext (decrypted text), or part of it, you can XOR the plaintext with the ciphertext (encrypted text), and you get the key.
It is vulnerable to [chosen ciphertext attacks](https://en.wikipedia.org/wiki/Chosen-ciphertext_attack)
=======================================================================================================
If I can give you some ciphertext (encrypted text) and get you to decrypt it, and show me the plaintext (decrypted text), then I can work out the key by XORing them.
In particular, if I just give you a bunch of 0 bytes, and ask you to decrypt them, the plaintext will be the key XOR key16. That's really lame.
It is vulnerable to [frequency analysis](https://en.wikipedia.org/wiki/Frequency_analysis)
==========================================================================================
The most common letter in English is 'e' (ASCII 0x65) or possibly a space (ASCII 0x20). If you see that 0x8F as the most common first byte of a round, you can guess that the first byte of the key XOR key16 is 0xEA (which would make them 'e') or 0xAF (which would make them spaces). Same for the second byte, and the third byte, and all the other bytes. For this to work, the message has to be quite long.
It is vulnerable to XORing two messages
=======================================
Once you undo the random keys, you can XOR the ciphertext for two messages (or blocks) and it will be the same as XORing the plaintext for those two messages (or blocks). This can give you lots of information about the plaintext, but it's very specific to the situation. I'm not sure if this attack has a standard name. |
231,507 | I am trying to build a fast cryptography algorithm. The algorithm works fine, but I am worried if there are any potential flaws that might make the algorithm vulnerable to any kind of attack. Here is my code.
`Encryptor.cpp`
---------------
```cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Encryptor
{
private:
unsigned char *key; //256 byte
unsigned char key16[16]; //16 byte
public:
Encryptor(unsigned char *k)
{
key = k;
for (int i = 0; i < 256; i += 16)
{
for (int j = 0; j < 16; j++)
{
if (i < 16)
{
key16[j] = key[j];
}
else
{
key16[j] = key16[j] ^ key[i + j];
}
}
}
srand(time(0));
}
string encrypt(string txt)
{
int totalRounds = (txt.size() / 256);
if (txt.size() % 256)
totalRounds++;
string cipher(totalRounds * 16 + txt.size(), 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? txt.size() % 256 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = random(1, 254);
cipher[cipherIndex] = key16[j] ^ randKey[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
cipher[cipherIndex] = key[j] ^ randKey[j % 16] ^ txt[txtIndex];
cipherIndex++;
txtIndex++;
}
}
return cipher;
}
string decrypt(string cipher)
{
int totalRounds = (cipher.size() / (256 + 16));
if (cipher.size() % (256 + 16))
totalRounds++;
string txt(cipher.size() - totalRounds * 16, 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? (cipher.size() % (256 + 16)) - 16 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = cipher[cipherIndex] ^ key16[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
txt[txtIndex] = cipher[cipherIndex] ^ key[j] ^ randKey[j % 16];
cipherIndex++;
txtIndex++;
}
}
return txt;
}
int random(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
};
```
`main.cpp`
----------
```cpp
#include <iostream>
#include "Encryptor.cpp"
using namespace std;
int main()
{
unsigned char key[256] = {239, 222, 80, 163, 48, 26, 182, 101, 123, 51, 145, 28, 106, 157, 105, 1, 51, 129, 222, 124, 80, 254, 118, 220, 208, 75, 225, 127, 180, 192, 125, 149, 22, 140, 218, 162, 89, 45, 237, 250, 71, 85, 245, 75, 59, 122, 146, 95, 68, 130, 33, 62, 124, 11, 203, 252, 72, 141, 140, 12, 241, 218, 89, 147, 58, 124, 209, 177, 71, 254, 201, 3, 166, 10, 179, 89, 194, 72, 150, 32, 97, 197, 119, 50, 185, 11, 202, 164, 175, 115, 239, 113, 146, 7, 84, 62, 49, 124, 25, 108, 111, 107, 250, 168, 75, 137, 87, 219, 115, 242, 237, 23, 79, 53, 95, 45, 180, 59, 243, 138, 37, 219, 174, 13, 188, 19, 62, 104, 176, 154, 183, 242, 177, 19, 215, 42, 197, 88, 149, 246, 40, 54, 184, 31, 187, 9, 115, 152, 128, 165, 116, 105, 179, 242, 145, 195, 250, 153, 139, 247, 96, 51, 225, 237, 86, 97, 97, 196, 146, 67, 73, 88, 30, 135, 192, 29, 64, 189, 123, 95, 152, 22, 31, 5, 71, 38, 136, 6, 68, 247, 93, 206, 200, 229, 243, 140, 11, 137, 60, 197, 22, 92, 118, 44, 3, 47, 121, 249, 88, 27, 101, 242, 222, 36, 112, 45, 188, 46, 170, 201, 244, 90, 115, 224, 88, 157, 109, 136, 228, 134, 186, 124, 154, 3, 78, 49, 225, 57, 249, 172, 103, 44, 74, 84, 158, 48, 139, 185, 207, 9, 58, 143, 211, 177, 62, 32};
Encryptor e(key);
for (int i = 0; i < 100; i++)
{
string c = e.encrypt("my secret");
cout << "cipher: " << c << endl;
cout << "After decryption: " << e.decrypt(c) << endl;
}
return 0;
}
```
---
Algorithm:
==========
* user provides 256 byte key where the value of any byte can't be 0 or 255
* 16 byte internal key is generated from the user provided key
encryption:
===========
* plain text is processed in 256-byte blocks (same as the key length) except the last one which depends on the length of the plain text.
* 16-byte random key is generated for every block where the value of each byte is between 1,254.
* for each plain text block additional 16 byte is added in the beginning of cipher text block that increases the cipher text block size to 256+16 byte
* the first 16 bytes of each cipher text block contains the XOR result of the block random key and the internal key
* the 17th byte of the cipher text = key[first byte] xor random key[first byte] xor plain text block[first byte]
* the 18th byte of the cipher text = key[second byte] xor random key[second byte] xor plain text block[second byte]
....
* when the random key reaches its last byte, as it is shorter than the block size, it repeats from the beginning.
The decryption process is reverse of the encryption process. | 2019/10/30 | [
"https://codereview.stackexchange.com/questions/231507",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/-1/"
]
| Please do not roll your own encryption outside of an academic context.
If you would like a fast algorithm that can be easily implemented in C/C++ take a look at [ChaCha or Salsa](https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant). Runs great on most general purpose CPUs and has been verified by the cryptographic community at large. I've seen it outpace AES accelerators in constrained devices. | File naming
===========
It's a long-standing convention in C++, as in C, that files meant to be included as part of another translation unit (headers) are given names with a `.h` suffix. It's a good idea to follow such conventions, as it makes the code easier for everyone to understand.
Includes
========
Don't use the C compatibility headers in new code; use the C++ versions, which declare their identifiers in the `std` namespace, whence they can be used unambiguously:
```
#include <cstdio>
#include <cstdlib>
#include <ctime>
```
`using` directive
=================
Don't bring the whole of `std` into the global namespace - especially not in a header file, which will inflict the harm onto the entire translation unit. Just use the minimum set of identifiers you need into the smallest reasonable scope, and fully qualify names where reasonable.
Use initializers
================
Instead of writing `key = k;` in the body of the constructor, it's much better practice to use an initializer for this. That makes it easier for the compiler to determine whether the class is properly initialized:
```
Encryptor(unsigned char *k)
: key{k}
```
Mark conversion constructor as explicit
=======================================
We don't want `Encryptor` to be considered as an implicit promotion from `unsigned char*`, so it should be marked `explicit`.
Avoid mutable non-owning pointers
=================================
We never modify the values in `k[]`, so don't store a mutable pointer:
```
class Encryptor
{
unsigned char const *key;
public:
explicit Encryptor(unsigned char const *k)
: key{k}
{
```
Validate arguments
==================
There's a documented constraint that `k[n]` is not 0 or 255, but this is never checked. The constructor should validate that constraint and throw `std::invalid_argument` if it's violated. However, there's no justification for that constraint - I see no reason not to accept all values from 0 to `UCHAR_MAX`.
Use the full keyspace
=====================
The `key16` array contains only values from 1 to 254. We actually need it to be uniformly distributed across the full range 0 to `UCHAR_MAX`.
Initialise the random seed only once
====================================
`std::srand()` doesn't give very good randomness if reseeded every time we create a new `Encryptor` - it's best called exactly once per process (generally in `main()`, where we can't accidentally link in another call).
Don't pass `std::string` by value
=================================
We can pass inputs by reference to `const`:
```
std::string encrypt(const std::string& txt);
std::string decrypt(const std::string& cipher);
```
Don't pass mutable `this` unnecessarily
=======================================
`encrypt()` and `decrypt()` require only read access; `random()` doesn't use any members at all:
```
std::string encrypt(const std::string& txt) const;
std::string decrypt(const std::string& cipher) const;
private:
static int random(int lower, int upper);
```
Don't mix signed and unsigned arithmetic
========================================
Strings are measured and indexed using `std::size_t`, which is unsigned, so don't access them using `int`, which is signed and may be too small.
Scrub key data after use
========================
Don't leave secrets in memory unnecessarily, as they could be exposed to an attacker (e.g. in core dumps).
```
~Encryptor()
{
std::fill(std::begin(key16), std::end(key16), 0u);
}
```
Improve the encryption
======================
The encryption algorithm is extremely weak, as some elementary cryptanalysis would reveal. Avoid any encryption that isn't based on proven mathematical difficulty.
The only positive thing I could find is that the code doesn't seem to have any obvious data dependencies in its timing or power consumption.
Ciphertexts are more than 6% larger than plaintexts, making this algorithm inefficient for storage or transmission of secret data. |
231,507 | I am trying to build a fast cryptography algorithm. The algorithm works fine, but I am worried if there are any potential flaws that might make the algorithm vulnerable to any kind of attack. Here is my code.
`Encryptor.cpp`
---------------
```cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Encryptor
{
private:
unsigned char *key; //256 byte
unsigned char key16[16]; //16 byte
public:
Encryptor(unsigned char *k)
{
key = k;
for (int i = 0; i < 256; i += 16)
{
for (int j = 0; j < 16; j++)
{
if (i < 16)
{
key16[j] = key[j];
}
else
{
key16[j] = key16[j] ^ key[i + j];
}
}
}
srand(time(0));
}
string encrypt(string txt)
{
int totalRounds = (txt.size() / 256);
if (txt.size() % 256)
totalRounds++;
string cipher(totalRounds * 16 + txt.size(), 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? txt.size() % 256 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = random(1, 254);
cipher[cipherIndex] = key16[j] ^ randKey[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
cipher[cipherIndex] = key[j] ^ randKey[j % 16] ^ txt[txtIndex];
cipherIndex++;
txtIndex++;
}
}
return cipher;
}
string decrypt(string cipher)
{
int totalRounds = (cipher.size() / (256 + 16));
if (cipher.size() % (256 + 16))
totalRounds++;
string txt(cipher.size() - totalRounds * 16, 0);
for (int i = 0; i < totalRounds; i++)
{
unsigned char randKey[16];
int txtIndex = i * 256;
int cipherIndex = i * (16 + 256);
int txtSize = (i == (totalRounds - 1)) ? (cipher.size() % (256 + 16)) - 16 : 256;
for (int j = 0; j < 16; j++)
{
randKey[j] = cipher[cipherIndex] ^ key16[j];
cipherIndex++;
}
for (int j = 0; j < txtSize; j++)
{
txt[txtIndex] = cipher[cipherIndex] ^ key[j] ^ randKey[j % 16];
cipherIndex++;
txtIndex++;
}
}
return txt;
}
int random(int lower, int upper)
{
return (rand() % (upper - lower + 1)) + lower;
}
};
```
`main.cpp`
----------
```cpp
#include <iostream>
#include "Encryptor.cpp"
using namespace std;
int main()
{
unsigned char key[256] = {239, 222, 80, 163, 48, 26, 182, 101, 123, 51, 145, 28, 106, 157, 105, 1, 51, 129, 222, 124, 80, 254, 118, 220, 208, 75, 225, 127, 180, 192, 125, 149, 22, 140, 218, 162, 89, 45, 237, 250, 71, 85, 245, 75, 59, 122, 146, 95, 68, 130, 33, 62, 124, 11, 203, 252, 72, 141, 140, 12, 241, 218, 89, 147, 58, 124, 209, 177, 71, 254, 201, 3, 166, 10, 179, 89, 194, 72, 150, 32, 97, 197, 119, 50, 185, 11, 202, 164, 175, 115, 239, 113, 146, 7, 84, 62, 49, 124, 25, 108, 111, 107, 250, 168, 75, 137, 87, 219, 115, 242, 237, 23, 79, 53, 95, 45, 180, 59, 243, 138, 37, 219, 174, 13, 188, 19, 62, 104, 176, 154, 183, 242, 177, 19, 215, 42, 197, 88, 149, 246, 40, 54, 184, 31, 187, 9, 115, 152, 128, 165, 116, 105, 179, 242, 145, 195, 250, 153, 139, 247, 96, 51, 225, 237, 86, 97, 97, 196, 146, 67, 73, 88, 30, 135, 192, 29, 64, 189, 123, 95, 152, 22, 31, 5, 71, 38, 136, 6, 68, 247, 93, 206, 200, 229, 243, 140, 11, 137, 60, 197, 22, 92, 118, 44, 3, 47, 121, 249, 88, 27, 101, 242, 222, 36, 112, 45, 188, 46, 170, 201, 244, 90, 115, 224, 88, 157, 109, 136, 228, 134, 186, 124, 154, 3, 78, 49, 225, 57, 249, 172, 103, 44, 74, 84, 158, 48, 139, 185, 207, 9, 58, 143, 211, 177, 62, 32};
Encryptor e(key);
for (int i = 0; i < 100; i++)
{
string c = e.encrypt("my secret");
cout << "cipher: " << c << endl;
cout << "After decryption: " << e.decrypt(c) << endl;
}
return 0;
}
```
---
Algorithm:
==========
* user provides 256 byte key where the value of any byte can't be 0 or 255
* 16 byte internal key is generated from the user provided key
encryption:
===========
* plain text is processed in 256-byte blocks (same as the key length) except the last one which depends on the length of the plain text.
* 16-byte random key is generated for every block where the value of each byte is between 1,254.
* for each plain text block additional 16 byte is added in the beginning of cipher text block that increases the cipher text block size to 256+16 byte
* the first 16 bytes of each cipher text block contains the XOR result of the block random key and the internal key
* the 17th byte of the cipher text = key[first byte] xor random key[first byte] xor plain text block[first byte]
* the 18th byte of the cipher text = key[second byte] xor random key[second byte] xor plain text block[second byte]
....
* when the random key reaches its last byte, as it is shorter than the block size, it repeats from the beginning.
The decryption process is reverse of the encryption process. | 2019/10/30 | [
"https://codereview.stackexchange.com/questions/231507",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/-1/"
]
| Regarding the cryptographic algorithm only:
Important observations
======================
This is equivalent to an XOR cipher with a repeating 256-byte key. The key16 stuff adds no security. The randKey stuff adds no security. The following is working decryption code for one round (I'll use your terminology), if you know the key:
```
unsigned char key16[16] = {0};
for(int k = 0; k < 256; k++) key16[k % 16] ^= key[k];
for(int k = 0; k < 256; k++) key[k] ^= key16[k % 16];
// everything above this line adds no security,
// because we could just take the modified key HERE
// and pretend that's the real key.
// Then we wouldn't need key16.
string decrypted = encrypted.substr(16);
for(int i = 0; i < decrypted.length(); i++) {
// This line adds no security, because the attacker
// knows what encrypted[i % 16] is.
decrypted[i] ^= encrypted[i % 16];
// This is the only part where we need to know the key.
// It's a standard XOR cipher.
decrypted[i] ^= key[i % 256];
}
std::cout << decrypted << std::endl;
```
This does the same as your decryption code (try it and see), but I've rearranged it for easier analysis.
*In the rest of this answer, I will ignore key16 and randKey because they are easily reversed (see code above) and concentrate on the XOR cipher.*
So with that in mind, what are the problems?
It is vulnerable to statistical analysis, to get key16
======================================================
The bytes in randKey are never 0 or 255. This means that after you XOR them with key16, they'll never be equal to key16 or key16^255. If the attacker sees a lot of rounds, this means the attacker can guess the bytes in key16, by narrowing each byte down to 2 possibilities.
If you did discover key16, then you can combine it with 240 key bytes to work out the other 16. So it's not *much* of a breakthrough.
It might be vulnerable to statistical analysis, to get the message
==================================================================
Because the key bytes are never 0 or 255, once you have recovered key16 (see above), you can XOR that with the ciphertext (along with the randKey^key16) and then you'll never get bytes equal to the original message, or the message XOR 255. If you had enough copies of the same message encrypted with different keys, you could figure out which bytes you *aren't* getting, which is the message.
To use this attack, you'd need to have a very long message (so that it contains enough rounds to figure out key16 for each key) and you'd need to see it encrypted with a lot of different keys (so that you can figure out the message).
It is vulnerable to [known plaintext attacks](https://en.wikipedia.org/wiki/Known-plaintext_attack).
====================================================================================================
If you know the plaintext (decrypted text), or part of it, you can XOR the plaintext with the ciphertext (encrypted text), and you get the key.
It is vulnerable to [chosen ciphertext attacks](https://en.wikipedia.org/wiki/Chosen-ciphertext_attack)
=======================================================================================================
If I can give you some ciphertext (encrypted text) and get you to decrypt it, and show me the plaintext (decrypted text), then I can work out the key by XORing them.
In particular, if I just give you a bunch of 0 bytes, and ask you to decrypt them, the plaintext will be the key XOR key16. That's really lame.
It is vulnerable to [frequency analysis](https://en.wikipedia.org/wiki/Frequency_analysis)
==========================================================================================
The most common letter in English is 'e' (ASCII 0x65) or possibly a space (ASCII 0x20). If you see that 0x8F as the most common first byte of a round, you can guess that the first byte of the key XOR key16 is 0xEA (which would make them 'e') or 0xAF (which would make them spaces). Same for the second byte, and the third byte, and all the other bytes. For this to work, the message has to be quite long.
It is vulnerable to XORing two messages
=======================================
Once you undo the random keys, you can XOR the ciphertext for two messages (or blocks) and it will be the same as XORing the plaintext for those two messages (or blocks). This can give you lots of information about the plaintext, but it's very specific to the situation. I'm not sure if this attack has a standard name. | File naming
===========
It's a long-standing convention in C++, as in C, that files meant to be included as part of another translation unit (headers) are given names with a `.h` suffix. It's a good idea to follow such conventions, as it makes the code easier for everyone to understand.
Includes
========
Don't use the C compatibility headers in new code; use the C++ versions, which declare their identifiers in the `std` namespace, whence they can be used unambiguously:
```
#include <cstdio>
#include <cstdlib>
#include <ctime>
```
`using` directive
=================
Don't bring the whole of `std` into the global namespace - especially not in a header file, which will inflict the harm onto the entire translation unit. Just use the minimum set of identifiers you need into the smallest reasonable scope, and fully qualify names where reasonable.
Use initializers
================
Instead of writing `key = k;` in the body of the constructor, it's much better practice to use an initializer for this. That makes it easier for the compiler to determine whether the class is properly initialized:
```
Encryptor(unsigned char *k)
: key{k}
```
Mark conversion constructor as explicit
=======================================
We don't want `Encryptor` to be considered as an implicit promotion from `unsigned char*`, so it should be marked `explicit`.
Avoid mutable non-owning pointers
=================================
We never modify the values in `k[]`, so don't store a mutable pointer:
```
class Encryptor
{
unsigned char const *key;
public:
explicit Encryptor(unsigned char const *k)
: key{k}
{
```
Validate arguments
==================
There's a documented constraint that `k[n]` is not 0 or 255, but this is never checked. The constructor should validate that constraint and throw `std::invalid_argument` if it's violated. However, there's no justification for that constraint - I see no reason not to accept all values from 0 to `UCHAR_MAX`.
Use the full keyspace
=====================
The `key16` array contains only values from 1 to 254. We actually need it to be uniformly distributed across the full range 0 to `UCHAR_MAX`.
Initialise the random seed only once
====================================
`std::srand()` doesn't give very good randomness if reseeded every time we create a new `Encryptor` - it's best called exactly once per process (generally in `main()`, where we can't accidentally link in another call).
Don't pass `std::string` by value
=================================
We can pass inputs by reference to `const`:
```
std::string encrypt(const std::string& txt);
std::string decrypt(const std::string& cipher);
```
Don't pass mutable `this` unnecessarily
=======================================
`encrypt()` and `decrypt()` require only read access; `random()` doesn't use any members at all:
```
std::string encrypt(const std::string& txt) const;
std::string decrypt(const std::string& cipher) const;
private:
static int random(int lower, int upper);
```
Don't mix signed and unsigned arithmetic
========================================
Strings are measured and indexed using `std::size_t`, which is unsigned, so don't access them using `int`, which is signed and may be too small.
Scrub key data after use
========================
Don't leave secrets in memory unnecessarily, as they could be exposed to an attacker (e.g. in core dumps).
```
~Encryptor()
{
std::fill(std::begin(key16), std::end(key16), 0u);
}
```
Improve the encryption
======================
The encryption algorithm is extremely weak, as some elementary cryptanalysis would reveal. Avoid any encryption that isn't based on proven mathematical difficulty.
The only positive thing I could find is that the code doesn't seem to have any obvious data dependencies in its timing or power consumption.
Ciphertexts are more than 6% larger than plaintexts, making this algorithm inefficient for storage or transmission of secret data. |
992,919 | I am using Ubuntu 14.04 LTS with Linux Kernel version 3.13.0-34.
How can I find out what is the default or what is the current TCP congestion control algorithm being used ?
Thanks. | 2015/10/28 | [
"https://superuser.com/questions/992919",
"https://superuser.com",
"https://superuser.com/users/401696/"
]
| There aren't TCP variants; there are TCP *congestion control algorithms*:
```
sysctl net.ipv4.tcp_congestion_control
cat /proc/sys/net/ipv4/tcp_congestion_control
```
The default is usually `cubic` or `reno`, although plenty others are available, and programs can set the preferred algorithm for *individual connections* (e.g. Transmission enables `lp` if available).
(The same knob affects both IPv4 and IPv6, despite its name.) | Adding to ***@grawity*** answer, it is possible to check all TCP congestion control algorithms available with the following command:
```
sysctl net.ipv4.tcp_available_congestion_control
```
A list of some of the possible output (i.e.- availble flavours) is:
*reno*: Traditional TCP used by almost all other OSes. (default)
*cubic*: CUBIC-TCP
*bic*: BIC-TCP
*htcp*: Hamilton TCP
*vegas*: TCP Vegas
*westwood*: optimized for lossy networks
*YeAH*: delay-aware/state-enabled to keep a pipe at or below a threshold
NOTE:
If *cubic* and/or *htcp* are not listed when you do `'sysctl net.ipv4.tcp_available_congestion_control'`, try the following, as most distributions include them as loadable kernel modules:
```
/sbin/modprobe tcp_htcp
/sbin/modprobe tcp_cubic
```
For more detailes you can have look here:
[TCP tuning Details](https://fasterdata.es.net/host-tuning/linux/expert/)
Hope it helps.
Cheers,
Guy. |
992,919 | I am using Ubuntu 14.04 LTS with Linux Kernel version 3.13.0-34.
How can I find out what is the default or what is the current TCP congestion control algorithm being used ?
Thanks. | 2015/10/28 | [
"https://superuser.com/questions/992919",
"https://superuser.com",
"https://superuser.com/users/401696/"
]
| There aren't TCP variants; there are TCP *congestion control algorithms*:
```
sysctl net.ipv4.tcp_congestion_control
cat /proc/sys/net/ipv4/tcp_congestion_control
```
The default is usually `cubic` or `reno`, although plenty others are available, and programs can set the preferred algorithm for *individual connections* (e.g. Transmission enables `lp` if available).
(The same knob affects both IPv4 and IPv6, despite its name.) | If you want to find out the current congestion control algorithm used on each connection you can use the `ss` command (part of the [iproute2](https://wiki.linuxfoundation.org/networking/iproute2) package/tools):
```
ss -ti
```
Here's some example output: Below the connection details, the first item in the parameter output is the congestion control algorithm - in this case `cubic`- which is followed by various parameters related to the TCP connection.
```
ESTAB 0 0 192.168.56.102:ssh 192.168.56.1:61795
cubic wscale:6,7 rto:201 rtt:0.218/0.038 ato:40 mss:1448 rcvmss:1392
advmss:1448 cwnd:10 bytes_acked:8753 bytes_received:3945 segs_out:40
segs_in:63 send 531.4Mbps lastsnd:1 lastrcv:2 lastack:1
pacing_rate 1059.1Mbps rcv_rtt:2 rcv_space:28960
```
Note: It is possible for applications to chose the congestion control algorithm they want to use by using the [`TCP_CONGESTION`](https://www.systutorials.com/docs/linux/man/7-tcp/) setsockopt() call. |
992,919 | I am using Ubuntu 14.04 LTS with Linux Kernel version 3.13.0-34.
How can I find out what is the default or what is the current TCP congestion control algorithm being used ?
Thanks. | 2015/10/28 | [
"https://superuser.com/questions/992919",
"https://superuser.com",
"https://superuser.com/users/401696/"
]
| Adding to ***@grawity*** answer, it is possible to check all TCP congestion control algorithms available with the following command:
```
sysctl net.ipv4.tcp_available_congestion_control
```
A list of some of the possible output (i.e.- availble flavours) is:
*reno*: Traditional TCP used by almost all other OSes. (default)
*cubic*: CUBIC-TCP
*bic*: BIC-TCP
*htcp*: Hamilton TCP
*vegas*: TCP Vegas
*westwood*: optimized for lossy networks
*YeAH*: delay-aware/state-enabled to keep a pipe at or below a threshold
NOTE:
If *cubic* and/or *htcp* are not listed when you do `'sysctl net.ipv4.tcp_available_congestion_control'`, try the following, as most distributions include them as loadable kernel modules:
```
/sbin/modprobe tcp_htcp
/sbin/modprobe tcp_cubic
```
For more detailes you can have look here:
[TCP tuning Details](https://fasterdata.es.net/host-tuning/linux/expert/)
Hope it helps.
Cheers,
Guy. | If you want to find out the current congestion control algorithm used on each connection you can use the `ss` command (part of the [iproute2](https://wiki.linuxfoundation.org/networking/iproute2) package/tools):
```
ss -ti
```
Here's some example output: Below the connection details, the first item in the parameter output is the congestion control algorithm - in this case `cubic`- which is followed by various parameters related to the TCP connection.
```
ESTAB 0 0 192.168.56.102:ssh 192.168.56.1:61795
cubic wscale:6,7 rto:201 rtt:0.218/0.038 ato:40 mss:1448 rcvmss:1392
advmss:1448 cwnd:10 bytes_acked:8753 bytes_received:3945 segs_out:40
segs_in:63 send 531.4Mbps lastsnd:1 lastrcv:2 lastack:1
pacing_rate 1059.1Mbps rcv_rtt:2 rcv_space:28960
```
Note: It is possible for applications to chose the congestion control algorithm they want to use by using the [`TCP_CONGESTION`](https://www.systutorials.com/docs/linux/man/7-tcp/) setsockopt() call. |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| 1. create **/resources** folder inside **src/main**
2. create **application.properties** file inside **/resources**
3. write `server.port=9090` //(use any port number of your choice) | you can set `server.port= #some-available-port number` in application.properties file
or run command prompt in administrator mode and run `netstat -a -o -n`.
Find the process id which is using port 8080.
Run `taskkill /F /PID #Processid` command |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| open command prompt as administrator
step1: netstat -ano | findstr :<enter your 4 digit port number>
```
netstat -ano | findstr :8080
```
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 6436
TCP [::]:8080 [::]:0 LISTENING 6436
step2: taskkill /PID <enter above pid number(sometimes it shown 3/4/5/6 digits)> /F
```
taskkill /PID 6436 /F
```
SUCCESS: The process with PID 6436 has been terminated. | If you getting this error again and again , then make sure server.port=(your port no) is the first line in application.properties file. |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| 1. create **/resources** folder inside **src/main**
2. create **application.properties** file inside **/resources**
3. write `server.port=9090` //(use any port number of your choice) | Reset port 8080.
[reset image description here](https://i.stack.imgur.com/6YVJt.png) |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| 1. create **/resources** folder inside **src/main**
2. create **application.properties** file inside **/resources**
3. write `server.port=9090` //(use any port number of your choice) | The error basically means that your port 8080 is occupied. If you are getting this error then go to your project and open application.properties and add the below line and it should work fine:
```
server.port = 8090
``` |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| If you had previously started the spring boot app and forgot to stop before hitting play again then Go to windows **task manager** and locate the java application(Something like *"OpenJDK Platform binary"* and click on End Task. (Java app not eclipse). Then try running again. It worked for me. | It is a simple answer.If you are getting this error then go to your project then
src/main/resources and open application.properties file and mention there
server.port=8045 you can give your own number here instead of 8045
thanks[](https://i.stack.imgur.com/OzCG4.png) |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| Another way to do this is by first checking what processes are using that specific port, then killing it using its process ID:
1. Run `lsof -i :8080`
This will identify which process is listening on port 8080.
2. Take note of the process ID (PID) e.g. 63262
3. Run `kill -9 <PID>` e.g. `kill -9 63262` | Your client application also spring boot application, whats why you have two spring boot application run in 8080 port.
Change port one of them or create a standalone java application with main class, put your web client in it and run.
As http client you can use Apache Http Client. |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| If you don't want the embedded server to start, just set the following property in you `application.properties` (or `.yml`):
```
spring.main.web-application-type=none
```
>
> If your classpath contains the necessary bits to start a web server, Spring Boot will automatically start it. To disable this behaviour configure the WebApplicationType in your application.properties
>
>
>
Source: <https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-web-servers.html>
---
If you application really **is** a Web application, then you can easily change the port using the `server.port` property (in your application's `.properties`/`.yaml` file, as a command line argument at startup, etc). | if port:8080 already in use error occurs:
* goto command prompt
.type command> .netstat -ano
.Enter->this will show all running port check port 8080
.type command> taskkill /F /PID 8080
.process will terminate. |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| 1. create **/resources** folder inside **src/main**
2. create **application.properties** file inside **/resources**
3. write `server.port=9090` //(use any port number of your choice) | You try to use an already used port.
Ports are used on the transport layer - `tcp`, `http` is application layer and uses a transport layer to send and receive requests.
Default port exposed by spring boot app is `8080`. In your case you have two solutions:
* change port for your application
* stop the service that uses the port you want to use |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| If on windows and your getting this every time you run the application you need to keep doing:
```
> netstat -ano | findstr *<port used>*
TCP 0.0.0.0:*<port used>* 0.0.0.0:0 LISTENING *<pid>*
TCP [::]:*<port used>* [::]:0 LISTENING *<pid>*
> taskkill /F /PID *<pid>*
SUCCESS: The process with PID *<pid>* has been terminated.
```
If netstat above includes something like this;
```
TCP [zzzz:e2ce:44xx:1:axx6:dxxf:xxx:xxxx]:540yy [zzzz:e2ce:44xx:1:axx6:dxxf:xxx:xxxx]:*<port used>* TIME_WAIT 0
```
Then you can either wait for a little while or reconfigure to use another port.
I suppose we could write some code to randomly generate and check if a port is free when the application runs. Though this will have diminishing returns as they start to get used up. On the other hand could add a resource clean up code that does what we have above once the application stops. | If you had previously started the spring boot app and forgot to stop before hitting play again then Go to windows **task manager** and locate the java application(Something like *"OpenJDK Platform binary"* and click on End Task. (Java app not eclipse). Then try running again. It worked for me. |
56,499,932 | I am trying to optimize my code and I found out about comprehensions. But I am struggling with my code and how to apply dictionary comprehension.
The original code is below.
How do I optimize this code in a proper pythonic way?
```py
all_users = []
for x in range(len(result)):
user = {}
user["fieldy"] = str(result[x][1].get("valueforfield1", None))[3:-2]
user["fieldx"] = str(result[x][1].get("valueforfield2", None))[3:-2]
user["fieldc"] = str(result[x][1].get("valueforfield3", None))[3:-2]
user["fieldv"] = str(result[x][1].get("valueforfield4", None))[3:-2]
user["fieldb"] = str(result[x][1].get("valueforfield5", None))[3:-2]
all_users.append(user)
```
example value of result
```py
result = [('CN=Xxx X,OU=X,OU=X,DC=X,DC=X', {'valueforfield1': [b'Va'], 'valueforfield2': [b'val'], 'valueforfield3': [b'+123'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevalue']}),('CN=Yyy Y,OU=Y,OU=Y,DC=Y,DC=Y', {'valueforfield1': [b'Ycx'], 'valueforfield2': [b'Dy'], 'valueforfield3': [b'+321'], 'valueforfield4': [b'[email protected]'], 'valueforfield5': [b'examplevaluey']})]
```
after the code is executed the `user` dictionary have following content after the first iteration of for loop
```
{"fieldy": "Va", "fieldx": "val", "fieldc": "+123", "fieldv": "[email protected]", "fieldb": "examplevalue"}
```
Also should I write a function to replace the `user["field1"] = str(result[x][1].get("valueforfield1", None))[3:-2]` code? Is it worth it and recommended?
Thanks! | 2019/06/07 | [
"https://Stackoverflow.com/questions/56499932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6701554/"
]
| You can change the default port of your application in application.properties by adding the following line:
server.port = 8090 | The best answer to this is to always use the "Relaunch Application" button. That will stop the web server and restart the entire app on the same port as before.
It's the button with the red square and green play icon combined.
<https://i.stack.imgur.com/ICGtX.png> |
41,019,725 | To make it simple let's say I have a dataset consiting of four names: Anna, Bobby , Casper, Christine. The column name is just 'Names'.
I want to sort it in this order: Bobby, Anna, Casper, Christine. I cant use 'proc sort' with 'asc/desc' here. Because it's ordered randomly I need to type in the order manually.
Can I somehow include it the following proc sort statement?
```
Proc Sort
data = dataset; order by Names;
run;
``` | 2016/12/07 | [
"https://Stackoverflow.com/questions/41019725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6278424/"
]
| The answer from @Joe is the best way due to being scalable and the ability to read in formats from a dataset using CNTLIN. I just thought I'd post an alternative solution, using `proc sql`. The version SAS uses enables you to create a custom order on the fly by adding an `order by` statement along with a `case` statement. Effectively this creates an extra column in memory which is used to sort on, but the column is not output.
This is a useful method when the number of items to sort on is relatively small.
```
proc sql;
create table want
as select *
from have
order by case names
when 'Bobby' then 1
when 'Anna' then 2
when 'Casper' then 3
when 'Christine' then 4
end;
quit;
``` | The way you should store categorical variables in SAS is as numerics, with formats to show the characters. This is how other programming languages, e.g. R, handle them (`factor` in R).
So for example:
```
data have;
length names $15;
input names $;
datalines;
Bobby
Anna
Casper
Christine
;;;;
run;
proc format;
value yourformatf
1 = 'Bobby'
2 = 'Anna'
3 = 'Casper'
4 = 'Christine'
other = ' '
;
invalue yourinformati
'Bobby' = 1
'Anna' = 2
'Casper' = 3
'Christine' = 4
other = .
;
quit;
data want;
set have;
names_cat = input(names,yourinformati.);
format names_cat yourformatf.;
run;
```
Here I create a format and an informat to go back/forth (name to number, number to name). You can now sort by `names_cat` and it will sort as you want. You can do this programmatically (creating the format) using a `cntlin` dataset; search here or your search engine of choice for more information on that.
To compare to `r`, if that's what you're familiar with, here the numeric variable is analogous to the values in the factor variable, and the format is analogous to the labels for the levels. (There is no direct analogue to the levels themselves stored in the metadata, but many SAS procs have options to use the numbers stored in the format in the same way levels would be used in R.) |
37,161,349 | Am trying to connect DB2 database in java but it throwing error, I can't find what issue was that. I added **db2jcc.jar** and here I show my complete database connectivity code.
```
public class ConnectionExample {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/TestDb";
String user="user";
String password="pass@123";
Connection connection = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
Am trying to connect DB2 database with the above code but it throws error.
```
com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][3.63.123] Exception java.net.ConnectException: Error opening socket to server localhost/127.0.0.1 on port 50,000 with message: Connection refused: connect. ERRORCODE=-4499, SQLSTATE=08001
at com.ibm.db2.jcc.am.fd.a(fd.java:321)
at com.ibm.db2.jcc.am.fd.a(fd.java:340)
at com.ibm.db2.jcc.t4.xb.a(xb.java:433)
at com.ibm.db2.jcc.t4.xb.<init>(xb.java:90)
at com.ibm.db2.jcc.t4.a.z(a.java:347)
at com.ibm.db2.jcc.t4.b.a(b.java:1974)
at com.ibm.db2.jcc.am.ib.a(ib.java:691)
at com.ibm.db2.jcc.am.ib.<init>(ib.java:644)
at com.ibm.db2.jcc.t4.b.<init>(b.java:330)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:231)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:197)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:472)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:113)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ConnectionExample.main(ConnectionExample.java:18)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.ibm.db2.jcc.t4.x.run(x.java:38)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.db2.jcc.t4.xb.a(xb.java:419)
... 13 more
```
Hope Someone helps me to find out the solution. Thanks | 2016/05/11 | [
"https://Stackoverflow.com/questions/37161349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4348410/"
]
| Actually the port 50000 is not opened that is the reason I got the error after change that port to 51020 it works fine also it connects with database.
```
String url="jdbc:db2://localhost:51020/TestDb";
```
Thanks | **Cause**
A possible cause for this problem is that TCP/IP is not properly enabled on your DB2 database server.
**Resolving the problem**
Use the `db2set DB2COMM` command from the DB2 command window to start the TCP/IP connection:
```
db2set DB2COMM=protocol_names
```
For example, to set the database manager to start connection managers for the TCP/IP communication protocols, enter the following commands:
```
db2set DB2COMM=tcpip
db2stop
db2start
```
Source: <https://www-304.ibm.com/support/docview.wss?uid=swg21403644> |
43,371,178 | I want to make my character transparent in some circumstances, I know I could do that via
```
GetComponent<SpriteRenderer>().color = new Color(1f,1f,1f,0.2f);
```
if it's a single sprite without animation.
But the thing is that it's during an animation, so is there any way to change the sprite sheet's alpha which the animation is using alpha via scripts? | 2017/04/12 | [
"https://Stackoverflow.com/questions/43371178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2288944/"
]
| **Abort object creation**
As documented by Qt, three methods exists to unload/abort an object instantiation:
1. Set [`Loader.active`](http://doc.qt.io/qt-5/qml-qtquick-loader.html#active-prop) to `false`
2. Set [`Loader.source`](http://doc.qt.io/qt-5/qml-qtquick-loader.html#source-prop) to an empty string
3. Set [`Loader.sourceComponent`](http://doc.qt.io/qt-5/qml-qtquick-loader.html#sourceComponent-prop) to `undefined`
**Asynchronous behaviour**
To be able to change these properties during loading, [`Loader.asynchronous`](http://doc.qt.io/qt-5/qml-qtquick-loader.html#asynchronous-prop) should be `true`, otherwise the GUI thread is busy with loading the object. You also need to [`QQmlIncubationController`](http://doc.qt.io/qt-5/qqmlincubationcontroller.html) for your [`QQmlEngine`](http://doc.qt.io/qt-5/qqmlengine.html#setIncubationController) to control the idle time used for object incubation. Without such a controller `Loader.asynchronous` does not have any effect. Note that [`QQmlApplicationEngine`](http://doc.qt.io/qt-5/qqmlapplicationengine.html#details) automatically installs a default controller if the scene contains a `QQuickWindow`.
**Bugs**
Up to the last tested Qt version (Qt 5.8.0, 5.9.0 beta), a severe memory leaks exist when aborting an unfinished object incubation (at least in certain cases, including the example in the answer of derM) resulting in a fast memory usage increase for large components. A [bug report](https://bugreports.qt.io/browse/QTBUG-60188) is created including a proposed solution.
According to the bug report, this should be fixed in Qt version 5.15 (not tested). | I don't know what your issu is, with those *objects that are destroyed before the loader finishs*, but maybe the issue is there? If not, this should work:
If it does not help, please add some code to your question, that reproduces your problem.
**main.qml**
```
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
id: root
visible: true
width: 400; height: 450
Button {
text: (complexLoader.active ? 'Loading' : 'Unloading')
onClicked: complexLoader.active = !complexLoader.active
}
Loader {
id: complexLoader
y: 50
width: 400
height: 400
source: 'ComplexComponent.qml'
asynchronous: true
active: false
// visible: status === 1
}
BusyIndicator {
anchors.fill: complexLoader
running: complexLoader.status === 2
visible: running
}
}
```
**ComplexComponent.qml**
```
import QtQuick 2.0
Rectangle {
id: root
width: 400
height: 400
Grid {
id: grid
anchors.fill: parent
rows: 50
columns: 50
Repeater {
model: parent.rows * parent.columns
delegate: Rectangle {
width: root.width / grid.columns
height: root.height / grid.rows
color: Qt.rgba(Math.random(index),
Math.random(index),
Math.random(index),
Math.random(index))
}
}
}
}
``` |
50,596,214 | I am coding in react js.
We have an input form, which has text input. The text input fires an onChange function that results in a change in state (and thus rendering).
```
var resultJSXcount = 1;
for (let i = 0; i < myArray.length; i++){
resultJSXTable.push(
<tr key= {resultJSXcount++}>
<td style = {{"paddingRight": "10px"}} > {i+1}: </td>
<td style = {{"paddingRight": "10px"}}>
<input
type='text'
id = {i}
value = {myArray[i].name}
onChange = {(event) => {
myArray[i].name = event.target.value;
this.props.updateState()}}
/>
<span style={{"color":"red"}} >
{this.props.parentState.errorName[i]}
</span>
</tr>
);
}
```
This works perfect in Chrome and Internet Explorer. In Firefox, you cannot type, because the input loses focus.
Any help is appreciated! | 2018/05/30 | [
"https://Stackoverflow.com/questions/50596214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9864875/"
]
| I have a guess. It's just a guess, because you do not show everything that is going on.
Your problems come from not understanding how React works. Try this:
* myArray probably comes from state or props. Use setState() to update the contents of myArray instead doing `myArray[i].name = event.target.value;` within onChange. Or if it comes from props, then use redux to update them.
* you probably use props.updateState to trigger rerendering of the component. This should not be necessary if you things described in previous point. | Sorry! I found out the problem was in a completely different area of the code. The above code worked fine.
My error was that when I was applying my styles I had a random focus(). I am not sure why it still worked in Chrome, but crisis averted.
Thanks for the input! |
68,447,733 | I believe I'm misunderstanding how state works in React. I have a TextField as part of a Material UI Autocomplete component. The page is supposed to fetch new results each time the text changes to search the API with the new value. The simple output list at the bottom is updated as expected, but no results are ever populated in the list Autocomplete component. **[Here](https://material-ui.com/components/autocomplete/#combo-box)** is how the Autocomplete is generally supposed to function, and here is my code (**[Sandbox link](https://codesandbox.io/s/boring-davinci-5r4rl?file=/src/App.js)**).
My questions are
1. Why does the TextField not have the text value "basketball" on inital load if the label below does?
2. Are my dependencies of inputText and setOptions the best way to load the data as I'm describing?
Ultimately I want to fetch a list of books, limited to top N results, and populate the rest of the form with data that comes back from the JSON results.
Thanks!
```
<Autocomplete
id="ac1"
options={options}
onInputChange={(event, newValue) => { // text box value changed
console.log("onInputChange start");
setInputText(newValue);
// if ((newValue).length > 3) { setInputText(newValue); }
// else { setOptions([]); }
console.log("onInputChange end");
}}
// SHOW THE TITLE IF THERE IS ONE
getOptionLabel={(option) => option.volumeInfo && option.volumeInfo.title ? option.volumeInfo.title : "Unknown Title"}
style={{ width: 600 }}
renderInput={(params) =>
<>
<TextField {...params} label="Search for a book" variant="outlined"
//ISBN - 10 or 13 digit
value={inputText} // *** I WOULD EXPECT THIS TO BE SET TO "BASKETBALL" ON FIRST RENDER
InputProps={{
...params.inputProps
}}
/>
</>}
/>
```
```
useEffect(() => {
async function fetchData() {
const fetchString = `https://www.googleapis.com/books/v1/volumes?maxResults=3&q=${inputText}&projection=lite`;
console.log(fetchString);
const res = await fetch(
fetchString,
);
const json = await res.json();
// set the options to
(json && json.items) ? setOptions(json.items) : setOptions([]);
}
console.log("fetching data");
fetchData();
console.log("fetched data");
}, [inputText, setOptions]);
``` | 2021/07/19 | [
"https://Stackoverflow.com/questions/68447733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2275171/"
]
| Try this
```
<TextField {...params} label="Search for a book" variant="outlined"
//ISBN - 10 or 13 digit
value={inputText} // *** I WOULD EXPECT THIS TO BE SET TO "BASKETBALL" ON FIRST RENDER
/>
``` | Thank you to @Ignacio Elias for getting me halfway there, so thank you.
I'm sad to say (for the 1,000th time in my career) that the it was something really, *really* stupid. On the second line of the code below I needed to capitalize InputProps in the spread operator because while inputProps *is* [a valid property of TextField](https://material-ui.com/api/text-field/#props), it's not the one I wanted. **I changed "inputProps" to "InputProps" and I'm good now**. I was mixing props InputProps and inputProps. Crazy that these two both exist as valid props.
```
InputProps={{
...params.inputProps, // <----- RIGHT HERE
//autoComplete: 'new-password', // forces no auto-complete history
endAdornment: (
<InputAdornment position="end" color="inherit">
{/* className={classes.adornedEnd} */}
{/* {loading ? */}
<CircularProgress color="secondary" size={"2rem"} />
{/* : null} */}
</InputAdornment>
),
style: {
paddingRight: "5px"
}
}}
``` |
44,672,262 | I have two options in my payment get way i.e. `Credit Card` and `E-Check`. When I select the `Credit Card`, the layout should show something like this
[](https://i.stack.imgur.com/x7xay.png)
The problem is when I select the `E-Check` the layout shows something like this,
[](https://i.stack.imgur.com/loSBb.png)
What I want is to **remove the gap between the radio buttons** and the contents after I click the `E-Check option` and show the E-Check contents in the same place where the credit card shows its contents. It would be more helpful if the get to know how to show nothing when nothing is selected.
**Layout.xml**
```
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="1000dp"
android:background="@color/whitecolor"
tools:context=".Payment">
<ImageView
android:id="@+id/layout"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:background="#FFF"
android:src="@drawable/logo" />
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout2"
android:layout_alignStart="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2">
<TextView
android:id="@+id/paymentduedate"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:text="Payment Date"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp">
<EditText
android:id="@+id/txtpaymentmonth"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:paddingTop="10dp"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtpaymentyear"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="300dp"
android:layout_height="70dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/layout"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="22dp"
android:weightSum="1">
<TextView
android:id="@+id/paymentamount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:text="Payment Amount"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtpaymentamount"
android:layout_width="192dp"
android:layout_height="40dp"
android:layout_marginBottom="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="16dp"
android:layout_weight="0.39"
android:ems="10"
android:hint="00.0"
android:inputType="number"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout3"
android:layout_alignStart="@+id/linearLayout3"
android:layout_below="@+id/linearLayout3"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/paymentvia"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="25dp"
android:text="Payment Via"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="225dp"
android:layout_height="match_parent"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="15dp"
android:paddingLeft="5dp"
android:paddingStart="1dp"
android:weightSum="2">
<RadioButton
android:id="@+id/rdocreditcard"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Credit card"
android:textColor="@color/menucolor" />
<RadioButton
android:id="@+id/rdoEcheck"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingEnd="5dp"
android:text="E-Check"
android:textColor="@color/menucolor" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtcreaditcardnumber"
android:layout_width="181dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.91"
android:ems="10"
android:hint="Credit Card Number"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
<!--
<EditText
android:id="@+id/expmonth"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/expyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.17"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor"
/>
-->
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout"
android:layout_alignStart="@+id/linearLayout"
android:layout_below="@+id/linearLayout">
<EditText
android:id="@+id/txtexpirymonth"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.00"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout5"
android:layout_alignStart="@+id/linearLayout5"
android:layout_below="@+id/linearLayout5">
<EditText
android:id="@+id/txtfirstname"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.11"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
android:layout_weight="0.81"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout6"
android:layout_alignStart="@+id/linearLayout6"
android:layout_alignEnd="@+id/linearLayout6"
android:id="@+id/linearLayout7">
<EditText
android:id="@+id/txtaddress"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Address"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtcity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="City"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout7"
android:layout_alignStart="@+id/linearLayout7"
android:layout_alignEnd="@+id/linearLayout7"
android:weightSum="1"
android:id="@+id/linearLayout8">
<EditText
android:id="@+id/txtstate"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="State"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtzipcode"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Zip code"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtcountry"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Country"
android:textColorHint="@color/menucolor"/>
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout8"
android:layout_alignStart="@+id/linearLayout8"
android:layout_alignEnd="@+id/linearLayout8"
android:id="@+id/linearLayout9">
<EditText
android:id="@+id/txtabaroutingnumber"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="ABA Routing Number"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Number"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout9"
android:layout_alignStart="@+id/linearLayout9"
android:layout_alignEnd="@+id/linearLayout9"
android:id="@+id/linearLayout10">
<EditText
android:id="@+id/txtbankname"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Bank Name"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Name"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout10"
android:layout_alignStart="@+id/linearLayout10"
android:layout_alignEnd="@+id/linearLayout10">
<EditText
android:id="@+id/txtaccounttype"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Account Type"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtechecktype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="E-Check Type"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
```
**Payment.java**
```
public class Payment extends AppCompatActivity {
EditText paymentAmount, paymentDateMonth, paymentDateYear, creditCardNumber, expiryDateMonth,
expirydateYear, ccv, firstName, lastName, address, city, state, zipCode, county,
abaRoutingNumber, accountNumber, bankName, accountName, accountType, echeckType;
RadioGroup radioGroup1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
paymentAmount = (EditText) findViewById(R.id.txtpaymentamount);
paymentDateMonth = (EditText) findViewById(R.id.txtpaymentmonth);
paymentDateYear = (EditText) findViewById(R.id.txtpaymentyear);
//creadit card
creditCardNumber = (EditText) findViewById(R.id.txtcreaditcardnumber);
expiryDateMonth = (EditText) findViewById(R.id.txtexpirymonth);
expirydateYear = (EditText) findViewById(R.id.txtexpiryyear);
ccv = (EditText) findViewById(R.id.txtccv);
firstName = (EditText) findViewById(R.id.txtfirstname);
lastName = (EditText) findViewById(R.id.txtlname);
address = (EditText) findViewById(R.id.txtaddress);
city = (EditText) findViewById(R.id.txtcity);
state = (EditText) findViewById(R.id.txtstate);
zipCode = (EditText) findViewById(R.id.txtzipcode);
county = (EditText) findViewById(R.id.txtcountry);
//E-check
abaRoutingNumber = (EditText) findViewById(R.id.txtabaroutingnumber);
accountNumber = (EditText) findViewById(R.id.txtaccountnumber);
bankName = (EditText) findViewById(R.id.txtbankname);
accountName = (EditText) findViewById(R.id.txtaccountname);
accountType = (EditText) findViewById(R.id.txtaccounttype);
echeckType = (EditText) findViewById(R.id.txtechecktype);
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
if (checkedId == R.id.rdocreditcard){
creditCardNumber.setVisibility(View.VISIBLE);
expiryDateMonth.setVisibility(View.VISIBLE);
expirydateYear.setVisibility(View.VISIBLE);
ccv.setVisibility(View.VISIBLE);
firstName.setVisibility(View.VISIBLE);
lastName.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
city.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
zipCode.setVisibility(View.VISIBLE);
county.setVisibility(View.VISIBLE);
abaRoutingNumber.setVisibility(View.INVISIBLE);
accountNumber.setVisibility(View.INVISIBLE);
bankName.setVisibility(View.INVISIBLE);
accountName.setVisibility(View.INVISIBLE);
accountType.setVisibility(View.INVISIBLE);
echeckType.setVisibility(View.INVISIBLE);
}
else {
creditCardNumber.setVisibility(View.INVISIBLE);
expiryDateMonth.setVisibility(View.INVISIBLE);
expirydateYear.setVisibility(View.INVISIBLE);
ccv.setVisibility(View.INVISIBLE);
firstName.setVisibility(View.INVISIBLE);
lastName.setVisibility(View.INVISIBLE);
address.setVisibility(View.INVISIBLE);
city.setVisibility(View.INVISIBLE);
state.setVisibility(View.INVISIBLE);
zipCode.setVisibility(View.INVISIBLE);
county.setVisibility(View.INVISIBLE);
abaRoutingNumber.setVisibility(View.VISIBLE);
accountNumber.setVisibility(View.VISIBLE);
bankName.setVisibility(View.VISIBLE);
accountName.setVisibility(View.VISIBLE);
accountType.setVisibility(View.VISIBLE);
echeckType.setVisibility(View.VISIBLE);
}
}
});
}
```
} | 2017/06/21 | [
"https://Stackoverflow.com/questions/44672262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5746625/"
]
| Use View.GONE instead of View.INVISIBLE
View.INVISIBLE:
>
> This view is invisible, but it still takes up space for layout
> purposes.
>
>
>
View.GONE:
>
> This view is invisible, and it doesn't take any space for layout
> purposes.
>
>
> | You should play with view attribute `View.GONE` and `View.VISIBLE` to make layouts appear/disappear correctly. |
44,672,262 | I have two options in my payment get way i.e. `Credit Card` and `E-Check`. When I select the `Credit Card`, the layout should show something like this
[](https://i.stack.imgur.com/x7xay.png)
The problem is when I select the `E-Check` the layout shows something like this,
[](https://i.stack.imgur.com/loSBb.png)
What I want is to **remove the gap between the radio buttons** and the contents after I click the `E-Check option` and show the E-Check contents in the same place where the credit card shows its contents. It would be more helpful if the get to know how to show nothing when nothing is selected.
**Layout.xml**
```
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="1000dp"
android:background="@color/whitecolor"
tools:context=".Payment">
<ImageView
android:id="@+id/layout"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:background="#FFF"
android:src="@drawable/logo" />
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout2"
android:layout_alignStart="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2">
<TextView
android:id="@+id/paymentduedate"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:text="Payment Date"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp">
<EditText
android:id="@+id/txtpaymentmonth"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:paddingTop="10dp"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtpaymentyear"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="300dp"
android:layout_height="70dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/layout"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="22dp"
android:weightSum="1">
<TextView
android:id="@+id/paymentamount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:text="Payment Amount"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtpaymentamount"
android:layout_width="192dp"
android:layout_height="40dp"
android:layout_marginBottom="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="16dp"
android:layout_weight="0.39"
android:ems="10"
android:hint="00.0"
android:inputType="number"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout3"
android:layout_alignStart="@+id/linearLayout3"
android:layout_below="@+id/linearLayout3"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/paymentvia"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="25dp"
android:text="Payment Via"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="225dp"
android:layout_height="match_parent"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="15dp"
android:paddingLeft="5dp"
android:paddingStart="1dp"
android:weightSum="2">
<RadioButton
android:id="@+id/rdocreditcard"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Credit card"
android:textColor="@color/menucolor" />
<RadioButton
android:id="@+id/rdoEcheck"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingEnd="5dp"
android:text="E-Check"
android:textColor="@color/menucolor" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtcreaditcardnumber"
android:layout_width="181dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.91"
android:ems="10"
android:hint="Credit Card Number"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
<!--
<EditText
android:id="@+id/expmonth"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/expyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.17"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor"
/>
-->
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout"
android:layout_alignStart="@+id/linearLayout"
android:layout_below="@+id/linearLayout">
<EditText
android:id="@+id/txtexpirymonth"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.00"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout5"
android:layout_alignStart="@+id/linearLayout5"
android:layout_below="@+id/linearLayout5">
<EditText
android:id="@+id/txtfirstname"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.11"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
android:layout_weight="0.81"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout6"
android:layout_alignStart="@+id/linearLayout6"
android:layout_alignEnd="@+id/linearLayout6"
android:id="@+id/linearLayout7">
<EditText
android:id="@+id/txtaddress"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Address"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtcity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="City"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout7"
android:layout_alignStart="@+id/linearLayout7"
android:layout_alignEnd="@+id/linearLayout7"
android:weightSum="1"
android:id="@+id/linearLayout8">
<EditText
android:id="@+id/txtstate"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="State"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtzipcode"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Zip code"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtcountry"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Country"
android:textColorHint="@color/menucolor"/>
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout8"
android:layout_alignStart="@+id/linearLayout8"
android:layout_alignEnd="@+id/linearLayout8"
android:id="@+id/linearLayout9">
<EditText
android:id="@+id/txtabaroutingnumber"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="ABA Routing Number"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Number"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout9"
android:layout_alignStart="@+id/linearLayout9"
android:layout_alignEnd="@+id/linearLayout9"
android:id="@+id/linearLayout10">
<EditText
android:id="@+id/txtbankname"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Bank Name"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Name"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout10"
android:layout_alignStart="@+id/linearLayout10"
android:layout_alignEnd="@+id/linearLayout10">
<EditText
android:id="@+id/txtaccounttype"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Account Type"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtechecktype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="E-Check Type"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
```
**Payment.java**
```
public class Payment extends AppCompatActivity {
EditText paymentAmount, paymentDateMonth, paymentDateYear, creditCardNumber, expiryDateMonth,
expirydateYear, ccv, firstName, lastName, address, city, state, zipCode, county,
abaRoutingNumber, accountNumber, bankName, accountName, accountType, echeckType;
RadioGroup radioGroup1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
paymentAmount = (EditText) findViewById(R.id.txtpaymentamount);
paymentDateMonth = (EditText) findViewById(R.id.txtpaymentmonth);
paymentDateYear = (EditText) findViewById(R.id.txtpaymentyear);
//creadit card
creditCardNumber = (EditText) findViewById(R.id.txtcreaditcardnumber);
expiryDateMonth = (EditText) findViewById(R.id.txtexpirymonth);
expirydateYear = (EditText) findViewById(R.id.txtexpiryyear);
ccv = (EditText) findViewById(R.id.txtccv);
firstName = (EditText) findViewById(R.id.txtfirstname);
lastName = (EditText) findViewById(R.id.txtlname);
address = (EditText) findViewById(R.id.txtaddress);
city = (EditText) findViewById(R.id.txtcity);
state = (EditText) findViewById(R.id.txtstate);
zipCode = (EditText) findViewById(R.id.txtzipcode);
county = (EditText) findViewById(R.id.txtcountry);
//E-check
abaRoutingNumber = (EditText) findViewById(R.id.txtabaroutingnumber);
accountNumber = (EditText) findViewById(R.id.txtaccountnumber);
bankName = (EditText) findViewById(R.id.txtbankname);
accountName = (EditText) findViewById(R.id.txtaccountname);
accountType = (EditText) findViewById(R.id.txtaccounttype);
echeckType = (EditText) findViewById(R.id.txtechecktype);
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
if (checkedId == R.id.rdocreditcard){
creditCardNumber.setVisibility(View.VISIBLE);
expiryDateMonth.setVisibility(View.VISIBLE);
expirydateYear.setVisibility(View.VISIBLE);
ccv.setVisibility(View.VISIBLE);
firstName.setVisibility(View.VISIBLE);
lastName.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
city.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
zipCode.setVisibility(View.VISIBLE);
county.setVisibility(View.VISIBLE);
abaRoutingNumber.setVisibility(View.INVISIBLE);
accountNumber.setVisibility(View.INVISIBLE);
bankName.setVisibility(View.INVISIBLE);
accountName.setVisibility(View.INVISIBLE);
accountType.setVisibility(View.INVISIBLE);
echeckType.setVisibility(View.INVISIBLE);
}
else {
creditCardNumber.setVisibility(View.INVISIBLE);
expiryDateMonth.setVisibility(View.INVISIBLE);
expirydateYear.setVisibility(View.INVISIBLE);
ccv.setVisibility(View.INVISIBLE);
firstName.setVisibility(View.INVISIBLE);
lastName.setVisibility(View.INVISIBLE);
address.setVisibility(View.INVISIBLE);
city.setVisibility(View.INVISIBLE);
state.setVisibility(View.INVISIBLE);
zipCode.setVisibility(View.INVISIBLE);
county.setVisibility(View.INVISIBLE);
abaRoutingNumber.setVisibility(View.VISIBLE);
accountNumber.setVisibility(View.VISIBLE);
bankName.setVisibility(View.VISIBLE);
accountName.setVisibility(View.VISIBLE);
accountType.setVisibility(View.VISIBLE);
echeckType.setVisibility(View.VISIBLE);
}
}
});
}
```
} | 2017/06/21 | [
"https://Stackoverflow.com/questions/44672262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5746625/"
]
| Don't know why people are giving you such stupid answers.
Try this simple thing:
In your layout code change this:
Just below your Radio button layout make two layout like this:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:layout_alignEnd="@+id/linearLayout4"
android:id="@+id/creditcard_layout">
//copy your credit card layout here
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:id="@+id/echeck_layout">
//copy your ecard card layout here
</LinearLayout>
```
and then in your code on radio button click show the respective layout.Apart from this you don't have to change anything else.
Hope it'll help you. | You should play with view attribute `View.GONE` and `View.VISIBLE` to make layouts appear/disappear correctly. |
44,672,262 | I have two options in my payment get way i.e. `Credit Card` and `E-Check`. When I select the `Credit Card`, the layout should show something like this
[](https://i.stack.imgur.com/x7xay.png)
The problem is when I select the `E-Check` the layout shows something like this,
[](https://i.stack.imgur.com/loSBb.png)
What I want is to **remove the gap between the radio buttons** and the contents after I click the `E-Check option` and show the E-Check contents in the same place where the credit card shows its contents. It would be more helpful if the get to know how to show nothing when nothing is selected.
**Layout.xml**
```
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="1000dp"
android:background="@color/whitecolor"
tools:context=".Payment">
<ImageView
android:id="@+id/layout"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:background="#FFF"
android:src="@drawable/logo" />
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout2"
android:layout_alignStart="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2">
<TextView
android:id="@+id/paymentduedate"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:text="Payment Date"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp">
<EditText
android:id="@+id/txtpaymentmonth"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:paddingTop="10dp"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtpaymentyear"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="300dp"
android:layout_height="70dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/layout"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="22dp"
android:weightSum="1">
<TextView
android:id="@+id/paymentamount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:text="Payment Amount"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtpaymentamount"
android:layout_width="192dp"
android:layout_height="40dp"
android:layout_marginBottom="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="16dp"
android:layout_weight="0.39"
android:ems="10"
android:hint="00.0"
android:inputType="number"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout3"
android:layout_alignStart="@+id/linearLayout3"
android:layout_below="@+id/linearLayout3"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/paymentvia"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="25dp"
android:text="Payment Via"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="225dp"
android:layout_height="match_parent"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="15dp"
android:paddingLeft="5dp"
android:paddingStart="1dp"
android:weightSum="2">
<RadioButton
android:id="@+id/rdocreditcard"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Credit card"
android:textColor="@color/menucolor" />
<RadioButton
android:id="@+id/rdoEcheck"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingEnd="5dp"
android:text="E-Check"
android:textColor="@color/menucolor" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtcreaditcardnumber"
android:layout_width="181dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.91"
android:ems="10"
android:hint="Credit Card Number"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
<!--
<EditText
android:id="@+id/expmonth"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/expyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.17"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor"
/>
-->
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout"
android:layout_alignStart="@+id/linearLayout"
android:layout_below="@+id/linearLayout">
<EditText
android:id="@+id/txtexpirymonth"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.00"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout5"
android:layout_alignStart="@+id/linearLayout5"
android:layout_below="@+id/linearLayout5">
<EditText
android:id="@+id/txtfirstname"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.11"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
android:layout_weight="0.81"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout6"
android:layout_alignStart="@+id/linearLayout6"
android:layout_alignEnd="@+id/linearLayout6"
android:id="@+id/linearLayout7">
<EditText
android:id="@+id/txtaddress"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Address"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtcity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="City"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout7"
android:layout_alignStart="@+id/linearLayout7"
android:layout_alignEnd="@+id/linearLayout7"
android:weightSum="1"
android:id="@+id/linearLayout8">
<EditText
android:id="@+id/txtstate"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="State"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtzipcode"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Zip code"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtcountry"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Country"
android:textColorHint="@color/menucolor"/>
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout8"
android:layout_alignStart="@+id/linearLayout8"
android:layout_alignEnd="@+id/linearLayout8"
android:id="@+id/linearLayout9">
<EditText
android:id="@+id/txtabaroutingnumber"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="ABA Routing Number"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Number"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout9"
android:layout_alignStart="@+id/linearLayout9"
android:layout_alignEnd="@+id/linearLayout9"
android:id="@+id/linearLayout10">
<EditText
android:id="@+id/txtbankname"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Bank Name"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Name"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout10"
android:layout_alignStart="@+id/linearLayout10"
android:layout_alignEnd="@+id/linearLayout10">
<EditText
android:id="@+id/txtaccounttype"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Account Type"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtechecktype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="E-Check Type"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
```
**Payment.java**
```
public class Payment extends AppCompatActivity {
EditText paymentAmount, paymentDateMonth, paymentDateYear, creditCardNumber, expiryDateMonth,
expirydateYear, ccv, firstName, lastName, address, city, state, zipCode, county,
abaRoutingNumber, accountNumber, bankName, accountName, accountType, echeckType;
RadioGroup radioGroup1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
paymentAmount = (EditText) findViewById(R.id.txtpaymentamount);
paymentDateMonth = (EditText) findViewById(R.id.txtpaymentmonth);
paymentDateYear = (EditText) findViewById(R.id.txtpaymentyear);
//creadit card
creditCardNumber = (EditText) findViewById(R.id.txtcreaditcardnumber);
expiryDateMonth = (EditText) findViewById(R.id.txtexpirymonth);
expirydateYear = (EditText) findViewById(R.id.txtexpiryyear);
ccv = (EditText) findViewById(R.id.txtccv);
firstName = (EditText) findViewById(R.id.txtfirstname);
lastName = (EditText) findViewById(R.id.txtlname);
address = (EditText) findViewById(R.id.txtaddress);
city = (EditText) findViewById(R.id.txtcity);
state = (EditText) findViewById(R.id.txtstate);
zipCode = (EditText) findViewById(R.id.txtzipcode);
county = (EditText) findViewById(R.id.txtcountry);
//E-check
abaRoutingNumber = (EditText) findViewById(R.id.txtabaroutingnumber);
accountNumber = (EditText) findViewById(R.id.txtaccountnumber);
bankName = (EditText) findViewById(R.id.txtbankname);
accountName = (EditText) findViewById(R.id.txtaccountname);
accountType = (EditText) findViewById(R.id.txtaccounttype);
echeckType = (EditText) findViewById(R.id.txtechecktype);
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
if (checkedId == R.id.rdocreditcard){
creditCardNumber.setVisibility(View.VISIBLE);
expiryDateMonth.setVisibility(View.VISIBLE);
expirydateYear.setVisibility(View.VISIBLE);
ccv.setVisibility(View.VISIBLE);
firstName.setVisibility(View.VISIBLE);
lastName.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
city.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
zipCode.setVisibility(View.VISIBLE);
county.setVisibility(View.VISIBLE);
abaRoutingNumber.setVisibility(View.INVISIBLE);
accountNumber.setVisibility(View.INVISIBLE);
bankName.setVisibility(View.INVISIBLE);
accountName.setVisibility(View.INVISIBLE);
accountType.setVisibility(View.INVISIBLE);
echeckType.setVisibility(View.INVISIBLE);
}
else {
creditCardNumber.setVisibility(View.INVISIBLE);
expiryDateMonth.setVisibility(View.INVISIBLE);
expirydateYear.setVisibility(View.INVISIBLE);
ccv.setVisibility(View.INVISIBLE);
firstName.setVisibility(View.INVISIBLE);
lastName.setVisibility(View.INVISIBLE);
address.setVisibility(View.INVISIBLE);
city.setVisibility(View.INVISIBLE);
state.setVisibility(View.INVISIBLE);
zipCode.setVisibility(View.INVISIBLE);
county.setVisibility(View.INVISIBLE);
abaRoutingNumber.setVisibility(View.VISIBLE);
accountNumber.setVisibility(View.VISIBLE);
bankName.setVisibility(View.VISIBLE);
accountName.setVisibility(View.VISIBLE);
accountType.setVisibility(View.VISIBLE);
echeckType.setVisibility(View.VISIBLE);
}
}
});
}
```
} | 2017/06/21 | [
"https://Stackoverflow.com/questions/44672262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5746625/"
]
| Use View.GONE instead of View.INVISIBLE
View.INVISIBLE:
>
> This view is invisible, but it still takes up space for layout
> purposes.
>
>
>
View.GONE:
>
> This view is invisible, and it doesn't take any space for layout
> purposes.
>
>
> | You can use two `FrameLayout` inside of `RelativeLayout`. Insert all views related to credit card in first & other into second `FrameLayout`. Then manage click event with `View.GONE` and `View.VISIBLE` |
44,672,262 | I have two options in my payment get way i.e. `Credit Card` and `E-Check`. When I select the `Credit Card`, the layout should show something like this
[](https://i.stack.imgur.com/x7xay.png)
The problem is when I select the `E-Check` the layout shows something like this,
[](https://i.stack.imgur.com/loSBb.png)
What I want is to **remove the gap between the radio buttons** and the contents after I click the `E-Check option` and show the E-Check contents in the same place where the credit card shows its contents. It would be more helpful if the get to know how to show nothing when nothing is selected.
**Layout.xml**
```
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="1000dp"
android:background="@color/whitecolor"
tools:context=".Payment">
<ImageView
android:id="@+id/layout"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:background="#FFF"
android:src="@drawable/logo" />
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout2"
android:layout_alignStart="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2">
<TextView
android:id="@+id/paymentduedate"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:text="Payment Date"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp">
<EditText
android:id="@+id/txtpaymentmonth"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:paddingTop="10dp"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtpaymentyear"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="300dp"
android:layout_height="70dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/layout"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="22dp"
android:weightSum="1">
<TextView
android:id="@+id/paymentamount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:text="Payment Amount"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtpaymentamount"
android:layout_width="192dp"
android:layout_height="40dp"
android:layout_marginBottom="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="16dp"
android:layout_weight="0.39"
android:ems="10"
android:hint="00.0"
android:inputType="number"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout3"
android:layout_alignStart="@+id/linearLayout3"
android:layout_below="@+id/linearLayout3"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/paymentvia"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="25dp"
android:text="Payment Via"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="225dp"
android:layout_height="match_parent"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="15dp"
android:paddingLeft="5dp"
android:paddingStart="1dp"
android:weightSum="2">
<RadioButton
android:id="@+id/rdocreditcard"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Credit card"
android:textColor="@color/menucolor" />
<RadioButton
android:id="@+id/rdoEcheck"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingEnd="5dp"
android:text="E-Check"
android:textColor="@color/menucolor" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtcreaditcardnumber"
android:layout_width="181dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.91"
android:ems="10"
android:hint="Credit Card Number"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
<!--
<EditText
android:id="@+id/expmonth"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/expyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.17"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor"
/>
-->
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout"
android:layout_alignStart="@+id/linearLayout"
android:layout_below="@+id/linearLayout">
<EditText
android:id="@+id/txtexpirymonth"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.00"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout5"
android:layout_alignStart="@+id/linearLayout5"
android:layout_below="@+id/linearLayout5">
<EditText
android:id="@+id/txtfirstname"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.11"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
android:layout_weight="0.81"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout6"
android:layout_alignStart="@+id/linearLayout6"
android:layout_alignEnd="@+id/linearLayout6"
android:id="@+id/linearLayout7">
<EditText
android:id="@+id/txtaddress"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Address"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtcity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="City"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout7"
android:layout_alignStart="@+id/linearLayout7"
android:layout_alignEnd="@+id/linearLayout7"
android:weightSum="1"
android:id="@+id/linearLayout8">
<EditText
android:id="@+id/txtstate"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="State"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtzipcode"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Zip code"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtcountry"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Country"
android:textColorHint="@color/menucolor"/>
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout8"
android:layout_alignStart="@+id/linearLayout8"
android:layout_alignEnd="@+id/linearLayout8"
android:id="@+id/linearLayout9">
<EditText
android:id="@+id/txtabaroutingnumber"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="ABA Routing Number"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Number"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout9"
android:layout_alignStart="@+id/linearLayout9"
android:layout_alignEnd="@+id/linearLayout9"
android:id="@+id/linearLayout10">
<EditText
android:id="@+id/txtbankname"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Bank Name"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Name"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout10"
android:layout_alignStart="@+id/linearLayout10"
android:layout_alignEnd="@+id/linearLayout10">
<EditText
android:id="@+id/txtaccounttype"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Account Type"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtechecktype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="E-Check Type"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
```
**Payment.java**
```
public class Payment extends AppCompatActivity {
EditText paymentAmount, paymentDateMonth, paymentDateYear, creditCardNumber, expiryDateMonth,
expirydateYear, ccv, firstName, lastName, address, city, state, zipCode, county,
abaRoutingNumber, accountNumber, bankName, accountName, accountType, echeckType;
RadioGroup radioGroup1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
paymentAmount = (EditText) findViewById(R.id.txtpaymentamount);
paymentDateMonth = (EditText) findViewById(R.id.txtpaymentmonth);
paymentDateYear = (EditText) findViewById(R.id.txtpaymentyear);
//creadit card
creditCardNumber = (EditText) findViewById(R.id.txtcreaditcardnumber);
expiryDateMonth = (EditText) findViewById(R.id.txtexpirymonth);
expirydateYear = (EditText) findViewById(R.id.txtexpiryyear);
ccv = (EditText) findViewById(R.id.txtccv);
firstName = (EditText) findViewById(R.id.txtfirstname);
lastName = (EditText) findViewById(R.id.txtlname);
address = (EditText) findViewById(R.id.txtaddress);
city = (EditText) findViewById(R.id.txtcity);
state = (EditText) findViewById(R.id.txtstate);
zipCode = (EditText) findViewById(R.id.txtzipcode);
county = (EditText) findViewById(R.id.txtcountry);
//E-check
abaRoutingNumber = (EditText) findViewById(R.id.txtabaroutingnumber);
accountNumber = (EditText) findViewById(R.id.txtaccountnumber);
bankName = (EditText) findViewById(R.id.txtbankname);
accountName = (EditText) findViewById(R.id.txtaccountname);
accountType = (EditText) findViewById(R.id.txtaccounttype);
echeckType = (EditText) findViewById(R.id.txtechecktype);
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
if (checkedId == R.id.rdocreditcard){
creditCardNumber.setVisibility(View.VISIBLE);
expiryDateMonth.setVisibility(View.VISIBLE);
expirydateYear.setVisibility(View.VISIBLE);
ccv.setVisibility(View.VISIBLE);
firstName.setVisibility(View.VISIBLE);
lastName.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
city.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
zipCode.setVisibility(View.VISIBLE);
county.setVisibility(View.VISIBLE);
abaRoutingNumber.setVisibility(View.INVISIBLE);
accountNumber.setVisibility(View.INVISIBLE);
bankName.setVisibility(View.INVISIBLE);
accountName.setVisibility(View.INVISIBLE);
accountType.setVisibility(View.INVISIBLE);
echeckType.setVisibility(View.INVISIBLE);
}
else {
creditCardNumber.setVisibility(View.INVISIBLE);
expiryDateMonth.setVisibility(View.INVISIBLE);
expirydateYear.setVisibility(View.INVISIBLE);
ccv.setVisibility(View.INVISIBLE);
firstName.setVisibility(View.INVISIBLE);
lastName.setVisibility(View.INVISIBLE);
address.setVisibility(View.INVISIBLE);
city.setVisibility(View.INVISIBLE);
state.setVisibility(View.INVISIBLE);
zipCode.setVisibility(View.INVISIBLE);
county.setVisibility(View.INVISIBLE);
abaRoutingNumber.setVisibility(View.VISIBLE);
accountNumber.setVisibility(View.VISIBLE);
bankName.setVisibility(View.VISIBLE);
accountName.setVisibility(View.VISIBLE);
accountType.setVisibility(View.VISIBLE);
echeckType.setVisibility(View.VISIBLE);
}
}
});
}
```
} | 2017/06/21 | [
"https://Stackoverflow.com/questions/44672262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5746625/"
]
| Don't know why people are giving you such stupid answers.
Try this simple thing:
In your layout code change this:
Just below your Radio button layout make two layout like this:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:layout_alignEnd="@+id/linearLayout4"
android:id="@+id/creditcard_layout">
//copy your credit card layout here
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:id="@+id/echeck_layout">
//copy your ecard card layout here
</LinearLayout>
```
and then in your code on radio button click show the respective layout.Apart from this you don't have to change anything else.
Hope it'll help you. | You can use two `FrameLayout` inside of `RelativeLayout`. Insert all views related to credit card in first & other into second `FrameLayout`. Then manage click event with `View.GONE` and `View.VISIBLE` |
44,672,262 | I have two options in my payment get way i.e. `Credit Card` and `E-Check`. When I select the `Credit Card`, the layout should show something like this
[](https://i.stack.imgur.com/x7xay.png)
The problem is when I select the `E-Check` the layout shows something like this,
[](https://i.stack.imgur.com/loSBb.png)
What I want is to **remove the gap between the radio buttons** and the contents after I click the `E-Check option` and show the E-Check contents in the same place where the credit card shows its contents. It would be more helpful if the get to know how to show nothing when nothing is selected.
**Layout.xml**
```
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="1000dp"
android:background="@color/whitecolor"
tools:context=".Payment">
<ImageView
android:id="@+id/layout"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:background="#FFF"
android:src="@drawable/logo" />
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout2"
android:layout_alignStart="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2">
<TextView
android:id="@+id/paymentduedate"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="30dp"
android:text="Payment Date"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp">
<EditText
android:id="@+id/txtpaymentmonth"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:paddingTop="10dp"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtpaymentyear"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="300dp"
android:layout_height="70dp"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/layout"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="22dp"
android:weightSum="1">
<TextView
android:id="@+id/paymentamount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:text="Payment Amount"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtpaymentamount"
android:layout_width="192dp"
android:layout_height="40dp"
android:layout_marginBottom="5dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="10dp"
android:layout_marginTop="16dp"
android:layout_weight="0.39"
android:ems="10"
android:hint="00.0"
android:inputType="number"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout3"
android:layout_alignStart="@+id/linearLayout3"
android:layout_below="@+id/linearLayout3"
android:orientation="horizontal"
android:weightSum="1">
<TextView
android:id="@+id/paymentvia"
android:layout_width="117dp"
android:layout_height="18dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="25dp"
android:text="Payment Via"
android:textColor="@color/menucolor"
android:textSize="15dp"
android:textStyle="bold" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="225dp"
android:layout_height="match_parent"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="15dp"
android:paddingLeft="5dp"
android:paddingStart="1dp"
android:weightSum="2">
<RadioButton
android:id="@+id/rdocreditcard"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Credit card"
android:textColor="@color/menucolor" />
<RadioButton
android:id="@+id/rdoEcheck"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:paddingEnd="5dp"
android:text="E-Check"
android:textColor="@color/menucolor" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="@+id/txtcreaditcardnumber"
android:layout_width="181dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.91"
android:ems="10"
android:hint="Credit Card Number"
android:inputType="number"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColorHint="@color/menucolor" />
<!--
<EditText
android:id="@+id/expmonth"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/expyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.17"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor"
/>
-->
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout5"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout"
android:layout_alignStart="@+id/linearLayout"
android:layout_below="@+id/linearLayout">
<EditText
android:id="@+id/txtexpirymonth"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.00"
android:ems="10"
android:hint="MM"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="YYYY"
android:inputType="number"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtexpiryyear"
android:layout_width="61dp"
android:layout_height="40dp"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:hint="CCV"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout6"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignEnd="@+id/linearLayout5"
android:layout_alignStart="@+id/linearLayout5"
android:layout_below="@+id/linearLayout5">
<EditText
android:id="@+id/txtfirstname"
android:layout_width="145dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="0.11"
android:ems="10"
android:hint="First Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtlname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
android:layout_weight="0.81"
android:ems="10"
android:hint="Last Name"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout6"
android:layout_alignStart="@+id/linearLayout6"
android:layout_alignEnd="@+id/linearLayout6"
android:id="@+id/linearLayout7">
<EditText
android:id="@+id/txtaddress"
android:layout_width="149dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:hint="Address"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
<EditText
android:id="@+id/txtcity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:ems="10"
android:hint="City"
android:inputType="textPersonName"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/linearLayout7"
android:layout_alignStart="@+id/linearLayout7"
android:layout_alignEnd="@+id/linearLayout7"
android:weightSum="1"
android:id="@+id/linearLayout8">
<EditText
android:id="@+id/txtstate"
android:layout_width="101dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="State"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtzipcode"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Zip code"
android:textColorHint="@color/menucolor"/>
<EditText
android:id="@+id/txtcountry"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="Country"
android:textColorHint="@color/menucolor"/>
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout8"
android:layout_alignStart="@+id/linearLayout8"
android:layout_alignEnd="@+id/linearLayout8"
android:id="@+id/linearLayout9">
<EditText
android:id="@+id/txtabaroutingnumber"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="ABA Routing Number"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Number"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout9"
android:layout_alignStart="@+id/linearLayout9"
android:layout_alignEnd="@+id/linearLayout9"
android:id="@+id/linearLayout10">
<EditText
android:id="@+id/txtbankname"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Bank Name"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtaccountname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="Account Name"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="60dp"
android:weightSum="1"
android:layout_below="@+id/linearLayout10"
android:layout_alignStart="@+id/linearLayout10"
android:layout_alignEnd="@+id/linearLayout10">
<EditText
android:id="@+id/txtaccounttype"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:hint="Account Type"
android:textColorHint="@color/menucolor"
android:layout_weight="0.05" />
<EditText
android:id="@+id/txtechecktype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_weight="0.84"
android:ems="10"
android:hint="E-Check Type"
android:inputType="number"
android:textColorHint="@color/menucolor" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
```
**Payment.java**
```
public class Payment extends AppCompatActivity {
EditText paymentAmount, paymentDateMonth, paymentDateYear, creditCardNumber, expiryDateMonth,
expirydateYear, ccv, firstName, lastName, address, city, state, zipCode, county,
abaRoutingNumber, accountNumber, bankName, accountName, accountType, echeckType;
RadioGroup radioGroup1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
paymentAmount = (EditText) findViewById(R.id.txtpaymentamount);
paymentDateMonth = (EditText) findViewById(R.id.txtpaymentmonth);
paymentDateYear = (EditText) findViewById(R.id.txtpaymentyear);
//creadit card
creditCardNumber = (EditText) findViewById(R.id.txtcreaditcardnumber);
expiryDateMonth = (EditText) findViewById(R.id.txtexpirymonth);
expirydateYear = (EditText) findViewById(R.id.txtexpiryyear);
ccv = (EditText) findViewById(R.id.txtccv);
firstName = (EditText) findViewById(R.id.txtfirstname);
lastName = (EditText) findViewById(R.id.txtlname);
address = (EditText) findViewById(R.id.txtaddress);
city = (EditText) findViewById(R.id.txtcity);
state = (EditText) findViewById(R.id.txtstate);
zipCode = (EditText) findViewById(R.id.txtzipcode);
county = (EditText) findViewById(R.id.txtcountry);
//E-check
abaRoutingNumber = (EditText) findViewById(R.id.txtabaroutingnumber);
accountNumber = (EditText) findViewById(R.id.txtaccountnumber);
bankName = (EditText) findViewById(R.id.txtbankname);
accountName = (EditText) findViewById(R.id.txtaccountname);
accountType = (EditText) findViewById(R.id.txtaccounttype);
echeckType = (EditText) findViewById(R.id.txtechecktype);
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
if (checkedId == R.id.rdocreditcard){
creditCardNumber.setVisibility(View.VISIBLE);
expiryDateMonth.setVisibility(View.VISIBLE);
expirydateYear.setVisibility(View.VISIBLE);
ccv.setVisibility(View.VISIBLE);
firstName.setVisibility(View.VISIBLE);
lastName.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
city.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
zipCode.setVisibility(View.VISIBLE);
county.setVisibility(View.VISIBLE);
abaRoutingNumber.setVisibility(View.INVISIBLE);
accountNumber.setVisibility(View.INVISIBLE);
bankName.setVisibility(View.INVISIBLE);
accountName.setVisibility(View.INVISIBLE);
accountType.setVisibility(View.INVISIBLE);
echeckType.setVisibility(View.INVISIBLE);
}
else {
creditCardNumber.setVisibility(View.INVISIBLE);
expiryDateMonth.setVisibility(View.INVISIBLE);
expirydateYear.setVisibility(View.INVISIBLE);
ccv.setVisibility(View.INVISIBLE);
firstName.setVisibility(View.INVISIBLE);
lastName.setVisibility(View.INVISIBLE);
address.setVisibility(View.INVISIBLE);
city.setVisibility(View.INVISIBLE);
state.setVisibility(View.INVISIBLE);
zipCode.setVisibility(View.INVISIBLE);
county.setVisibility(View.INVISIBLE);
abaRoutingNumber.setVisibility(View.VISIBLE);
accountNumber.setVisibility(View.VISIBLE);
bankName.setVisibility(View.VISIBLE);
accountName.setVisibility(View.VISIBLE);
accountType.setVisibility(View.VISIBLE);
echeckType.setVisibility(View.VISIBLE);
}
}
});
}
```
} | 2017/06/21 | [
"https://Stackoverflow.com/questions/44672262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5746625/"
]
| Don't know why people are giving you such stupid answers.
Try this simple thing:
In your layout code change this:
Just below your Radio button layout make two layout like this:
```
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:layout_alignEnd="@+id/linearLayout4"
android:id="@+id/creditcard_layout">
//copy your credit card layout here
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone"
android:layout_alignEnd="@+id/linearLayout4"
android:layout_alignStart="@+id/linearLayout4"
android:layout_below="@+id/linearLayout4"
android:id="@+id/echeck_layout">
//copy your ecard card layout here
</LinearLayout>
```
and then in your code on radio button click show the respective layout.Apart from this you don't have to change anything else.
Hope it'll help you. | Use View.GONE instead of View.INVISIBLE
View.INVISIBLE:
>
> This view is invisible, but it still takes up space for layout
> purposes.
>
>
>
View.GONE:
>
> This view is invisible, and it doesn't take any space for layout
> purposes.
>
>
> |
43,751,597 | ```
SELECT
player.FirstName,
player.LastName,
team.teamName,
TotalPoints,
TotalRebounds,
TotalAssists,
TotalSteals,
TotalBlocks
FROM playerstats
INNER JOIN player
ON playerstats.PlayerID = player.PlayerID
```
I have a table called player (Player ID, firstname, lastname, team ID)
table called Team (teamID, teamName). I have a table called playerstat(which has playerID)
I want to list firstname, last name and team along with total points, rebounds, etc
I want to use the playerID to get the team Id then list the team name ... if that makes sense. Not sure how to do that. | 2017/05/03 | [
"https://Stackoverflow.com/questions/43751597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7795206/"
]
| There's no built-in function for this, but you can easily create one yourself:
```
def chop(expr, *, max=0.3):
return [i if i > max else 0 for i in expr]
```
Calling this would convert all numbers less than or equal to `0.3` to a `0`:
```
>>> chop([1.0, 0.2, 0.4, 0.3, 0.31])
[1.0, 0, 0.4, 0, 0.31]
```
You should change the default value of `max` to something that suits your needs better, but you can always change it separately for individual calls too:
```
>>> chop([0.2, 0.3, 0.4], max=0.25)
[0, 0.3, 0.4]
>>> chop([0.3, 1, 2, 3], max=2)
[0, 0, 0, 3]
```
And if you want, you can convert negative numbers too! Either using the same distance from zero for both positive and negative numbers:
```
def chop(expr, *, max=0.3):
return [i if abs(i) > max else 0 for i in expr]
```
Or by using two different limits:
```
def chop(expr, *, max=0.3, min=-0.3):
if max < min:
raise ValueError
return [
i if i > max or i < min else 0
for i in expr
]
``` | One way to do that with numpy would be to use a masked array:
```
>>> import numpy
>>> def chop(expr, delta=10**-10):
... return numpy.ma.masked_inside(expr, -delta, delta).filled(0)
>>> x = numpy.fft.irfft(numpy.fft.rfft([2, 1, 1, 0, 0, 0]))
>>> x
array([ 2.00000000e+00, 1.00000000e+00, 1.00000000e+00,
3.20493781e-17, -4.44089210e-16, -3.20493781e-17])
>>> chop(x)
array([ 2., 1., 1., 0., 0., 0.])
```
If you really don't want to use numpy for some reason, then here's a function that works for scalar values, lists and multidimensional lists (matrices):
```
def chop(expr, delta=10**-10):
if isinstance(expr, (int, float, complex)):
return 0 if -delta <= expr <= delta else expr
else:
return [chop(x) for x in expr]
``` |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| I'd suggest that you save the normalized versions to your table in addition with the real username. Changing the encoding on the fly can be expensive, and you have to do the conversion again for every row on every search.
If you're using PHP, you can use [iconv()](http://fi.php.net/manual/en/function.iconv.php) to handle the conversion:
```
$username = 'rené';
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
Then you'd just save both versions and use the normalized version for searching and normal username for display. Comparing and selecting will be alot faster from the normalized column, provided that you normalize the search string also:
```
$search = mysql_real_escape_string(iconv('UTF-8', 'ASCII//TRANSLIT', $_GET['search']));
mysql_query("SELECT * FROM User WHERE normalized LIKE '%".$search."%'");
```
Of course this method might not be viable if you have several columns that need normalizations, but in your specific case this might work allright. | ```
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
is a perfect php solution, but in mysql? CONVERT?
in mysql
```
SELECT 'Álvaro José' as accented, (CONVERT ('Álvaro José' USING ascii)) as notaccented
```
Produce:
```
Álvaro José ?lvaro Jos?
```
The accented words is not converted to no accented words, it is not equivalent a translit of iconv.
RegExp don't work with UTF-8.
Not any solution. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| The reason for the error is not the table but the characterset of your input, i.e. the 'rené' in your query. The behaviour depends on the [character\_set\_connection](http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_character_set_connection) variable:
>
> The character set used for literals that do not have a character set introducer and for number-to-string conversion.
>
>
>
Using the MySQL Client, change it using `SET NAMES`:
>
> A SET NAMES 'charset\_name' statement is equivalent to these three statements:
>
>
>
```
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET character_set_connection = charset_name;
```
(from <http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html>)
Example output:
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
Altenatively, use can explicitly set the character set using a 'character set introducer':
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = _utf8'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
*I know this question is pretty old but since Google led me here for a related question, I though it still deserves an answer :)* | I'd suggest that you save the normalized versions to your table in addition with the real username. Changing the encoding on the fly can be expensive, and you have to do the conversion again for every row on every search.
If you're using PHP, you can use [iconv()](http://fi.php.net/manual/en/function.iconv.php) to handle the conversion:
```
$username = 'rené';
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
Then you'd just save both versions and use the normalized version for searching and normal username for display. Comparing and selecting will be alot faster from the normalized column, provided that you normalize the search string also:
```
$search = mysql_real_escape_string(iconv('UTF-8', 'ASCII//TRANSLIT', $_GET['search']));
mysql_query("SELECT * FROM User WHERE normalized LIKE '%".$search."%'");
```
Of course this method might not be viable if you have several columns that need normalizations, but in your specific case this might work allright. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| I'd suggest that you save the normalized versions to your table in addition with the real username. Changing the encoding on the fly can be expensive, and you have to do the conversion again for every row on every search.
If you're using PHP, you can use [iconv()](http://fi.php.net/manual/en/function.iconv.php) to handle the conversion:
```
$username = 'rené';
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
Then you'd just save both versions and use the normalized version for searching and normal username for display. Comparing and selecting will be alot faster from the normalized column, provided that you normalize the search string also:
```
$search = mysql_real_escape_string(iconv('UTF-8', 'ASCII//TRANSLIT', $_GET['search']));
mysql_query("SELECT * FROM User WHERE normalized LIKE '%".$search."%'");
```
Of course this method might not be viable if you have several columns that need normalizations, but in your specific case this might work allright. | Does a search using *English* characters return results with foreign characters?
I wrote the following script to compare collations in MySQL 5.7 (Should also work for MariaDB 10.2+):
```
$db->query('CREATE TABLE IF NOT EXISTS test (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_520_ci');
$db->query('CREATE TABLE IF NOT EXISTS test2 (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_ci');
$db->query("insert into test values('Łove 520')");
$db->query("insert into test2 values('Łove 520')");
$types = ['utf8mb4_unicode_520_ci', 'utf8mb4_unicode_ci'];
$tables = ['test' => 'utf8mb4_unicode_520_ci', 'test2' => 'utf8mb4_unicode_ci'];
foreach($types as $n)
{
foreach($tables as $ta => $tc)
{
$db->query("SET NAMES 'utf8mb4' COLLATE '$n'");
$res = $db->query("Select * from $ta where name like 'Love%'"); // Ł equal
echo "\ntable $ta($tc), names($n): ".$res->fetchColumn(0);
}
}
```
Here are the results:
```
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_520_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_520_ci):
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_ci):
```
(Note: I ran the script from the command line, so it appears as ┼üove 520 instead of Łove 520)
It appears that L == Ł when the table collation is utf8mb4\_unicode\_**520**\_ci, regardless of the connection collation. However, it is **not** equivalent if you only use utf8mb4\_unicode\_ci. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| I have implemented a strtr php function/tr unix command in MySQL you can get the source [here](https://github.com/falcacibar/mysql-routines-collection/blob/master/tr.func.sql)
You can use as:
```
SELECT tr(name, 'áäèëî', 'aaeei') FROM persons
```
or to strip some characters
```
SELECT tr(name, 'áäèëî', null) FROM persons
``` | ```
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
is a perfect php solution, but in mysql? CONVERT?
in mysql
```
SELECT 'Álvaro José' as accented, (CONVERT ('Álvaro José' USING ascii)) as notaccented
```
Produce:
```
Álvaro José ?lvaro Jos?
```
The accented words is not converted to no accented words, it is not equivalent a translit of iconv.
RegExp don't work with UTF-8.
Not any solution. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| The reason for the error is not the table but the characterset of your input, i.e. the 'rené' in your query. The behaviour depends on the [character\_set\_connection](http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_character_set_connection) variable:
>
> The character set used for literals that do not have a character set introducer and for number-to-string conversion.
>
>
>
Using the MySQL Client, change it using `SET NAMES`:
>
> A SET NAMES 'charset\_name' statement is equivalent to these three statements:
>
>
>
```
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET character_set_connection = charset_name;
```
(from <http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html>)
Example output:
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
Altenatively, use can explicitly set the character set using a 'character set introducer':
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = _utf8'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
*I know this question is pretty old but since Google led me here for a related question, I though it still deserves an answer :)* | ```
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
is a perfect php solution, but in mysql? CONVERT?
in mysql
```
SELECT 'Álvaro José' as accented, (CONVERT ('Álvaro José' USING ascii)) as notaccented
```
Produce:
```
Álvaro José ?lvaro Jos?
```
The accented words is not converted to no accented words, it is not equivalent a translit of iconv.
RegExp don't work with UTF-8.
Not any solution. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| ```
$normalized = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
```
is a perfect php solution, but in mysql? CONVERT?
in mysql
```
SELECT 'Álvaro José' as accented, (CONVERT ('Álvaro José' USING ascii)) as notaccented
```
Produce:
```
Álvaro José ?lvaro Jos?
```
The accented words is not converted to no accented words, it is not equivalent a translit of iconv.
RegExp don't work with UTF-8.
Not any solution. | Does a search using *English* characters return results with foreign characters?
I wrote the following script to compare collations in MySQL 5.7 (Should also work for MariaDB 10.2+):
```
$db->query('CREATE TABLE IF NOT EXISTS test (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_520_ci');
$db->query('CREATE TABLE IF NOT EXISTS test2 (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_ci');
$db->query("insert into test values('Łove 520')");
$db->query("insert into test2 values('Łove 520')");
$types = ['utf8mb4_unicode_520_ci', 'utf8mb4_unicode_ci'];
$tables = ['test' => 'utf8mb4_unicode_520_ci', 'test2' => 'utf8mb4_unicode_ci'];
foreach($types as $n)
{
foreach($tables as $ta => $tc)
{
$db->query("SET NAMES 'utf8mb4' COLLATE '$n'");
$res = $db->query("Select * from $ta where name like 'Love%'"); // Ł equal
echo "\ntable $ta($tc), names($n): ".$res->fetchColumn(0);
}
}
```
Here are the results:
```
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_520_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_520_ci):
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_ci):
```
(Note: I ran the script from the command line, so it appears as ┼üove 520 instead of Łove 520)
It appears that L == Ł when the table collation is utf8mb4\_unicode\_**520**\_ci, regardless of the connection collation. However, it is **not** equivalent if you only use utf8mb4\_unicode\_ci. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| The reason for the error is not the table but the characterset of your input, i.e. the 'rené' in your query. The behaviour depends on the [character\_set\_connection](http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_character_set_connection) variable:
>
> The character set used for literals that do not have a character set introducer and for number-to-string conversion.
>
>
>
Using the MySQL Client, change it using `SET NAMES`:
>
> A SET NAMES 'charset\_name' statement is equivalent to these three statements:
>
>
>
```
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET character_set_connection = charset_name;
```
(from <http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html>)
Example output:
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
Altenatively, use can explicitly set the character set using a 'character set introducer':
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = _utf8'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
*I know this question is pretty old but since Google led me here for a related question, I though it still deserves an answer :)* | I have implemented a strtr php function/tr unix command in MySQL you can get the source [here](https://github.com/falcacibar/mysql-routines-collection/blob/master/tr.func.sql)
You can use as:
```
SELECT tr(name, 'áäèëî', 'aaeei') FROM persons
```
or to strip some characters
```
SELECT tr(name, 'áäèëî', null) FROM persons
``` |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| I have implemented a strtr php function/tr unix command in MySQL you can get the source [here](https://github.com/falcacibar/mysql-routines-collection/blob/master/tr.func.sql)
You can use as:
```
SELECT tr(name, 'áäèëî', 'aaeei') FROM persons
```
or to strip some characters
```
SELECT tr(name, 'áäèëî', null) FROM persons
``` | Does a search using *English* characters return results with foreign characters?
I wrote the following script to compare collations in MySQL 5.7 (Should also work for MariaDB 10.2+):
```
$db->query('CREATE TABLE IF NOT EXISTS test (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_520_ci');
$db->query('CREATE TABLE IF NOT EXISTS test2 (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_ci');
$db->query("insert into test values('Łove 520')");
$db->query("insert into test2 values('Łove 520')");
$types = ['utf8mb4_unicode_520_ci', 'utf8mb4_unicode_ci'];
$tables = ['test' => 'utf8mb4_unicode_520_ci', 'test2' => 'utf8mb4_unicode_ci'];
foreach($types as $n)
{
foreach($tables as $ta => $tc)
{
$db->query("SET NAMES 'utf8mb4' COLLATE '$n'");
$res = $db->query("Select * from $ta where name like 'Love%'"); // Ł equal
echo "\ntable $ta($tc), names($n): ".$res->fetchColumn(0);
}
}
```
Here are the results:
```
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_520_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_520_ci):
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_ci):
```
(Note: I ran the script from the command line, so it appears as ┼üove 520 instead of Łove 520)
It appears that L == Ł when the table collation is utf8mb4\_unicode\_**520**\_ci, regardless of the connection collation. However, it is **not** equivalent if you only use utf8mb4\_unicode\_ci. |
2,302,813 | I'd like to be able to do queries that normalize accented characters, so that for example:
```
é, è, and ê
```
are all treated as 'e', in queries using '=' and 'like'. I have a row with username field set to '**rené**', and I'd like to be able to match on it with both '**rene**' and '**rené**'.
I'm attempting to do this with the 'collate' clause in MySQL 5.0.8. I get the following error:
```
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
```
FWIW, my table was created with:
```
CREATE TABLE `User` (
`id` bigint(19) NOT NULL auto_increment,
`username` varchar(32) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueUsername` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=56790 DEFAULT CHARSET=utf8
``` | 2010/02/20 | [
"https://Stackoverflow.com/questions/2302813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93995/"
]
| The reason for the error is not the table but the characterset of your input, i.e. the 'rené' in your query. The behaviour depends on the [character\_set\_connection](http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_character_set_connection) variable:
>
> The character set used for literals that do not have a character set introducer and for number-to-string conversion.
>
>
>
Using the MySQL Client, change it using `SET NAMES`:
>
> A SET NAMES 'charset\_name' statement is equivalent to these three statements:
>
>
>
```
SET character_set_client = charset_name;
SET character_set_results = charset_name;
SET character_set_connection = charset_name;
```
(from <http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html>)
Example output:
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'
mysql> set names utf8;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = 'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
Altenatively, use can explicitly set the character set using a 'character set introducer':
```
mysql> set names latin1;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from User where username = _utf8'rené' collate utf8_general_ci;
Empty set (0.00 sec)
```
*I know this question is pretty old but since Google led me here for a related question, I though it still deserves an answer :)* | Does a search using *English* characters return results with foreign characters?
I wrote the following script to compare collations in MySQL 5.7 (Should also work for MariaDB 10.2+):
```
$db->query('CREATE TABLE IF NOT EXISTS test (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_520_ci');
$db->query('CREATE TABLE IF NOT EXISTS test2 (name varchar(20))
Engine=InnoDB character set utf8mb4 collate utf8mb4_unicode_ci');
$db->query("insert into test values('Łove 520')");
$db->query("insert into test2 values('Łove 520')");
$types = ['utf8mb4_unicode_520_ci', 'utf8mb4_unicode_ci'];
$tables = ['test' => 'utf8mb4_unicode_520_ci', 'test2' => 'utf8mb4_unicode_ci'];
foreach($types as $n)
{
foreach($tables as $ta => $tc)
{
$db->query("SET NAMES 'utf8mb4' COLLATE '$n'");
$res = $db->query("Select * from $ta where name like 'Love%'"); // Ł equal
echo "\ntable $ta($tc), names($n): ".$res->fetchColumn(0);
}
}
```
Here are the results:
```
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_520_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_520_ci):
table test(utf8mb4_unicode_520_ci), names(utf8mb4_unicode_ci): Łove 520
table test2(utf8mb4_unicode_ci), names(utf8mb4_unicode_ci):
```
(Note: I ran the script from the command line, so it appears as ┼üove 520 instead of Łove 520)
It appears that L == Ł when the table collation is utf8mb4\_unicode\_**520**\_ci, regardless of the connection collation. However, it is **not** equivalent if you only use utf8mb4\_unicode\_ci. |
50,354,041 | I am trying to write a dictionary to a csv file in python.
I've tried nearly every tutorial that I could find but did not get a good result yet.
I want to later edit that file in excel but it looks like this right now:
[](https://i.stack.imgur.com/aElEH.png)
My python code:
```
s = file_name
dict = App.get_running_app().get_widget_contents()
with open(s, 'w') as f:
writer = csv.writer(f)
for row in dict.items():
writer.writerow(row)
```
>
> 1. What I need is that the key is in column A, and the values are in
> column B.
> 2. Furthermore each row should be used instead of every second
> row.
> 3. It would be nice to remove the "," between the key and the
> value.
>
>
>
I am very happy if someone could help me with this.
Greetings,
Finn | 2018/05/15 | [
"https://Stackoverflow.com/questions/50354041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4944986/"
]
| ```
s = file_name
dict = App.get_running_app().get_widget_contents()
with open(s, 'w') as f:
writer = csv.writer(f)
writer.writerow(dict.keys()) #Header
for row, value in dict.items():
writer.writerow(value) #Write Values
``` | you can go with
```
s = file_name
dict = App.get_running_app().get_widget_contents()
with open(s, 'w') as f:
writer = csv.writer(f)
for key in dict:
writer.writerow([key, dict[key]])
``` |
21,174,310 | So I seem to have run into a bit of a dead end. I'm making a page which has an image slider. The slider has three images, one centered on the screen, the other two overflow on the left and right. When you click on the button to advance the slides it runs this code....
```
$('#slideRight').click(function() {
if ($('.container').is(':animated')) {return false;}
var next=parseInt($('.container img:last-of-type').attr('id')) + 1;
if (next == 12) {
next = 0;
}
var diff = galsize() - 700;
if ($('.thumbs').css("left") == "0px") {
var plus = 78;
} else {
var plus = 0;
}
var app='<img id="' + next + '" src="' + imgs[next].src + '">';
$('.container').width('2800px').append(app);
$('.container').animate({marginLeft: (diff + plus) + "px"}, 300, function() {
$('.container img:first-of-type').remove();
$('.container').width('2100px').css("margin-left", (galsize() + plus) + "px");
});
}); // end right click
```
This works just fine, not a problem..... I also have an interval set up to run this automatically every 5 seconds to form a slideshow...
```
var slideShow = setInterval(function() {
$('#slideRight').trigger("click");
}, 5000);
```
This also works perfectly, not a problem.... However my problem is this.... I have thumbnails, when you click on a thumbnail, it should run this code until the current picture is the same as the thumbnail.... here is the code....
```
$('img.thumbnail').click(function() {
clearInterval(slideShow);
var src = $(this).attr("src");
while ($('.container img:eq(1)').attr('src') != src) {
$('#slideRight').trigger("click");
}
});
```
When I click on the thumbnail nothing happens... I've used alert statements to try and debug, what ends up happening is this....
The while loop executes, however nothing happens the first time. The slide is not advanced at all. Starting with the second execution, the is('::animated') is triggered EVERY TIME and the remainder of the slideRight event is not executed...
So my first problem, can anyone shed some light on why it doesn't run the first time?
And my second question, is there any way to wait until the animation is complete before continuing with the loop?
Any help would be appreciated. Thank you! | 2014/01/16 | [
"https://Stackoverflow.com/questions/21174310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3159369/"
]
| I'm going to start with the second part of your question, regarding completing the animation before continuing with the loop.
I have done something similar in the past, and what I did was set two global variables to control the animation. One variable is for how long you want the period to be, the other is a counter for how much time since the last loop.
So, for example:
```
$timeToChange = 5; // in Seconds
$timeSinceReset = 0; // also in Seconds
```
Set your interval for one second and call a new function (`autoAdvance()`):
```
var slideShow = setInterval(function() {
autoAdvance();
}, 1000); // only one second
```
and then use the counter variable to count each time the interval is called (each second). Something like:
```
function autoAdvance(){
if($timeSinceReset == $timeToChange){
$timeSinceReset = 0;
$('#slideRight').trigger("click"); // execute click if satisfied
}
else{$timeSinceReset++;}
}
```
To stop from looping until the animation is done, reset `$timeSinceReset` back to 0 (zero) when you click on the thumbnail. Something like:
```
$('#thumbnail').click(function(){
$timeSinceReset = 0;
});
```
That'll give you a nice 5 second buffer (or whatever you set `$timeToChange`) before the loop continues.
As for the first part of your question, grab the number of the particular thumbnail, and use that to scroll to the appropriate image. Something like:
```
$('.thumb').click(function (each) {
$childNumber = $(this).index();
});
```
which you cansee in [this fiddle](http://jsfiddle.net/3Pe73/1/). Click in one of the grey boxes and it'll tell you which one you clicked in. Use that info to scroll to the appropriate image (1, 2 or 3 if you only have three images).
Hope this helps. | Here is a full solution for one possible way of doing it at [this fiddle](http://jsfiddle.net/3Pe73/4/).
**HTML:**
The top container holds the images. In this particular example I've included three, using divs instead of images. Whether you use images or divs doesn't change anything.
```
<div class="holder_container">
<div class="img_container">
<div class="photo type1">ONE</div>
<div class="photo type2">TWO</div>
<div class="photo type3">THREE</div>
</div>
</div>
```
`.img_container` holds all the images, and is the same width as the sum of the widths of the images. In this case, each image (`.photo`) is 150px wide and 50px tall, so `.img_container` is 450px wide and 50px tall. `.holder_container` is the same dimensions as a single image. When this runs, the `.holder_container` is set to hide any overflow while `.img_container` moves its position left or right.
Included also are two nav buttons (forward and back)
```
<div class="nav_buttons">
<div class="nav back"><<<</div>
<div class="nav forward">>>></div>
</div>
```
As well as three thumbnail images - one for each image in the top container
```
<div class="top">
<div class="thumb"></div>
<div class="thumb"></div>
<div class="thumb"></div>
</div>
```
**CSS:**
Refer to the JS Fiddle for all CSS rules.
The most important are:
```
.holder_container {
margin: 0px;
padding: 0px;
height: 50px;
width: 150px;
position: relative;
overflow: hidden;
}
.img_container {
margin: 0px;
padding: 0px;
height: 50px;
width: 450px;
position: relative;
left: 0px;
top: 0px;
}
```
In the example, `.type1`, `.type2` and `.type3` are only used to color the image divs so you can see the animation. They can be left out of your code.
**JavaScript:**
The javascript contains the following elements…
Variables:
```
var timeToChange = 3; // period of the image change, in seconds
var timeSinceReset = 0; // how many seconds have passed since last image change
var currentImage = 1; // Which image you are currently viewing
var totalImages = 3; // How many images there are in total
```
Functions:
autoAdvance - called once every second via `setInterval`. Counts the number of seconds since the last image change. If the number of seconds that has passed is equal to the period, a function is called that switches the images.
```
function autoAdvance() {
if (timeSinceReset == timeToChange) {
timeSinceReset = 0;
moveNext();
} else {
timeSinceReset++;
}
}
```
moveNext() - moves to the next image. If the current image is the last (`currentImage == totalImages`) then `currentImages` is set back to 1 and the first image is displayed.
```
function moveNext(){
if(currentImage == totalImages){
currentImage = 1;
var newPos = 0 + 'px';
$('.img_container').animate({left: newPos}, 300);
}else{
currentImage++;
var newPos = -((currentImage-1) * 150) + 'px'; // child numbers are zero-based
$('.img_container').animate({left: newPos}, 300);
}
}
```
Rest of code:
If one of the thumbs is clicked, move to the corresponding image.
```
$('.thumb').click(function (each) {
timeSinceReset = 0;
var childNumber = $(this).index();
currentImage = childNumber + 1; // child numbers are zero-based
var newPos = -(childNumber * 150) + 'px'; // child numbers are zero-based
$('.img_container').animate({left: newPos}, 300);
});
```
If one of the navigation buttons is clicked, move accordingly. If "back" is clicked, move one image backwards (or to last image if currently on first). If "first" is clicked, move one image forwards (or to first image if currently on last).
```
$('.nav').click(function(){
timeSinceReset = 0;
if($(this).hasClass('back')){ // Back button
if(currentImage == 1){
currentImage = totalImages;
}else{
currentImage--;
}
}else{ // Forward button
if(currentImage == totalImages){
currentImage = 1;
}else{
currentImage++;
}
}
var newPos = -((currentImage-1) * 150) + 'px';
$('.img_container').animate({left: newPos}, 300);
});
```
Here is the [link](http://jsfiddle.net/3Pe73/4/) to the fiddle example. |
51,817 | Hope someone can help, can't find exactly my situation.
I have a Mackie proFx16 v3 which has 3 × 6.3 mm (pre fader switchable) Aux sends. (Well 4, but one of them is dedicated to Fx.)
My band is currently using 2 × active floor monitors – i.e. 2 monitor mixes, one fed from Aux send 1 and 1 fed from Aux send 2. All works fine, but there's the usual issues of too much noise on stage and occasional feedback issues.
We want to move to in-ear monitoring but still with 2 “mixes”, one shared by myself and a singer and another shared by 2 guitarists/singers. I'm planning on achieving this by buying 2 x SHURE PSM 300 in-ear monitoring systems, each with 2 bodypack receivers. So one for 1 mix shared by myself and vocalist (AUX 1) and the other shared by the 2 guitarist/singers (AUX 2) - hence 2 body pack receivers with each transmitter, which is not a problem.
The problem I cannot find a definitive answer to is the best way to hook up each PSM 300 transmitter to the mixing desk from the relevant Aux output – i.e. what cable? Each Aux send on the desk is just one 6.3 mm output, but there are 2 (combo xlr/jack) inputs on the back of the Shure PSM 300 transmitter, Left & Right. It would seem to me that as there are 2 inputs it would be best to use them both, but...
Would it be best to get a TRS jack to 2 × 6.3 mm jacks cable, or simply a mono jack to jack cable feeding just one input on the back of the PSM 300? (There's a note in the PSM300 manual which says: Important: When connecting to only one transmitter input, use the LEFT/CH1 input. Set the transmitter to MONO to hear audio on both channels)
I'm not sure whether the Aux output of the Mackie mixer is Stereo, Mono or balanced mono, and frankly whether it makes a difference in the real world. I don't need to hear “stereo” in the ear monitors, but do need the sound to come through both earpieces, not just one.
I've tried researching online and ended up going off at tangents detailing TRRS (rather than TRS) cables etc. which is just confusing me.
Any comments/suggestions very welcome! | 2022/10/13 | [
"https://sound.stackexchange.com/questions/51817",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/35984/"
]
| If you don't need stereo, connect one aux output to the left input and set the transmitter to mono. This is the most common configuration for a band sharing a limited number of monitor mixes.
Regarding TS (tip-sleeve) or TRS (tip-ring-sleeve) cables: in the live sound world, TRS cables with 1/4" connectors will usually carry a balanced mono signal or an unbalanced stereo signal (less common). A TS cable always carries an unbalanced signal.
The point of any balanced signal is RF (radio frequency) noise rejection. The importance of this noise rejection depends on the length of the cable, the amount of RF noise present, and the level of the signal. (Sound engineer joke: what do you call a long unbalanced cable? An antenna.)
If you have a long cable, lots of RF, or a weak signal (or any combination of these factors), you'll need a balanced run from output to input. For example: if you need to run a low-level (i.e. mic) signal 150 feet through a hostile RF environment, balanced connectors and cabling are a must. If you need to send a line-level (strong) signal a few feet, a balanced run is rarely necessary.
Your situation is the latter. Connect your aux output to the transmitter input with the shortest possible cable, and you should be fine with an unbalanced (TS) run. | Concerning the technical part of your question: having a look at the Mackie's product description, the Aux sends seem to be mono, but balanced (please verify).
The PSM300's product description mentions "Connector Type: 6.35 mm (1/4") TRS".
So that's fine: you can connect one of the PSM300s with 2 TRS cables, and the other one with 1 TRS cable (use the left input, which is de facto standard for mono).
The inherent musical aspect of your question: from my experience both as a musician and a mixing engineer, it is always better or at least useful to have a stereo signal. But you can try and then decide who of your band's members is going to use mono and who is taking stereo. |
31,150,565 | So i'm learning to create a java game on eclipse. I learned adding shapes and such. I also learned how to paint the shapes (change the colours) I was wondering how to add an image to the shape. This is the code for painting the rectangle.
```
public void paintColumn(Graphics g, Rectangle column)
{
g.setColor(Color.blue.darker());
g.fillRect(column.x, column.y, column.width, column.height);
}
``` | 2015/07/01 | [
"https://Stackoverflow.com/questions/31150565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4761936/"
]
| Start by having a look at [Reading/Loading an Image](http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html) for details about how to load a image, also, have a look at [2D Graphics](http://docs.oracle.com/javase/tutorial/2d/) for more details about 2D Graphics API.
Basically, you load the image, you draw it and then draw the shape around it.

```
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.drawImage(img, x, y, this);
g2d.setColor(Color.RED);
g2d.drawRect(x, y, img.getWidth(), img.getHeight());
g2d.dispose();
```
Now, this just draws the rectangle over the image, if you want to, somehow "frame" the image instead, you could fill the rectangle, making it larger then the image, but you'd have to fill first, then draw the image

```
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.setColor(Color.RED);
g2d.fillRect(x - 10, y - 10, img.getWidth() + 20, img.getHeight() + 20);
g2d.drawImage(img, x, y, this);
g2d.dispose();
``` | Simply create a BufferedImage object:
```
BufferedImage image = ImageIO.read(filename);
```
Then instead of doing g.drawShape do:
```
g.drawImage(image, [starting x], [starting y], [image width], [image height], [image observer]);
```
In your case, you probably won't need an image observer, so you can just put `null` in that spot.
Then what would be easiest is to just draw your rectangle on top of the image. Even though the image will not actually be "inside" the the rectangle, the layered effect will make it look as if it is. You can use `drawRect` instead of `fillRect` so you just get a border around your image.
To ensure that your rectangle ends up on top of the image, and doesn't get covered since the image is the same size, make sure to put the drawRect line **after** the drawImage.
```
g.drawRect([starting x], [starting y], [width], [height]);
```
Check out these [Graphics Java Docs](http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawImage(java.awt.Image,%20int,%20int,%20int,%20int,%20java.awt.image.ImageObserver)) for more information on drawing images. |
69,087,873 | I'm trying to build a simple web app using the MERN stack while following a course.
My backend runs on port 5000 while react runs on port 3000. When I want to make a request with the backend API, it sends it to port 3000 instead of 5000. I keep on getting this error message:
>
> xhr.js:178 POST http://localhost:3000/api/users 400 (Bad Request)
>
>
>
I included `"proxy" : "http://localhost:5000"` in my package.json. I tried replacing 'localhost' with 127.0.0.1. I tried deleting and reinstalling the package-lock.json and node\_modules folders. I tried removing the proxy and using the entire url. I tried installing http proxy middleware. I tried enabling CORS on the backend too.
Either I'm cursed or doing everything wrong.
I'm using axios for handling the requests, here's the code.
```
const config = {
headers: {
'Content-type': "application-json"
}
}
const body = JSON.stringify(newUser)
const res = await axios.post('/api/users', body, config)
console.log(res.data)
``` | 2021/09/07 | [
"https://Stackoverflow.com/questions/69087873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14116644/"
]
| I suggest considering usage of [`pickle`](https://docs.python.org/3/library/pickle.html) built-in module. You can use it following way for writing
```
import pickle
data = [1,(2,3)]
with open('save.p','wb') as f:
pickle.dump(data, f)
```
and following way for reading
```
import pickle
with open('save.p','rb') as f:
data = pickle.load(f)
print(data) # [1, (2, 3)]
```
Beware that `pickle` is not secure (read linked docs for more information). `pickle` is one of way of providing *persistent storage* if it doesn not suit your needs you might try searching for another method - look for *persistent storage python* | If you are wanting to write a python list to a txt file and then read it back in as a list you need to do something like this.
Write it with some delimiter.
```
with open("myfile.txt", "w") as f:
string1 = ",".join(map(str, LIST))
f.write(string1)
```
And then read it in and split it on that same delimiter.
```
with open("myfile.txt", "r") as f:
text = f.read()
my_list = text.split(',')
``` |
69,087,873 | I'm trying to build a simple web app using the MERN stack while following a course.
My backend runs on port 5000 while react runs on port 3000. When I want to make a request with the backend API, it sends it to port 3000 instead of 5000. I keep on getting this error message:
>
> xhr.js:178 POST http://localhost:3000/api/users 400 (Bad Request)
>
>
>
I included `"proxy" : "http://localhost:5000"` in my package.json. I tried replacing 'localhost' with 127.0.0.1. I tried deleting and reinstalling the package-lock.json and node\_modules folders. I tried removing the proxy and using the entire url. I tried installing http proxy middleware. I tried enabling CORS on the backend too.
Either I'm cursed or doing everything wrong.
I'm using axios for handling the requests, here's the code.
```
const config = {
headers: {
'Content-type': "application-json"
}
}
const body = JSON.stringify(newUser)
const res = await axios.post('/api/users', body, config)
console.log(res.data)
``` | 2021/09/07 | [
"https://Stackoverflow.com/questions/69087873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14116644/"
]
| As pickle is not secure you can use `json` format
```
dump/dumps: Serialize
load/loads: Deserialize
```
<https://docs.python.org/3/library/json.html>
Code:
```
>>> import json
>>> l = [1,2,3,4]
>>> with open("test.txt", "w") as fp:
... json.dump(l, fp)
...
>>> with open("test.txt", "r") as fp:
... b = json.load(fp)
...
>>> b
[1, 2, 3, 4]
``` | If you are wanting to write a python list to a txt file and then read it back in as a list you need to do something like this.
Write it with some delimiter.
```
with open("myfile.txt", "w") as f:
string1 = ",".join(map(str, LIST))
f.write(string1)
```
And then read it in and split it on that same delimiter.
```
with open("myfile.txt", "r") as f:
text = f.read()
my_list = text.split(',')
``` |
4,124,906 | >
> Bob tells his sister that if she thinks of a number with all its digits different and ordered in increasing order from left to right, and then multiplies the number she thought of by 9, he always knows how much the sum of the digits of the result of multiplication, although he does not know what number his sister thought.
> Decide if Bob is lying or telling the truth and explain why.
> Note: she thinks of a non-zero number.
>
>
>
The only useful thing that I found is that $9N=10N-N$, thus $9N=\overline{a\_1(a\_2-a\_1)(a\_3-a\_2)\cdots (a\_{n-1}-a\_{n-2})(a\_n-a\_{n-1}-1)(10-a\_n)}$, if $N=\overline{a\_1a\_2\cdots a\_n}$.
Could anyone help me? | 2021/05/02 | [
"https://math.stackexchange.com/questions/4124906",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/757330/"
]
| Writing $9n=10n-n$ is a good start. The idea then is to note that, since the digits are strictly increasing, it is easy to see how that subtraction must turn out. Indeed, in most places you are subtracting a number from one which is strictly greater. More precisely, other than in the units and the tens place we are subtracting $a\_i$ from $a\_{i+1}$, thereby producing the gap between $a\_{i+1}$ and $a\_i$. (using your notation) In the units place we are, of course, subtracting the final digit from $0$ which will require a simple carry.
Consider the gap sequence, pretending that the number begins with a $0$. Thus, if your starting number were $24578$ the gap sequence would be $\{2,2,1,2,1\}$. We remark that the partial sums of the gaps return the original digits. In particular, the sum of all the gaps is the final digit...let's call it $d$.
Then the digits in $9n=10n-n$ are precisely the digits in the gap sequence, save that the final one is lowered by $1$ and we append $10-d$. All that remains is to remark that the sum of the digits in that string is precisely $d-1+10-d=9$ and we are done.
Example: sticking with $n=24578$ we get $9n=221202$ as claimed.
Remark: the lowering of the penultimate gap and the appending of $10-d$ are the result of the obvious carry, when you try to subtract $d$ from $0$. Of course, if $n=0$ at the start, then there is no carry. In all other cases, there is always a carry at that stage (and no other). | >
> $9N=\overline{a\_1(a\_2-a\_1)(a\_3-a\_2)\cdots (a\_{n-1}-a\_{n-2})(a\_n-a\_{n-1}-1)(10-a\_n)}$
>
>
>
And that's it!
$a\_1 + (a\_2-a\_1) + (a\_3 -a\_2) \cdots (a\_{n-1}-a\_{n-2}) + (a\_n-a\_{n-1}-1) + (10-a\_n)=$
$ (a\_1 + a\_2 + a\_3 + ..... + a\_n) - (a\_1 + a\_2 + ...a\_{n-2}+a\_{n-1}+a\_n) + (-1+10) =$
$ 9$.
Always.
The only real issue is are these the *actual* digits of $9N$? And so long as 1) $a\_n \ne 0$ and 2) $a\_n- a\_{n-1} \ge 1$ and 3) we always have $a\_k > a\_{k-1}$-- then those will be the digits. If those are not the case then there will be some more borrowing involved in settling out the digits and those won't be the digits.
And that is why the condition that the digits are increasing order was stipulated. This assure those three conditions.
.....
(note if they are not increasing, say $n = 31$ then $9\times 31 = 10\times 30 -30 + 10 - 1 = 3\times 10^2 + (1-3 -1)\times 10 + (10-1)$ all right, but $\overline{a\_1(a\_2-a\_1 -1)(10 -a\_1)} = \overline{3(-3)9}$ isn't a legitimate number as we don't have $(a\_2 - a\_1) \ge 1$. so instead we have $9N = \overline{(a\_1-1)(10 + a\_2 -a\_1-1)(10-a\_2)}$ and the sum of the digits is $(a\_1 + a\_2) -(a\_1+a\_2) +(-1 +10 -1 + 10) = 18$.)
(Also note we don't need them distinct and increasing. If they repeat it's okay so long as they never decrease and the last digit is always higher than the second to last.)
====OLD ANSWER BELOW ======
If the original number is $N= d\_k 10^k + d\_{k-1} 10^{k-1} + ...... +d\_210^2 + d\_110 + d\_0$ (a $k+1$ digit number) then
$9N = 9d\_k 10^k + 9d\_{k-1} 10^{k-1} + ...... +9d\_210^2 + 9d\_110+9d\_0=$
$(10-1)d\_k10^k + (10-1)d\_{k-1} 10^{k-1} + ...... +(10-1)d\_2 10^2 + (10-1)d\_110 + (10-1)d\_0=$
$d\_k10^{k-1} + (d\_{k-1}-d\_k)10^k+ (d\_{k-2} - d\_{k-1})10^{k-1} + ..... + (d\_1-d\_2)10^2 +(d\_0-d\_1)10 -d\_0$.
Now here's the kicker. The digits are distinct and in increasing order (that is $d\_k < d\_{k-1} < ...< d\_2 < d\_1 < d\_0$). So each of the $9>d\_{m}-d\_{m-1} \ge 1$ and is therefore a single digit in itself. Except for the very last $-d\_0$. But we can "borrow" a $10$ for $(d\_0 - d\_1)10$ as $d\_0 - d\_1 \ge 1$.
So
$9N = d\_k10^{k-1} + (d\_{k-1}-d\_k)10^k+ (d\_{k-2} - d\_{k-1})10^{k-1} + ..... + (d\_1-d\_2)10^2 +(d\_0-d\_1-1)10+ (10 -d\_0)$
And that is a $k+2$ digit number with the digits: $d\_k, (d\_{k-1}-d\_k),(d\_{k-2} - d\_{k-1}),(d\_1-d\_2),(d\_0-d\_1-1),$ and $(10-d\_0)$.
So if we add up all the digits we get $d\_k+ (d\_{k-1}-d\_k)+(d\_{k-2} - d\_{k-1})+(d\_1-d\_2)+(d\_0-d\_1-1)+(10-d\_0)=9$.
(If the numbers weren't distinct and increasing we couldn't assure the sums of the digits would collapse so nicely. The "rule of $9$" assures the sum of the digits will be a multiple of $9$ but the strictly increasing nature of the digits assures a "single shift" and we can't get a higher multiple of $9$. Ex. $9\times 103 = 927$ and problem is the "shift" $(10-1)1\times 100 + (10-1)0\times 10 + (10-1)3 = 1\times 1000 + (0-1)100 + (3-0)10 -3=1\times 100 + (-1)100 + (2)10 + 7$ doesn't shift cleanly.)
(I suppose I should do the case where $k =0$ $N$ is a *one* digit number. But that's eas. $9\times d\_0 = 10d\_0 - d\_0 = (d\_0-1)10 + (10 -d\_0)$ and the sum of the digits is $(d\_0 -1)+(10-d\_0) = 9$.) |
35,011 | Ok, long story short, I'm currious how long it would take an agency to crack a 10-15 character winrar password. The file names in the archive are also scrambled including a word at the start and numbers and characters. Roughly, should I have reason to believe this could be cracked within a reasonable time frame? | 2013/04/29 | [
"https://security.stackexchange.com/questions/35011",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/25336/"
]
| There is some data [here](http://www.tomshardware.com/reviews/password-recovery-gpu,2945-8.html). WinRAR uses a custom [key derivation function](http://en.wikipedia.org/wiki/Key_derivation_function) which involves thousands of SHA-1 invocations. Apparently, with two good GPU, about 15000 passwords per second can be tried.
Then it depends, not on the *length* of your password, but on the way you produced it. It's not the length which makes the password strong, but the randomness. If your password is a sequence of 15 random characters, chosen uniformly and independently of each other, then it will resist forever. If it is a common English word which happens to be 15 characters long, then it is toast and will be recovered in a matter of seconds. | The answer is 42 of course.
In all seriousness, this question is unanswerable. There are many factors, including but not limited to the amount of hardware the attacker is willing to throw at you.
Your password is **weak** though, it's very predictable which is the bane of strong passwords. |
35,011 | Ok, long story short, I'm currious how long it would take an agency to crack a 10-15 character winrar password. The file names in the archive are also scrambled including a word at the start and numbers and characters. Roughly, should I have reason to believe this could be cracked within a reasonable time frame? | 2013/04/29 | [
"https://security.stackexchange.com/questions/35011",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/25336/"
]
| The answer is 42 of course.
In all seriousness, this question is unanswerable. There are many factors, including but not limited to the amount of hardware the attacker is willing to throw at you.
Your password is **weak** though, it's very predictable which is the bane of strong passwords. | As mentioned rar uses SHA-1 which is pretty strong. You can have a good comparison of different algorithms [here](http://www.gat3way.eu/index.php?mact=News,cntnt01,detail,0&cntnt01articleid=192&cntnt01returnid=15).
As you can see cracking rar is slower than WPA-PSK. |
35,011 | Ok, long story short, I'm currious how long it would take an agency to crack a 10-15 character winrar password. The file names in the archive are also scrambled including a word at the start and numbers and characters. Roughly, should I have reason to believe this could be cracked within a reasonable time frame? | 2013/04/29 | [
"https://security.stackexchange.com/questions/35011",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/25336/"
]
| There is some data [here](http://www.tomshardware.com/reviews/password-recovery-gpu,2945-8.html). WinRAR uses a custom [key derivation function](http://en.wikipedia.org/wiki/Key_derivation_function) which involves thousands of SHA-1 invocations. Apparently, with two good GPU, about 15000 passwords per second can be tried.
Then it depends, not on the *length* of your password, but on the way you produced it. It's not the length which makes the password strong, but the randomness. If your password is a sequence of 15 random characters, chosen uniformly and independently of each other, then it will resist forever. If it is a common English word which happens to be 15 characters long, then it is toast and will be recovered in a matter of seconds. | As mentioned rar uses SHA-1 which is pretty strong. You can have a good comparison of different algorithms [here](http://www.gat3way.eu/index.php?mact=News,cntnt01,detail,0&cntnt01articleid=192&cntnt01returnid=15).
As you can see cracking rar is slower than WPA-PSK. |
20,455,295 | I have an object within an object and want to create a restriction using one of the fields within the inner most object. Now i figured it could be achieved by doing something like:
... .add(Restrictions.eq("myObjectTwp.myObjectThree.myObjectsID", mySearchId)).list();
However this does not seem to work. However, I get no error message and instead it almost looks like this restriction has not been taken into account. | 2013/12/08 | [
"https://Stackoverflow.com/questions/20455295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1383163/"
]
| You are probably looking for [CONCAT() function](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat), and your custom parts of the sentence have to be enclosed in single quotes and have the desired spaces at the beginning and at the end:
```
SELECT CONCAT (
A.CUSTNAME,
' WHO IS HOLDING ',
A.ACCNAME,
' ACCOUNT ',
T.TRATYPE,
' THE AMOUNT ',
T.AMT,
' ON ',
T.t_DATE
)
FROM ACCOUNTHOLDER A
INNER JOIN TRANSACTION T ON T.ACCNO = A.ACCNO
WHERE CUSTNAME = 'JAMES BOND'
```
And your JOIN wasn't right either You either use the explicit way and add INNER JOIN and ON, or you separate your tables with commas and put the condition in the WHERE clause. | You need to use proper `join` syntax. In addition to the `on` clause, you need a `join` statement. In addition, what look like string constants should be in single quotes. And, the proper way to concatenate strings in MySQL is to use the `concat()` function, not vertical bars:
```
SELECT concat(A.CUSTNAME, ' WHO IS HOLDING ', A.ACCNAME, ' ACCOUNT ',
T.TRATYPE, ' THE AMOUNT ', T.AMT, ' ON ', T.t_DATE)
FROM ACCOUNTHOLDER A join
TRANSACTION T
ON T.ACCNO=A.ACCNO
WHERE CUSTNAME = 'JAMES BOND';
``` |
54,672,187 | I have many `varchar` YYYY-mm values in my table :
[](https://i.stack.imgur.com/OhtND.png)
But now I need days in Month from this.
>
> I need the result: 2018-04 -> 30 Days
>
>
>
So how I can achieve this?
I thank you in advance! | 2019/02/13 | [
"https://Stackoverflow.com/questions/54672187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10921131/"
]
| You can use `eomonth()`:
```
select day(eomonth(convert(date, yyyymm + '-01')))
```
[Here](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=4be2dbb3aa77fd7d0ef478bb414c6657) is a db<>fiddle for doubters. | In addition to Gordon's spot-on answer, here is another way to compute the number of days in the month:
```
SELECT
DATEDIFF(day,
TRY_CONVERT(datetime, date+'01'),
DATEADD(month, 1, TRY_CONVERT(datetime, date+'01')))
FROM yourTable;
```
[Demo
----](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=85778de39b61d8dfbf56d489503e1d61)
Actually, if you have a long term need for the number of days in each calendar month over some range, you might want to just create a calendar table with this fixed table. Then, you may join to it whenever you need it. |
54,672,187 | I have many `varchar` YYYY-mm values in my table :
[](https://i.stack.imgur.com/OhtND.png)
But now I need days in Month from this.
>
> I need the result: 2018-04 -> 30 Days
>
>
>
So how I can achieve this?
I thank you in advance! | 2019/02/13 | [
"https://Stackoverflow.com/questions/54672187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10921131/"
]
| You can use `eomonth()`:
```
select day(eomonth(convert(date, yyyymm + '-01')))
```
[Here](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=4be2dbb3aa77fd7d0ef478bb414c6657) is a db<>fiddle for doubters. | The eomonth() function does the job :) |
54,672,187 | I have many `varchar` YYYY-mm values in my table :
[](https://i.stack.imgur.com/OhtND.png)
But now I need days in Month from this.
>
> I need the result: 2018-04 -> 30 Days
>
>
>
So how I can achieve this?
I thank you in advance! | 2019/02/13 | [
"https://Stackoverflow.com/questions/54672187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10921131/"
]
| In addition to Gordon's spot-on answer, here is another way to compute the number of days in the month:
```
SELECT
DATEDIFF(day,
TRY_CONVERT(datetime, date+'01'),
DATEADD(month, 1, TRY_CONVERT(datetime, date+'01')))
FROM yourTable;
```
[Demo
----](https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=85778de39b61d8dfbf56d489503e1d61)
Actually, if you have a long term need for the number of days in each calendar month over some range, you might want to just create a calendar table with this fixed table. Then, you may join to it whenever you need it. | The eomonth() function does the job :) |
3,911,013 | Hey,
I'm saving a copy of all contacts in a database.
Upon launching, I want to check if there is a new contact in the address book in order to add it to my data base.
How to perform this check? I can't find the suitable logic to implement it. | 2010/10/12 | [
"https://Stackoverflow.com/questions/3911013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394868/"
]
| There's not an easy way to get "new contacts" in the address book. Instead you'll have to do something like this:
1. [Get an array of all the contacts in the address book](http://developer.apple.com/library/ios/documentation/AddressBook/Reference/ABPersonRef_iPhoneOS/Reference/reference.html#//apple_ref/c/func/ABAddressBookCopyArrayOfAllPeople).
2. Loop through the array and see if the contact is in your database. (**NOTE:** Record ids [can change](http://mattgemmell.com/2008/10/31/iphone-dev-tips-for-synced-contacts)!)
3. If you find a contact that is not in your database, add it.
It's probably also smart to store the [last modification date](http://developer.apple.com/library/ios/documentation/AddressBook/Reference/ABPersonRef_iPhoneOS/Reference/reference.html#//apple_ref/doc/c_ref/kABPersonModificationDateProperty) of the property and compare that with each record so you can know if something has changed on an existing record.
Finally, this could take a while depending on the number of contacts the user has. It's probably something you want to do without blocking the UI. (Another note: Address Book types are not thread safe. Keep this in mind if you're working in a background thread.)
While your app is running, you can register [address book change notification callback](http://tuvix.apple.com/library/ios/documentation/AddressBook/Reference/ABAddressBookRef_iPhoneOS/Reference/reference.html#//apple_ref/c/func/ABAddressBookRegisterExternalChangeCallback) to be alerted of changes that happen while your app is running. | A little easier way(don't need too much memory space):
1. Save your App's database lastest TimeStamp when you load data from AddressBook & total person count.
2. write a check function, and call it whenever you need it
3. check function : Get the latest modification date in all contacts, and get the total count right now, just compare the latest date with TimeStamp:
BOOL beNeedRefresh = NO;
if( latest > TimeStamp){
beNeedRefresh = YES;
}else if(addressbook count != your Database count){
beNeedRefresh = YES;
}
if(beNeedRefresh){
refresh your database !!!!
} |
15,510,466 | For example
```
class A
{
void f() {}
void g()
{
[this]() // Lambda capture this
{
f();
A* p = this;
[p]() // Workaround to let inner lambda capture this
{
p->f();
};
};
}
};
```
Any better way to capture this in the inner lambda? | 2013/03/19 | [
"https://Stackoverflow.com/questions/15510466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899020/"
]
| Just use `[=]`, this is implicitly captured. If you have other variables which you don't wanna capture by copy, then just capture `[this]`. | You could just re-capture `this`:
```
class A
{
void f() {}
void g()
{
[this]()
{
f();
[this]()
// ^^^^
{
f();
};
};
}
};
``` |
67,897,255 | I need to append the same list before every element in list
```py
list1 = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
```
*magic*
```py
list2 = ['barfoo', 'barfob', 'barfaz', 'barfunk']
``` | 2021/06/09 | [
"https://Stackoverflow.com/questions/67897255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16037285/"
]
| Simple, concatenation and list comprehension should do the job.
```
newList = [string+word for word in list1]
```
output
```
['barfoo', 'barfob', 'barfaz', 'barfunk']
``` | It would be a good idea to use comprehension for this
```
list2 = [string+i for i in list1]
``` |
1,401,248 | I have tried several ways to login to a website through java. I have used watij, HTMLunit etc. but due to not so familiar with any of these, I am not able to login successfully.
Can anyone tell me in detail how to login through java
To be more specific, I want to login to the ORKUT and want the pagesource of the page that comes after login. | 2009/09/09 | [
"https://Stackoverflow.com/questions/1401248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157027/"
]
| The answer depends on how the website attempts to authenticate you:
* Do you have to set a username and password in the HTTP headers (basic auth)?
* Or do you have to fill out and submit a form containing the username and password?
For either I would recommend commons-httpclient, although the latter screen-scraping approach is always messy to do programatically.
For basic authentication, take a look at httpclient's [Authentication Guide](http://hc.apache.org/httpclient-3.x/authentication.html).
For forms authentication, you'll need to check the HTML source of the page to understand
* The URL the form is submitted to
* What the names of the parameters to submit are
For help on how to submit a form in httpclient, take a look at [the documentation on the POST method](http://hc.apache.org/httpclient-3.x/methods/post.html).
The httpclient site also contains a [basic tutorial](http://hc.apache.org/httpclient-3.x/tutorial.html). | Why are you trying to login via Java, why not just use cURL? Is there something specific you're trying to accomplish? |
1,401,248 | I have tried several ways to login to a website through java. I have used watij, HTMLunit etc. but due to not so familiar with any of these, I am not able to login successfully.
Can anyone tell me in detail how to login through java
To be more specific, I want to login to the ORKUT and want the pagesource of the page that comes after login. | 2009/09/09 | [
"https://Stackoverflow.com/questions/1401248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157027/"
]
| Your best chances to do such things & survive in the real world web are with Selenium-RC.
Basically, what you will do is to remote-control your browser to do anything that you can do manually (except file uploads).
Many times, I have used this pattern:
1. Login with selenium
2. Take the cookies
3. Continue with my favourite HTTP library. | Why are you trying to login via Java, why not just use cURL? Is there something specific you're trying to accomplish? |
1,401,248 | I have tried several ways to login to a website through java. I have used watij, HTMLunit etc. but due to not so familiar with any of these, I am not able to login successfully.
Can anyone tell me in detail how to login through java
To be more specific, I want to login to the ORKUT and want the pagesource of the page that comes after login. | 2009/09/09 | [
"https://Stackoverflow.com/questions/1401248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157027/"
]
| The answer depends on how the website attempts to authenticate you:
* Do you have to set a username and password in the HTTP headers (basic auth)?
* Or do you have to fill out and submit a form containing the username and password?
For either I would recommend commons-httpclient, although the latter screen-scraping approach is always messy to do programatically.
For basic authentication, take a look at httpclient's [Authentication Guide](http://hc.apache.org/httpclient-3.x/authentication.html).
For forms authentication, you'll need to check the HTML source of the page to understand
* The URL the form is submitted to
* What the names of the parameters to submit are
For help on how to submit a form in httpclient, take a look at [the documentation on the POST method](http://hc.apache.org/httpclient-3.x/methods/post.html).
The httpclient site also contains a [basic tutorial](http://hc.apache.org/httpclient-3.x/tutorial.html). | Orkut uses Google auth to login. My suggestion is to use an HTTP debugger like Fiddler to watch the traffic during login. Probably, there are cookies and redirects that you need to replicate.
Generally,
1. Look at the login form, get the names of the name and password field and the action that the form posts to
2. Create a POST request to the action URL and pass in the name and password correctly (e.g. name=username&password=pwd)
3. Was this HTTPS (make sure to do that correctly)
4. If the response has a SET-COOKIE in the header, make sure to send that cookie on all subsequent requests
5. If the response has a redirect, then do a GET for the redirect, sending cookies if appropriate
6. (keep looping on #5 until you don't get a redirect)
The response you get at the end of this is the page source.
Take a look at this:
<http://code.google.com/apis/gdata/javadoc/com/google/gdata/client/http/AuthSubUtil.html>
<http://code.google.com/p/apex-google-data/source/browse/trunk/google_data_toolkit/src/classes/AuthSubUtil.cls>
Looks like google code for authenticating with their services. |
1,401,248 | I have tried several ways to login to a website through java. I have used watij, HTMLunit etc. but due to not so familiar with any of these, I am not able to login successfully.
Can anyone tell me in detail how to login through java
To be more specific, I want to login to the ORKUT and want the pagesource of the page that comes after login. | 2009/09/09 | [
"https://Stackoverflow.com/questions/1401248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157027/"
]
| Your best chances to do such things & survive in the real world web are with Selenium-RC.
Basically, what you will do is to remote-control your browser to do anything that you can do manually (except file uploads).
Many times, I have used this pattern:
1. Login with selenium
2. Take the cookies
3. Continue with my favourite HTTP library. | Orkut uses Google auth to login. My suggestion is to use an HTTP debugger like Fiddler to watch the traffic during login. Probably, there are cookies and redirects that you need to replicate.
Generally,
1. Look at the login form, get the names of the name and password field and the action that the form posts to
2. Create a POST request to the action URL and pass in the name and password correctly (e.g. name=username&password=pwd)
3. Was this HTTPS (make sure to do that correctly)
4. If the response has a SET-COOKIE in the header, make sure to send that cookie on all subsequent requests
5. If the response has a redirect, then do a GET for the redirect, sending cookies if appropriate
6. (keep looping on #5 until you don't get a redirect)
The response you get at the end of this is the page source.
Take a look at this:
<http://code.google.com/apis/gdata/javadoc/com/google/gdata/client/http/AuthSubUtil.html>
<http://code.google.com/p/apex-google-data/source/browse/trunk/google_data_toolkit/src/classes/AuthSubUtil.cls>
Looks like google code for authenticating with their services. |
5,008,744 | ```
<ul id="list">
</ul>
<input type="checkbox" id="item1" name="item one" />
<input type="checkbox" id="item2" name="item two" />
<input type="checkbox" id="item3" name="item three" />
<input type="checkbox" id="item4" name="item four" />
```
I need to add checked items to the `#list` as li's in this format:
```
<li class="CHECKBOX ID">CHECKBOX NAME</li>
```
Here's what I'm currently working on:
```
$('input[type=checkbox]').change(function () {
if($(this).is(':checked')){
var checkboxId = $(this).attr('id');
var checkboxName = $(this).attr('name');
$('#list').append('<li class="' + checkboxId + '">' + checkboxName + '</li>');
} else {
$('#list .' + checkboxId).remove();
}
```
When ever I work with javascript I always feel like I'm very inefficient. This also doesn't take into account boxes already set to check on page load... | 2011/02/15 | [
"https://Stackoverflow.com/questions/5008744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/149128/"
]
| What you should do is make a function, e.g. `toggleListCheckbox` and call that when the page loads and also on the event.
```
function toggleListCheckbox() {
if($(this).is(':checked')) {
var checkboxId = $(this).attr('id');
var checkboxName = $(this).attr('name');
$('#list').append('<li class="' + checkboxId + '">' + checkboxName + '</li>');
} else {
$('#list .' + checkboxId).remove();
}
}
$(document).ready(function () {
$('input[type=checkbox]').each(toggleListCheckbox).change(toggleListCheckbox);
}
``` | I'd have them on the page from the beginning, and then just show/hide them using the [`filter()`*(docs)*](http://api.jquery.com/filter/) method with `this.id` and the [`toggle()`*(docs)*](http://api.jquery.com/toggle/) method with `this.checked`, while placing the most recently clicked one at the bottom of the list using the [`appendTo()`*(docs)*](http://api.jquery.com/appendto/) method.
**Example:** <http://jsfiddle.net/NBQpM/3/>
*html*
```
<ul id="list">
<li class="item1">item one</li>
<li class="item2">item two</li>
<li class="item3">item three</li>
<li class="item4">item four</li>
</ul>
```
*js*
```
var listItems = $('#list li');
$('input[type=checkbox]').change(function() {
listItems.filter('.' + this.id).appendTo('#list').toggle(this.checked);
}).change();
```
This also triggers the [`change()`*(docs)*](http://api.jquery.com/change/) event on each element immediately after they've been assigned to set the initial state of the list items. |
26,796,171 | I'm letting users add a `UITextField` on top of their images like a caption.
I've designed it so that their images are all perfect squares according to their iPhone screen size. So on my iPhone 5S, it would be a 320x320 `UIImageView`. An iPhone 6 would be 375x375 `UIImageView`. Images posted by larger screen phones would be scaled down by the imageView when viewing in the smaller phone.
How do I setup a font size that will be relative to screen width?
I'm currently using:
```
[UIFont systemFontOfSize:16.0]
```
Would it be appropriate to use this?:
```
[UIFont systemFontOfSize:self.frame.size.width/20];
```
I'm not sure what point size actually represents in a font size. I've also found `[UIFont preferredFontForTextStyle:UIFontTextStyleBody];` but I'm not sure if this is what I'm looking for.
Thanks | 2014/11/07 | [
"https://Stackoverflow.com/questions/26796171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/339946/"
]
| No you can't stream it using the O365 REST API, you'll have to download the file first. | You could try HTTP progressive download mechanism that doesn't require full file to be downloaded prior to playback. The media player has to be capable of playing with buffered data. On most modern players that is supported. |
36,807,223 | We have implemented RTSP server on our MCU. For testing purpose we are using VLC media player as a client. We coded our MCU such a way that only after receiving PLAY command from client, MCU reads data from camera. And we are seeing MCU receives data from camera and streams thorugh RTSP. We could see data streaming from server through UDP on Wireshark. And Also Codec information getting dispalyed on VLC media player. But video doesn't get played in VLC.What could be the issue?
Below is our SDP file info
"v=0\r\ns=Unnamed\r\ni=N/A\r\nc=IN IP4 sumukha-PC\r\nt=0 0\r\na=tool:vlc 2.2.2\r\na=recvonly\r\na=type:broadcast\r\na=charset:UTF-8\r\na=control:rtsp://192.168.1.100:8555\r\nm=video 0 RTP/AVP 96\r\nb=RR:0\r\na=rtpmap:96 H264/90000\r\na=fmtp:96 packetization-mode=1\r\na=control:rtsp://192.168.1.100:8555/trackID=0\r\n\r\n");
Thanks,
Ck | 2016/04/23 | [
"https://Stackoverflow.com/questions/36807223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6243514/"
]
| The error message tells you what is going wrong:
>
> live555 error: no data received in 10s, aborting
>
>
>
The usual reasons for this are firewalls or NAT?
You can select the RTP over RTSP (TCP) option in the VLC preferences to verify this. If the stream works over TCP, UDP packets are being blocked somewhere. | I suggest using ffmpeg and ffplay to test your streaming from a RTSP source.
It is command line, but the information and logs are very helpful |
30,508,243 | I have a value to check in the list range
Example:
```
recipies = int(input("enter:"))
print(recipies)
interval =[]
for i in range(recipies):
x = (input().split())
interval.append(x)
print(interval)
agroup =int(input("enter:"))
print(agroup)
qali = []
for i in range(agroup):
x = (input().split())
qali.append(x)
print(qali)
for cmp in qali:
toa = cmp[1:]
Input:
4
1 4
3 10
2 6
5 8
3
1 5
2 2 6
3 1 10 9
Output:
3
4
2
```
Here i want to check weather the value of toa available in the interval if available i want to print how many times that value available in the given intervals,same way i want to check values in quali(list) | 2015/05/28 | [
"https://Stackoverflow.com/questions/30508243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2992226/"
]
| You can use following list comprehensions :
```
>>> f_list=[map(int,i.split(',')) for i in li]
>>> ['yes' if toa in range(i,j) else 'No' for i,j in f_list]
['yes', 'yes']
```
Fist you need to extract your ranges that it can be done with splitting your strings with `,` and convert to `int` with `map` function.
Then you can use a list comprehension like following to check the member-ship :
```
['yes' if toa in range(i,j) else 'No' for i,j in f_list]
```
But not that `range` will contains the `start` but not `end` if you dont want such things you need to increase your start when you want to create the range :
```
>>> ['yes' if toa in range(i+1,j) else 'No' for i,j in f_list]
['yes', 'No']
``` | You'll have to parse each string into a start and stop value (integers):
```
ranges = ['1,9', '2,10']
for start_stop in ranges:
start, stop = map(int, start_stop.split(','))
if toa in range(start, stop):
print('yes')
```
Instead of creating a new `range()` object you can just use comparison operators:
```
for start_stop in yourlist:
start, stop = map(int, start_stop.split(','))
if start <= toa < stop:
print('yes')
```
This'll be faster as you don't need to create an additional `range()` object.
You probably want to store those integers instead:
```
ranges = [[int(i) for i in start_stop.split(',')] for start_stop in ranges]
```
to not have to parse them each and every time.
If you need to do a lot of these tests, against a large number of intervals, consider using an [Interval Tree](http://en.wikipedia.org/wiki/Interval_tree) data structure instead. In an Interval Tree finding matching ranges (intervals) takes O(log N) time, vs. O(N) for the straight search. So for 10000 ranges to test against, it'll only take 100 steps to find all matches, vs 10000 steps using the straight search used above. |
57,427,048 | I am new to using react hooks api.
Earlier I used to distinguish container components and presentational components.
The project directory structure was according to this distinction.
Container components used to inject store state and action creators to the component through `props`.
With hooks I have been left clueless how the directory structure should be and whether the hooks should be injected to the component through props or simply imported inside the component.
Should there be a containers and components distinction.
The redux documentation which describes container and presentational components also doesn't seem to be updated for hooks.
Any relevant article or answer is welcome. | 2019/08/09 | [
"https://Stackoverflow.com/questions/57427048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5093536/"
]
| About the separation between container components and presentational components, Dan Abramov (working on ReactJs, co-author of Redux and Create React App) wrote this in [Presentational and Container Components](https://link.medium.com/50US3ylBB2) :
>
> Update from 2019: I wrote this article a long time ago and my views have since evolved. In particular, I don’t suggest splitting your components like this anymore. If you find it natural in your codebase, this pattern can be handy. But I’ve seen it enforced without any necessity and with almost dogmatic fervor far too many times. The main reason I found it useful was because it let me separate complex stateful logic from other aspects of the component. Hooks let me do the same thing without an arbitrary division. This text is left intact for historical reasons but don’t take it too seriously.
>
>
> | As user adel commented, there is now hook equivalents of `react-redux` stuff. To read redux state, instead of `connect`, you can use `useSelector`.
```
import { useSelector } from 'react-redux'
..
const somePieceOfData = useSelector( state => state.path.to.data )
```
About container components, you can still seperate your container, using `react-redux` hook stuff. There is nothing about that with `react-redux`. |
57,427,048 | I am new to using react hooks api.
Earlier I used to distinguish container components and presentational components.
The project directory structure was according to this distinction.
Container components used to inject store state and action creators to the component through `props`.
With hooks I have been left clueless how the directory structure should be and whether the hooks should be injected to the component through props or simply imported inside the component.
Should there be a containers and components distinction.
The redux documentation which describes container and presentational components also doesn't seem to be updated for hooks.
Any relevant article or answer is welcome. | 2019/08/09 | [
"https://Stackoverflow.com/questions/57427048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5093536/"
]
| About the separation between container components and presentational components, Dan Abramov (working on ReactJs, co-author of Redux and Create React App) wrote this in [Presentational and Container Components](https://link.medium.com/50US3ylBB2) :
>
> Update from 2019: I wrote this article a long time ago and my views have since evolved. In particular, I don’t suggest splitting your components like this anymore. If you find it natural in your codebase, this pattern can be handy. But I’ve seen it enforced without any necessity and with almost dogmatic fervor far too many times. The main reason I found it useful was because it let me separate complex stateful logic from other aspects of the component. Hooks let me do the same thing without an arbitrary division. This text is left intact for historical reasons but don’t take it too seriously.
>
>
> | I am also running into the same problem now and was looking for some nice resources in that , but here what I've reached:
There is no big need for the distinction now between UI and container components, you can use custom hooks for the same purpose and you will have fewer lines of code and more readable one. From what I've read (i didn't experiment this yet) but it should have better performance as using functional components including custom hooks inc the app performance.
Take a look at this :
<https://dev.to/jenc/discuss-react-hooks-and-life-after-the-container-component-pattern-5bn> |
245,958 | 1. A particular mass of helium is required to lift a particular weight. If the weight stays the same and the mass of helium is decreased can the same lift force be achieved by increasing the acceleration of the helium gas? Not to be an Einstein, but if I recall correctly, force = mass \* acceleration.
2. Also, can helium gas be accelerated by heating it or by cutting it with a fan like propeller?
3. Lastly, when do we all get a flying saucer? | 2016/03/28 | [
"https://physics.stackexchange.com/questions/245958",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/112603/"
]
| Normally when you speak of lifting by helium you are using the buoyancy of a balloon in the atmosphere. If you decrease the mass of helium you decrease the volume of the balloon. The lift capacity of a balloon is the difference between the weight of a balloon and the weight of the air it displaces. If you can lighten the envelope you can maintain that difference with a smaller balloon and maintain the lift capacity. The helium gas has no appreciable acceleration and there is no fan.
If you are doing something different to lift something with helium you will have to explain more clearly what it is. | Well, you could get more lift force out the helium by accelerating it. If the helium, let's say in a balloon, was initial moving upwards quickly and the object you're trying to lift was stationary, at some point the rope connecting them would go tight and at that point the rope will apply a downwards force on the helium slowing it and accelerating it downwards. The helium would apply an equal upwards force on the rope giving you extra lifting force.
You could test this experimentally fairly easily. Get a helium balloon, a string and a payload that is just a tiny bit too heavy for the balloon to lift. With the payload on the ground, pull the balloon down to ground level so that the string is slack then release the balloon. When the string goes tight the balloon should lift the payload off the ground but only very briefly. Once the balloon is done accelerating that force goes away.
The scenario described above is easier to picture with something denser and more streamlined moving upwards - say an arrow that's been shot up by a bow. The thing about helium is that it's got such a low density. This means that as soon as it's moving with any speed through air you are going to get substantial air resistance. Your rapidly moving mass of helium will end up exerting an upwards force on the surrounding air - not the desired result. |
30,739,144 | All:
Suppose I have two directives( dir1 and dir2) , which are both isolated scope. From some posts, I learnt that I need to use "require" to get scope of the other directive, but there is one question confused me so much:
Suppose I use ng-repeat generated a lot of dir1 and dir2, how do I know in certain dir1, which specific dir2's controller scope is required( cos there are many dir2 and in my understanding, all those scopes in dir2 controller are independent to each other)?
For example:
```
app.directive("dir1", function(){
var counter = 0;
return {
restrict:"AE",
scope:{},
template: "<button class='dir1_btn'>highlight dir2_"+(couter++)+" </button>",
link:function(scope, EL, attrs){
EL.find("button.dir1_btn").on("click", function(){
// How to let according dir2 know this click?
})
}
}
})
app.directive("dir2", function(){
var counter = 0;
return {
restrict:"AE",
scope:{},
template: "<span class='dir2_area'>This is dir2_"+(couter++)+" </span>",
link:function(scope, EL, attrs){
// Maybe put something here to listening the event passed from dir1?
}
}
})
```
And the html like( for simple purpose, I just put 2 of each there, actually it will generated by ng-repeat) :
```
<dir1></dir1>
<dir2></dir2>
<dir1></dir1>
<dir2></dir2>
```
Consider this just like the switch and light, dir1 is the switch to open(by change background-color) according light (dir2).
>
> In actual project, what I want to do is angularJS directive version
> sidemenu and scrollContent, each item in sidemenu is a directive,
> click it will make according content(another directive) to auto scroll
> to top.
>
>
>
I wonder how to do this? I know this is easy in jQuery, just wondering how to hook this into AngularJS data-driven pattern.
Thanks | 2015/06/09 | [
"https://Stackoverflow.com/questions/30739144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647559/"
]
| There's no hard rule, but sometimes you do have to do it. You will also need to do if you inherit from something or need the protocol declaration.
In general I would restate the rule as "use forward declarations of @class and @protocol whenever possible." | If you've read such a rule, that rule is wrong. You can include (and import, which is just a safer way of include) things into your header, if that's something required for the interface declaration. Otherwise save it for the implementation files. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.