date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19 | 1,674 | 3,941 | <issue_start>username_0: i have a `string code= "\0\u0001\0\0\0????\u0001\0\0\0\0\0\0\0\u000f\u0001\0\0\0\u001f\u0001\\ABC01\0\0\0\u001f\0\0\0\u0002\DEF\01\0\0\0\u001f\0\0\0\u0003\\\GHI01\0\0\0\u001f\0\0\0"`
i need to retrieve the data between u0001 and u0002 and u0002 and u0003 and so on.
Output as:
>
> ABC,DEF, GHI etc.
>
>
>
How i'm trying to achieve it :
```
code.Substring((code.IndexOf("\u000" + i) + ("\u000" + i).Length), code.IndexOf("\u000" + (i + 1)) - code.IndexOf("\u000" + i) - ("\u000" + i).Length));
```
This results in compilation error :
>
> Unrecognised escape sequence.
>
>
>
I have tried `code.IndexOf("\u0001")`, this works but not `code.IndexOf("\u000"+i)`.
How to solve?
EDIT: Many of you seem to have gotten the question wrong,so here is the complete code:
private static List RetriveMethod( )
```
{
input="\u0001\0\u0005\0\0\0\u0001\0\0\0\tMyMethod1\u0001\u001cfunction MyMethod1("there cud be another function by name function here" ) {\n\t\n\n}\0\0\0\0\u0002\0\0\0\tMyMethod2\u0001?\u0001function MyMethod2( ) { }\0\0\0\0\u0003\0\0\0\tMyMethod3\u0001Ofunction MyMethod3( )
List ExtactedMethods = new List();
for (int i = 0; i <= 3; i++)
{
ExtactedMethods.Add(code.Substring((code.IndexOf("\u000" + i) + ("\u000"
+ i).Length), code.IndexOf("\u000" + (i + 1)) -
code.IndexOf("\u000" + i) - ("\u000" + i).Length));
}
return ExtactedMethods;
}
```<issue_comment>username_1: `\u----` denotes Unicode character (hence the prefix `u`). `"\u000"` is invalid Unicode character and that causes compilation error.
If you want `\u` not to be treated as Unicode character, than escape `\` character
```
"\\u"
```
Suggested Fix by @Immersive to escape `\u` in source string
```
string code= @"\0\u0001\...."
```
Read more about [verbatim string literals](http://www.yoda.arachsys.com/csharp/strings.html)
Upvotes: 3 [selected_answer]<issue_comment>username_2: >
> Note: code.IndexOf ("\ u000" + i) does not work because you can not convert an integer to a string, and what IndexOf does is find the numeric position of that character in the string, instead you should try code.IndexOf ( "\ u000") + i where are you this is the correct way to add a value to the position (value returned by IndexOf), if that is your goal
>
>
> You can not use the backslash \ because it is an escape sequence character \ n \ r \ t, if you want to apply it, you must add two \\ where the IDE will interpret that the first is the escape sequence and the second the character to read
>
>
>
In any case, I have created this method that extracts the uppercase letters of your text string
```
public List GetUpperLetters(string input)
{
List result = new List();
int index\_0 = 0;
string accum = string.Empty;
//Convert string input to char collection
//and walk it one by one
foreach (char c in input.ToCharArray())
{
if(char.IsLetter(c) && char.IsUpper(c))
{
accum += c;
index\_0++;
if(index\_0 == 3)
{
index\_0 = 0;
result.Add(accum);
accum = string.Empty;
}
}
}
return result;
}
```
where
>
> GetUpperLetters(code)[index from zero to n]
>
>
>
```
string code= "\0\u0001\0\0\0????\u0001\0\0\0\0\0\0\0\u000f\u0001\0\0\0\u001f\u0001\\ABC01\0\0\0\u001f\0\0\0\u0002\DEF\01\0\0\0\u001f\0\0\0\u0003\\\GHI01\0\0\0\u001f\0\0\0";
GetUpperLetters(code)[0] returns ABC
GetUpperLetters(code)[1] returns DEF
GetUpperLetters(code)[2] returns GHI
```
Upvotes: 1 <issue_comment>username_3: Thanks a lot all of you for the suggested answers.
The one by @Immersive worked!
The change to be done is string code= @"\0\u0001\0\0\0????\u0001\0\0\0\0\0\0\0\u000f\u0001\0\0\0\u001f\u0001\ABC01\0\0\0\u001f\0\0\0\u0002\DEF\01\0\0\0\u001f\0\0\0\u0003\\GHI01\0\0\0\u001f\0\0\0"
and
code.Substring((code.IndexOf(@"\u000" + i) + (@"\u000" + i).Length), code.IndexOf(@"\u000" + (i + 1)) - code.IndexOf(@"\u000" + i) - (@"\u000" + i).Length));
Upvotes: 0 |
2018/03/19 | 689 | 3,211 | <issue_start>username_0: I have a swarm robotic project. The localization system is done using ultrasonic and infrared transmitters/receivers. The accuracy is +-7 cm. I was able to do follow the leader algorithm. However, i was wondering why do i still have to use Kalman filter if the sensors raw data are good? what will it improve? isn't just will delay the coordinate being sent to the robots (the coordinates won't be updated instantly as it will take time to do the kalman filter math as each robot send its coordinates 4 times a second)<issue_comment>username_1: In general, Kalman filter helps to improve sensor accuracy by summing (with right coefficients) measurement (sensor output) and prediction for the sensor output. Prediction is the hardest part, because you need to create model that predicts in some way sensors' output. And I think in your case it is unnecessary to spend time creating this model.
Upvotes: 0 <issue_comment>username_2: Sensor data is **NEVER** the truth, no matter how good they are. They will always be perturbed by some noise. Additionally, they do have finite precision. So sensor data is nothing but an *observation* that you make, and what you want to do is estimate the *true state* based on these observations. In mathematical terms, you want to estimate a likelihood or joint probability based on those measurements. You can do that using different tools depending on the context. One such tool is the Kalman filter, which in the simplest case is just a moving average, but is usually used in conjunction with dynamic models and some assumptions on error/state distributions in order to be useful. The dynamic models model the state propagation (*e.g* motion knowing previous states) and the observation (measurements), and in robotics/SLAM one often assumes the error is Gaussian. A very important and useful product of such filters is an estimation of the uncertainty in terms of covariances.
Now, what are the potential improvements? Basically, you make sure that your sensor measurements are coherent with a mathematical model and that they are "smooth". For example, if you want to estimate the position of a moving vehicle, the kinematic equations will tell you where you expect the vehicle to be, and you have an associated covariance. Your measurements also come with a covariance. So, if you get measurements that have low certainty, you will end up trusting the mathematical model instead of trusting the measurements, and vice-versa.
Finally, if you are worried about the delay... Note that the complexity of a standard extended Kalman filter is roughly `O(N^3)` where `N` is the number of landmarks. So if you really don't have enough computational power you can just reduce the state to `pose, velocity` and then the overhead will be negligible.
Upvotes: 2 <issue_comment>username_3: Although you are getting accurate data from sensors but they cannot be consistent always. The Kalman filter will not only identify any outliers in the measurement data but also can predict it when some measurement is missing. However, if you are really looking for something with less computational requirements then you can go for a complimentary filter.
Upvotes: 0 |
2018/03/19 | 373 | 1,386 | <issue_start>username_0: Code:
```
import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.navCtrl.push('home');
}
}
```
First upon I removed many codes so login page is working properly. By using the same method I am redirecting the user to activation page that also working well but it not redirecting to homepage. How can I resolve this issue?<issue_comment>username_1: You need to import Component to which you are redirecting your page then you can do something like this to redirect or you can use any method if you want like after login button is hit choice is yours
```
import { Component } from '@angular/core';
import { IonicPage, NavController } from 'ionic-angular';
import { HomeComponent } from 'your path to Home Component Page';
@IonicPage()
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
constructor(public navCtrl: NavController, public navParams:
NavParams) {
this.navCtrl.push(HomeComponent);
}
}
```
Upvotes: 1 <issue_comment>username_2: you have to import your home path into login.ts and app.module.ts
```
import { home} from 'your path of home';
```
Upvotes: 0 |
2018/03/19 | 955 | 2,933 | <issue_start>username_0: I'm using AzCopy to copy a file from local server to Azure and coming up with the following failed operation is the command is run from a batch file. If the same command is run from the command prompt the operation is successful.
---
Run from a batch file - fails:
==============================
C:\ftp>AzCopy /Source:C:\ftp\ /Dest:"<https://companystrg01.file.core.wind>
ows.net/bss?sv=2016-05-31&si=bss-supersecretstring" /S
Incomplete operation with same command line detected at the journal directory "C
:\Users\Administrator\AppData\Local\Microsoft\Azure\AzCopy", do you want to resume the operation?
Choose Yes to resume, choose No to overwrite the journal to start a new operation. (Yes/No) y
[2018/03/19 13:50:22][ERROR] C:\ftp\board\file.TXT: The transfer fail
ed.
The remote server returned an error: (403) Forbidden.
HttpStatusMessage:Server failed to authenticate the request. Make sure the value
of Authorization header is formed correctly including the signature.
RequestId:
Time:Mon, 19 Mar 2018 03:50:05 GMT
Finished 0 of total 1 file(s).
[2018/03/19 13:50:22] Transfer summary:
Total files transferred: 1
Transfer successfully: 0
Transfer skipped: 0
Transfer failed: 1
Elapsed time: 00.00:00:04
================================
Run form a command line - succeeds:
===================================
C:\ftp>AzCopy /Source:C:\ftp\ /Dest:"<https://companystrg01.file.core.wind>
ows.net/bss?sv=2016-05-31&si=bss-supersecretstring" /S
[2018/03/19 13:56:57][WARNING] The command line "AzCopy /Source:C:\ftp\board\ /D
est:"<https://companystrg01.file.core.windows.net/bss?sv=2016-05-31&si=bss-supersecretstring>" /S" in the journal file "C:\Users\Administrator\AppData\
Local\Microsoft\Azure\AzCopy\AzCopy.jnl" is different from your input.
[2018/03/19 13:56:57][WARNING] Incomplete operation with different command line
detected at the journal directory "C:\Users\Administrator\AppData\Local\Microsof
t\Azure\AzCopy".
Do you want to overwrite the journal to start a new operation? Choose Yes to overwrite, choose No to cancel current operation. (Yes/No) y
Overwrite <https://companystrg01.file.core.windows.net/bss/file.TXT> w
ith C:\ftp\board\file.TXT? (Yes/No/All) y
Finished 1 of total 1 file(s).
[2018/03/19 13:57:06] Transfer summary:
Total files transferred: 1
Transfer successfully: 1
Transfer skipped: 0
Transfer failed: 0
Elapsed time: 00.00:00:09
C:\ftp>
---
I would appreciate some guidance.
Thank you.<issue_comment>username_1: You need to escape the special characters in your batch file. See a similar question here: [Batch character escaping](https://stackoverflow.com/questions/6828751/batch-character-escaping)
Upvotes: 4 [selected_answer]<issue_comment>username_2: Simply escape % sign with %% in your SAS token even if it is wrapped within ""!
Upvotes: 2 <issue_comment>username_3: Now it's not necessary to escape sign % on Windows OS.
Upvotes: 0 |
2018/03/19 | 742 | 2,712 | <issue_start>username_0: I have some Git-related doubt.
I have done some changes from master branch and by mistake I have commited to master branch. I did:
```
git add.
git commit "my changed"
```
But I could not push to the master branch due to some issues. So I have created another branch and from that branch I did push. But I was getting conflicts.
So my doubts are:
1. If I created a new branch again from master whether I will have all committed changes from the master?
2. What step do I need to follow to fix this conflict?
3. What do I need to do to make my master branch as same as server?
4. If I clone the project again, will it have my committed changes or same as server?
Can I do like? Clone again the master, checkout to the branch I got conflict,
do:
```
git merge master
```
From there and fix the conflicts?<issue_comment>username_1: 1. If i created a new branch again from master whether i will have all
committed changes from the master?
>
> Yes
>
>
>
2. What step i need to follow to fix this conflict?
>
> EIther rebase/merge your branch withh/into master and resolve the
> conflicts using
>
>
>
```
git rebase origin/master
git merge origin/master
```
3. What i need to do to make my master branch as same as server?
>
> Reset the branch with master using
>
>
>
```
git reset --hard origin/master
```
4. if i clone the project again , will it have my commiitted changes or
same as server?
>
> Yes
>
>
>
To conclude, in order to resolve your problems on the branch currently, you should do the following
```
git checkout branchA
git merge origin/master // resolve conflicts here
git commit
git push
```
Upvotes: 0 <issue_comment>username_2: 1. Just hit `git log` to find if you have all commits from master if your HEAD is ahead or at same level as master which means you have all commits from master (or) If you have created a branch from master
`git checkout master`
`git checkout -b new-branch`
then YES.
2. When you have conflicts you have to resolve using
`git mergetool`
Check `git status` whether you have resolved your conflicts
3. If you want to get local master reset to remote master branch
`git checkout -B master origin/master`
4. If you had pushed the commit on other branch instead of master, it will be on the remote other branch not on origin/master.
So when you are pushing new changes to remote custom branch,
`git fetch origin master`
`git checkout custom-branch`
`git rebase -i origin/master`
`git commit -m 'Your new feature stuff'`
`git push origin custom-branch`
This will only push to remote custom-branch not to master.
Create a merge request for merging to remote master.
Upvotes: 1 |
2018/03/19 | 615 | 1,988 | <issue_start>username_0: I'm using Laravel 5.5 and have a question about routing.
My route is like this
```
Route::get('/folder/{param}', 'PageController@getFolderTree');
```
And I want to get all parameters after /folder/:
<http://example.com/folder/com/example/app> -> I get /example/app
How can it possible ?<issue_comment>username_1: You can `explode` the URL. For example:
```
$url = 'http://example.com/folder/com/example/app';
$explodedText = explode('/folder/', $url);
$textBeforeFolder = $explodedText[0];
$textAfterFolder = $explodedText[1]; // This is the one you want
```
Upvotes: 0 <issue_comment>username_2: ```
request->url() //will return the whole url
```
and
```
request()->uri() //will return the URI
```
Now if you want to access the full URL u can access
```
request()-fullUrl() //will return the full url
```
Now you can use `str_replace()`
```
str_replace(request()->url.'folder/com/','', request->fullUrl());
//it will return example/app
```
Upvotes: 0 <issue_comment>username_3: If you know in advance what the maximum number of parameters will be you can do one of the next 2.
a) If [all are neccessery](https://laravel.com/docs/5.6/routing#required-parameters):
```
Route::get('/folder/{a}/{b}/{c}', 'PageController@getFolderTree');
```
b) If [not all are neccessery](https://laravel.com/docs/5.6/routing#parameters-optional-parameters):
```
Route::get('/folder/{a?}/{b?}/{c?}', 'PageController@getFolderTree');
```
And retrieve them like this:
```
public function getFolderTree($a, $b, $c) {...}
```
And if you don't know the maximum you will need to do a regex and explode. This would be the route:
```
Route::get('/folder/{any}', 'PageController@getFolderTree')
->where('any', '.*'); // Indicates that {any} can be anything
```
And do the explode in the controller:
```
public function getFolderTree($any) {
{
$params = explode('/', $any); // $params will be an array of params
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 3,220 | 11,392 | <issue_start>username_0: I just cannot figure out how to get the result I'm looking for. Here's my code
```
import java.util.Scanner;
public class StringInABox
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String Phrase = scan.nextLine();
String CapPhrase = Phrase.toUpperCase();
int PhraseLength = CapPhrase.length();
String SidePhrase = CapPhrase.substring(1);
int SidePhraseL = SidePhrase.length()-1;
for (int Letter = 0; Letter=0; Letters--)
{ for (int Space=0; Space <= PhraseLength\*2-3;Space++)
System.out.print(" ");
System.out.println(SidePhrase.charAt(Letters));}
for (int Letter = PhraseLength-1; Letter>=0; Letter--)
System.out.print(CapPhrase.charAt(Letter)+" ");
}
}
```
The result is supposed to be something like:
```
H E L P
E L
L E
P L E H
```
But I can only get:
```
H E L P
E
L
L
E
P L E H
```
I've run out of ideas. I'm a beginner and this shouldn't take advanced coding.<issue_comment>username_1: You're quite close but the problem here is the order of the `for` loops. To get the required output as follows:
```
E L
L E
```
You need to print both of these characters in the same loop i.e. when it's printing on the same line. So you need the `IndexFromFront` and `IndexFromBack` variables which store the value of `E` and `L` respectively.
After your initial loop to print the characters `H E L P`
```
for (int Letter = 0; Letter < PhraseLength; Letter++)
System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();
```
You need to start from the `first` index i.e. `1` to access `E` and the value of `IndexFromBack` would be `PhraseLength-1-(IndexFromFront)`. Now that you have the indices of the values that you'd have to print from the original string, you need to get the right spacing i.e. `2*(PhraseLength-1)-1` because you have a space after each character. So your second loop to print the lines
```
E L
L E
```
should be as follows:
```
for (int Letter = 1; Letter < PhraseLength-1; Letter++) {
int IndexFromFront = Letter;
int IndexFromBack = PhraseLength-1-Letter;
// Print character from the start of string at given Index
System.out.print(CapPhrase.charAt(IndexFromFront));
// Print required spaces
for (int Space = 0; Space < 2*(PhraseLength-1)-1; Space++) {
System.out.print(" ");
}
// End space print
// Print character from the end of string matching the required index
System.out.print(CapPhrase.charAt(IndexFromBack));
// Printing on this line is complete, so print a new line.
System.out.println();
}
```
and the final line i.e. reverse of given input string can be printed using the loop as follows:
```
for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
System.out.print(CapPhrase.charAt(Letter) + " ");
}
```
Therefore the final code that you'd have is as follows:
```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String Phrase = scan.nextLine();
String CapPhrase = Phrase.toUpperCase();
int PhraseLength = CapPhrase.length();
for (int Letter = 0; Letter < PhraseLength; Letter++)
System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();
for (int Letter = 1; Letter < PhraseLength - 1; Letter++) {
int IndexFromFront = Letter;
int IndexFromBack = PhraseLength - 1 - Letter;
System.out.print(CapPhrase.charAt(IndexFromFront));
// Print required spaces
for (int Space = 0; Space < 2 * (PhraseLength - 1) - 1; Space++) {
System.out.print(" ");
}
// End space print
System.out.print(CapPhrase.charAt(IndexFromBack));
System.out.println();
}
for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
System.out.print(CapPhrase.charAt(Letter) + " ");
}
}
```
Here's a sample output for `HELPINGYOUOUT`
```
Enter a phrase or word!
H E L P I N G Y O U O U T
E U
L O
P U
I O
N Y
G G
Y N
O I
U P
O L
U E
T U O U O Y G N I P L E H
```
---
**Edit:** More readable code
```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
public static void printSpaces(int phraseLength) {
for (int space = 0; space < 2 * (phraseLength - 1) - 1; space++) {
System.out.print(" ");
}
}
public static void printTopRow(String capPhrase, int phraseLength) {
for (int letter = 0; letter < phraseLength; letter++)
System.out.print(capPhrase.charAt(letter) + " ");
System.out.println();
}
public static void printIntermediateBoxRows(String capPhrase, int phraseLength) {
for (int letter = 1; letter < phraseLength - 1; letter++) {
int indexFromFront = letter;
int indexFromBack = phraseLength - 1 - letter;
System.out.print(capPhrase.charAt(indexFromFront));
// Print required spaces
printSpaces(phraseLength);
// End space print
System.out.print(capPhrase.charAt(indexFromBack));
System.out.println();
}
}
public static void printLastRow(String capPhrase, int phraseLength) {
for (int letter = phraseLength - 1; letter >= 0; letter--)
System.out.print(capPhrase.charAt(letter) + " ");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String phrase = scan.nextLine();
String capPhrase = phrase.toUpperCase();
int phraseLength = capPhrase.length();
// Print the box
printTopRow(capPhrase, phraseLength);
printIntermediateBoxRows(capPhrase, phraseLength);
printLastRow(capPhrase, phraseLength);
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: An incredibly helpful tactic for solving tricky problems is to map/draw/record everything that's changing and search for patterns. So we'll start by doing just that. For simplicity of tracking values I'll show the process in an array.
```
String keyword = "test"
```
Result will look something like this.
```
[t][e][s][t]
[e][ ][ ][s]
[s][ ][ ][e]
[t][s][e][t]
```
The first row is equal to the string but we'll replace the letters with values corresponding to the index of the character in the string. `Space` will be equal to `0`.
```
[1][2][3][1]
[2][0][0][3]
[3][0][0][2]
[1][3][2][1]
```
If we take these values and put them into one line we would end up with
```
1231200330021321
1231 2003 3002 1321 //Easier to read version
```
The first and last line are reversed and the second and third line are reversed. Thus, we can produce the output with three index counters. Each index counter is referencing a character within the original string
The first index counter will be for the full string to be read forward and backwards.
```
[t][e][s][t] //From 0 -> (keyword.length-1)
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[t][s][e][t] //From (keyword.length-1) -> 0
```
The second counter will be used to index up on the left side and the third counter will be used to index down on the right side.
```
[ ][ ][ ][ ] //Be aware of possible out of bounds index errors
[e][ ][ ][s] //From 1 -> (keyword.length-2)
[s][ ][ ][e] //From (keyword.length-2) -> 1
[ ][ ][ ][ ]
```
Upvotes: 0 <issue_comment>username_3: here's my answer. i've re-named things according to java naming standards, addressed the memory leak (Scanner wasn't closed), used methods as one does, and addressed the fact that the word phrase implies that there could be words with spaces in between.
```
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter a phrase or word!");
String phrase = scan.nextLine();
phrase = phrase.toUpperCase();
phrase = cleanUpWordBoundaries(phrase);
for (int letter = 0; letter < phrase.length(); letter++) {
System.out.print(phrase.charAt(letter) + " ");
}
System.out.println();
printSidePhrase(phrase);
for (int letter = phrase.length() - 1; letter >= 0; letter--) {
System.out.print(phrase.charAt(letter) + " ");
}
}
}
private static void printSidePhrase(String phrase) {
int startIndex = 1;
int lastIndex = phrase.length() - 2;
for (int letter = 1; letter < phrase.length() - 1; letter++) {
System.out.print(phrase.charAt(startIndex));
// print spaces
for (int i = 0; i < (phrase.length() - 2); i++) {
System.out.print(" ");
}
System.out.print(" " + phrase.charAt(lastIndex));
System.out.println();
startIndex++;
lastIndex--;
}
}
private static String cleanUpWordBoundaries(String phrase) {
String[] theWords = phrase.split("\\b");
String newPhrase = new String();
for (int i = 0; i < theWords.length; i++) {
newPhrase += theWords[i];
i++;
}
return newPhrase;
}
```
from running the program:
```
Enter a phrase or word!
w00 h00 bandit
W 0 0 H 0 0 B A N D I T
0 I
0 D
H N
0 A
0 B
B 0
A 0
N H
D 0
I 0
T I D N A B 0 0 H 0 0 W
```
Upvotes: 0 <issue_comment>username_4: I'm so lucky to answer your question! Attention! The key of the problem is that The cursor only go to next line,it won't go back previous line.
When the second loop end,the result is as follow:
```
H E L P
E
L
```
The print of the thirdly loop begins at line 4, So the print results of next line is as follow:
```
H E L P
E
L
L
```
I have coded the code as follow:
```
Scanner s = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String pharase = s.nextLine().toUpperCase();
int length = pharase.length();
char[] strArr = pharase.toCharArray();
for (int row = 0; row <= length-1 ; row++) {
for (int column = 0; column <= length -1 ; column++) {
System.out.print(row>0&&row0&&column
```
the result of input "youarehandsome":
```
Y O U A R E H A N D S O M E
O M
U O
A S
R D
E N
H A
A H
N E
D R
S A
O U
M O
E M O S D N A H E R A U O Y
```
Upvotes: 0 |
2018/03/19 | 3,105 | 11,228 | <issue_start>username_0: I am new to Material Design, and I have been reading about CardView. I am changing my app's layout and trying to use more of the Material Design Guidelines in it. According to Google, "Cards provide context and an entry point to more robust information and views," this is the layout that I came up with. Sorry that it's in Russian.

On the top is a card with a search bar, and below that is a card with radio buttons that let you choose whether you want to sort your results alphabetically or numerically. Below that is gonna be a list of search results.
I really like this design, but I don't think this is the right implementation of CardViews, since it's not an entry point to more robust information, but I just used them to group thing.
Please let me know whether this layout/theme is good according to Material Design Guidelines.<issue_comment>username_1: You're quite close but the problem here is the order of the `for` loops. To get the required output as follows:
```
E L
L E
```
You need to print both of these characters in the same loop i.e. when it's printing on the same line. So you need the `IndexFromFront` and `IndexFromBack` variables which store the value of `E` and `L` respectively.
After your initial loop to print the characters `H E L P`
```
for (int Letter = 0; Letter < PhraseLength; Letter++)
System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();
```
You need to start from the `first` index i.e. `1` to access `E` and the value of `IndexFromBack` would be `PhraseLength-1-(IndexFromFront)`. Now that you have the indices of the values that you'd have to print from the original string, you need to get the right spacing i.e. `2*(PhraseLength-1)-1` because you have a space after each character. So your second loop to print the lines
```
E L
L E
```
should be as follows:
```
for (int Letter = 1; Letter < PhraseLength-1; Letter++) {
int IndexFromFront = Letter;
int IndexFromBack = PhraseLength-1-Letter;
// Print character from the start of string at given Index
System.out.print(CapPhrase.charAt(IndexFromFront));
// Print required spaces
for (int Space = 0; Space < 2*(PhraseLength-1)-1; Space++) {
System.out.print(" ");
}
// End space print
// Print character from the end of string matching the required index
System.out.print(CapPhrase.charAt(IndexFromBack));
// Printing on this line is complete, so print a new line.
System.out.println();
}
```
and the final line i.e. reverse of given input string can be printed using the loop as follows:
```
for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
System.out.print(CapPhrase.charAt(Letter) + " ");
}
```
Therefore the final code that you'd have is as follows:
```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String Phrase = scan.nextLine();
String CapPhrase = Phrase.toUpperCase();
int PhraseLength = CapPhrase.length();
for (int Letter = 0; Letter < PhraseLength; Letter++)
System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();
for (int Letter = 1; Letter < PhraseLength - 1; Letter++) {
int IndexFromFront = Letter;
int IndexFromBack = PhraseLength - 1 - Letter;
System.out.print(CapPhrase.charAt(IndexFromFront));
// Print required spaces
for (int Space = 0; Space < 2 * (PhraseLength - 1) - 1; Space++) {
System.out.print(" ");
}
// End space print
System.out.print(CapPhrase.charAt(IndexFromBack));
System.out.println();
}
for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
System.out.print(CapPhrase.charAt(Letter) + " ");
}
}
```
Here's a sample output for `HELPINGYOUOUT`
```
Enter a phrase or word!
H E L P I N G Y O U O U T
E U
L O
P U
I O
N Y
G G
Y N
O I
U P
O L
U E
T U O U O Y G N I P L E H
```
---
**Edit:** More readable code
```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
public static void printSpaces(int phraseLength) {
for (int space = 0; space < 2 * (phraseLength - 1) - 1; space++) {
System.out.print(" ");
}
}
public static void printTopRow(String capPhrase, int phraseLength) {
for (int letter = 0; letter < phraseLength; letter++)
System.out.print(capPhrase.charAt(letter) + " ");
System.out.println();
}
public static void printIntermediateBoxRows(String capPhrase, int phraseLength) {
for (int letter = 1; letter < phraseLength - 1; letter++) {
int indexFromFront = letter;
int indexFromBack = phraseLength - 1 - letter;
System.out.print(capPhrase.charAt(indexFromFront));
// Print required spaces
printSpaces(phraseLength);
// End space print
System.out.print(capPhrase.charAt(indexFromBack));
System.out.println();
}
}
public static void printLastRow(String capPhrase, int phraseLength) {
for (int letter = phraseLength - 1; letter >= 0; letter--)
System.out.print(capPhrase.charAt(letter) + " ");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String phrase = scan.nextLine();
String capPhrase = phrase.toUpperCase();
int phraseLength = capPhrase.length();
// Print the box
printTopRow(capPhrase, phraseLength);
printIntermediateBoxRows(capPhrase, phraseLength);
printLastRow(capPhrase, phraseLength);
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: An incredibly helpful tactic for solving tricky problems is to map/draw/record everything that's changing and search for patterns. So we'll start by doing just that. For simplicity of tracking values I'll show the process in an array.
```
String keyword = "test"
```
Result will look something like this.
```
[t][e][s][t]
[e][ ][ ][s]
[s][ ][ ][e]
[t][s][e][t]
```
The first row is equal to the string but we'll replace the letters with values corresponding to the index of the character in the string. `Space` will be equal to `0`.
```
[1][2][3][1]
[2][0][0][3]
[3][0][0][2]
[1][3][2][1]
```
If we take these values and put them into one line we would end up with
```
1231200330021321
1231 2003 3002 1321 //Easier to read version
```
The first and last line are reversed and the second and third line are reversed. Thus, we can produce the output with three index counters. Each index counter is referencing a character within the original string
The first index counter will be for the full string to be read forward and backwards.
```
[t][e][s][t] //From 0 -> (keyword.length-1)
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[t][s][e][t] //From (keyword.length-1) -> 0
```
The second counter will be used to index up on the left side and the third counter will be used to index down on the right side.
```
[ ][ ][ ][ ] //Be aware of possible out of bounds index errors
[e][ ][ ][s] //From 1 -> (keyword.length-2)
[s][ ][ ][e] //From (keyword.length-2) -> 1
[ ][ ][ ][ ]
```
Upvotes: 0 <issue_comment>username_3: here's my answer. i've re-named things according to java naming standards, addressed the memory leak (Scanner wasn't closed), used methods as one does, and addressed the fact that the word phrase implies that there could be words with spaces in between.
```
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter a phrase or word!");
String phrase = scan.nextLine();
phrase = phrase.toUpperCase();
phrase = cleanUpWordBoundaries(phrase);
for (int letter = 0; letter < phrase.length(); letter++) {
System.out.print(phrase.charAt(letter) + " ");
}
System.out.println();
printSidePhrase(phrase);
for (int letter = phrase.length() - 1; letter >= 0; letter--) {
System.out.print(phrase.charAt(letter) + " ");
}
}
}
private static void printSidePhrase(String phrase) {
int startIndex = 1;
int lastIndex = phrase.length() - 2;
for (int letter = 1; letter < phrase.length() - 1; letter++) {
System.out.print(phrase.charAt(startIndex));
// print spaces
for (int i = 0; i < (phrase.length() - 2); i++) {
System.out.print(" ");
}
System.out.print(" " + phrase.charAt(lastIndex));
System.out.println();
startIndex++;
lastIndex--;
}
}
private static String cleanUpWordBoundaries(String phrase) {
String[] theWords = phrase.split("\\b");
String newPhrase = new String();
for (int i = 0; i < theWords.length; i++) {
newPhrase += theWords[i];
i++;
}
return newPhrase;
}
```
from running the program:
```
Enter a phrase or word!
w00 h00 bandit
W 0 0 H 0 0 B A N D I T
0 I
0 D
H N
0 A
0 B
B 0
A 0
N H
D 0
I 0
T I D N A B 0 0 H 0 0 W
```
Upvotes: 0 <issue_comment>username_4: I'm so lucky to answer your question! Attention! The key of the problem is that The cursor only go to next line,it won't go back previous line.
When the second loop end,the result is as follow:
```
H E L P
E
L
```
The print of the thirdly loop begins at line 4, So the print results of next line is as follow:
```
H E L P
E
L
L
```
I have coded the code as follow:
```
Scanner s = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String pharase = s.nextLine().toUpperCase();
int length = pharase.length();
char[] strArr = pharase.toCharArray();
for (int row = 0; row <= length-1 ; row++) {
for (int column = 0; column <= length -1 ; column++) {
System.out.print(row>0&&row0&&column
```
the result of input "youarehandsome":
```
Y O U A R E H A N D S O M E
O M
U O
A S
R D
E N
H A
A H
N E
D R
S A
O U
M O
E M O S D N A H E R A U O Y
```
Upvotes: 0 |
2018/03/19 | 3,190 | 11,387 | <issue_start>username_0: I am currently using the datasets at <https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all> to learn SQL.
The question I have been given is "Generate a list of all the Customers and the total cost of the Orders they have place – try displaying the total cost to 2 decimal places using the round() function.".
I am entering the code:
```
SELECT c.CustomerName, ROUND(sum(CostPerCustomer),2) as "TotalCost"
FROM (
SELECT c.CustomerName, p.ProductName, (p.Price)*count(c.CustomerName)) AS "CostPerCustomer"
FROM Customers c, Products p, Orders o, OrderDetails od
WHERE c.CustomerID = o.CustomerID and p.ProductID = od.ProductID and o.OrderID = od.OrderID
GROUP BY c.CustomerName, p.ProductName
ORDER BY c.CustomerName, count(c.CustomerName) desc)
GROUP BY CustomerName
```
I receive the error message 'You tried to execute a query that does not include the specified expression 'p.Price\*count(c.CustomerName)' as part of an aggregate function.'
Is someone please able to tell me what's wrong with my code and how I might fix it?<issue_comment>username_1: You're quite close but the problem here is the order of the `for` loops. To get the required output as follows:
```
E L
L E
```
You need to print both of these characters in the same loop i.e. when it's printing on the same line. So you need the `IndexFromFront` and `IndexFromBack` variables which store the value of `E` and `L` respectively.
After your initial loop to print the characters `H E L P`
```
for (int Letter = 0; Letter < PhraseLength; Letter++)
System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();
```
You need to start from the `first` index i.e. `1` to access `E` and the value of `IndexFromBack` would be `PhraseLength-1-(IndexFromFront)`. Now that you have the indices of the values that you'd have to print from the original string, you need to get the right spacing i.e. `2*(PhraseLength-1)-1` because you have a space after each character. So your second loop to print the lines
```
E L
L E
```
should be as follows:
```
for (int Letter = 1; Letter < PhraseLength-1; Letter++) {
int IndexFromFront = Letter;
int IndexFromBack = PhraseLength-1-Letter;
// Print character from the start of string at given Index
System.out.print(CapPhrase.charAt(IndexFromFront));
// Print required spaces
for (int Space = 0; Space < 2*(PhraseLength-1)-1; Space++) {
System.out.print(" ");
}
// End space print
// Print character from the end of string matching the required index
System.out.print(CapPhrase.charAt(IndexFromBack));
// Printing on this line is complete, so print a new line.
System.out.println();
}
```
and the final line i.e. reverse of given input string can be printed using the loop as follows:
```
for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
System.out.print(CapPhrase.charAt(Letter) + " ");
}
```
Therefore the final code that you'd have is as follows:
```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String Phrase = scan.nextLine();
String CapPhrase = Phrase.toUpperCase();
int PhraseLength = CapPhrase.length();
for (int Letter = 0; Letter < PhraseLength; Letter++)
System.out.print(CapPhrase.charAt(Letter) + " ");
System.out.println();
for (int Letter = 1; Letter < PhraseLength - 1; Letter++) {
int IndexFromFront = Letter;
int IndexFromBack = PhraseLength - 1 - Letter;
System.out.print(CapPhrase.charAt(IndexFromFront));
// Print required spaces
for (int Space = 0; Space < 2 * (PhraseLength - 1) - 1; Space++) {
System.out.print(" ");
}
// End space print
System.out.print(CapPhrase.charAt(IndexFromBack));
System.out.println();
}
for (int Letter = PhraseLength - 1; Letter >= 0; Letter--)
System.out.print(CapPhrase.charAt(Letter) + " ");
}
}
```
Here's a sample output for `HELPINGYOUOUT`
```
Enter a phrase or word!
H E L P I N G Y O U O U T
E U
L O
P U
I O
N Y
G G
Y N
O I
U P
O L
U E
T U O U O Y G N I P L E H
```
---
**Edit:** More readable code
```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class StringInABox {
public static void printSpaces(int phraseLength) {
for (int space = 0; space < 2 * (phraseLength - 1) - 1; space++) {
System.out.print(" ");
}
}
public static void printTopRow(String capPhrase, int phraseLength) {
for (int letter = 0; letter < phraseLength; letter++)
System.out.print(capPhrase.charAt(letter) + " ");
System.out.println();
}
public static void printIntermediateBoxRows(String capPhrase, int phraseLength) {
for (int letter = 1; letter < phraseLength - 1; letter++) {
int indexFromFront = letter;
int indexFromBack = phraseLength - 1 - letter;
System.out.print(capPhrase.charAt(indexFromFront));
// Print required spaces
printSpaces(phraseLength);
// End space print
System.out.print(capPhrase.charAt(indexFromBack));
System.out.println();
}
}
public static void printLastRow(String capPhrase, int phraseLength) {
for (int letter = phraseLength - 1; letter >= 0; letter--)
System.out.print(capPhrase.charAt(letter) + " ");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String phrase = scan.nextLine();
String capPhrase = phrase.toUpperCase();
int phraseLength = capPhrase.length();
// Print the box
printTopRow(capPhrase, phraseLength);
printIntermediateBoxRows(capPhrase, phraseLength);
printLastRow(capPhrase, phraseLength);
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: An incredibly helpful tactic for solving tricky problems is to map/draw/record everything that's changing and search for patterns. So we'll start by doing just that. For simplicity of tracking values I'll show the process in an array.
```
String keyword = "test"
```
Result will look something like this.
```
[t][e][s][t]
[e][ ][ ][s]
[s][ ][ ][e]
[t][s][e][t]
```
The first row is equal to the string but we'll replace the letters with values corresponding to the index of the character in the string. `Space` will be equal to `0`.
```
[1][2][3][1]
[2][0][0][3]
[3][0][0][2]
[1][3][2][1]
```
If we take these values and put them into one line we would end up with
```
1231200330021321
1231 2003 3002 1321 //Easier to read version
```
The first and last line are reversed and the second and third line are reversed. Thus, we can produce the output with three index counters. Each index counter is referencing a character within the original string
The first index counter will be for the full string to be read forward and backwards.
```
[t][e][s][t] //From 0 -> (keyword.length-1)
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[t][s][e][t] //From (keyword.length-1) -> 0
```
The second counter will be used to index up on the left side and the third counter will be used to index down on the right side.
```
[ ][ ][ ][ ] //Be aware of possible out of bounds index errors
[e][ ][ ][s] //From 1 -> (keyword.length-2)
[s][ ][ ][e] //From (keyword.length-2) -> 1
[ ][ ][ ][ ]
```
Upvotes: 0 <issue_comment>username_3: here's my answer. i've re-named things according to java naming standards, addressed the memory leak (Scanner wasn't closed), used methods as one does, and addressed the fact that the word phrase implies that there could be words with spaces in between.
```
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter a phrase or word!");
String phrase = scan.nextLine();
phrase = phrase.toUpperCase();
phrase = cleanUpWordBoundaries(phrase);
for (int letter = 0; letter < phrase.length(); letter++) {
System.out.print(phrase.charAt(letter) + " ");
}
System.out.println();
printSidePhrase(phrase);
for (int letter = phrase.length() - 1; letter >= 0; letter--) {
System.out.print(phrase.charAt(letter) + " ");
}
}
}
private static void printSidePhrase(String phrase) {
int startIndex = 1;
int lastIndex = phrase.length() - 2;
for (int letter = 1; letter < phrase.length() - 1; letter++) {
System.out.print(phrase.charAt(startIndex));
// print spaces
for (int i = 0; i < (phrase.length() - 2); i++) {
System.out.print(" ");
}
System.out.print(" " + phrase.charAt(lastIndex));
System.out.println();
startIndex++;
lastIndex--;
}
}
private static String cleanUpWordBoundaries(String phrase) {
String[] theWords = phrase.split("\\b");
String newPhrase = new String();
for (int i = 0; i < theWords.length; i++) {
newPhrase += theWords[i];
i++;
}
return newPhrase;
}
```
from running the program:
```
Enter a phrase or word!
w00 h00 bandit
W 0 0 H 0 0 B A N D I T
0 I
0 D
H N
0 A
0 B
B 0
A 0
N H
D 0
I 0
T I D N A B 0 0 H 0 0 W
```
Upvotes: 0 <issue_comment>username_4: I'm so lucky to answer your question! Attention! The key of the problem is that The cursor only go to next line,it won't go back previous line.
When the second loop end,the result is as follow:
```
H E L P
E
L
```
The print of the thirdly loop begins at line 4, So the print results of next line is as follow:
```
H E L P
E
L
L
```
I have coded the code as follow:
```
Scanner s = new Scanner(System.in);
System.out.println("Enter a phrase or word!");
String pharase = s.nextLine().toUpperCase();
int length = pharase.length();
char[] strArr = pharase.toCharArray();
for (int row = 0; row <= length-1 ; row++) {
for (int column = 0; column <= length -1 ; column++) {
System.out.print(row>0&&row0&&column
```
the result of input "youarehandsome":
```
Y O U A R E H A N D S O M E
O M
U O
A S
R D
E N
H A
A H
N E
D R
S A
O U
M O
E M O S D N A H E R A U O Y
```
Upvotes: 0 |
2018/03/19 | 2,874 | 9,458 | <issue_start>username_0: Normally i use this code for echo page rows. It's work good.
```
$query = "SELECT * FROM table WHERE id = '$id' ";
$result = mysqli_query($db_mysqli, $query);
$row = mysqli_fetch_assoc($result);
$page = $row['page'];
echo $page;
```
.....
Now i use `bind_param` this code for echo page rows. But not work , how can i do ?
```
$stmt = $db_mysqli->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->get_result();
$page = $row['page'];
echo $page;
```<issue_comment>username_1: You need to add:
```
while ($row = $result->fetch_assoc()) {
$page = $row['page'];
}
echo $page;
```
Upvotes: 0 <issue_comment>username_2: I try to avoid binding params as it can give strange results if not managed correctly.
I prefer to bind value as it will copy the point in time variable value, rather than maintaining the memory position connection.
However, mysqli seems to only support simplistic non-named param binding :(
<http://php.net/manual/en/mysqli-stmt.bind-param.php>
<http://php.net/manual/en/mysqli.prepare.php>
```
$stmt = $db_mysqli->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$page = $row['page'];
echo $page;
}
```
I’m more a fan of PDO than mysqli, easier to use.
Upvotes: -1 <issue_comment>username_3: Problem description:
--------------------
The `mysqli_result` object returned by the method `get_result` looks something like this:
```
mysqli_result Object
(
[current_field] => 0
[field_count] => 3
[lengths] =>
[num_rows] => 1
[type] => 0
)
```
As you can see, this object exposes only some properties (number of fields, number of rows, etc) about the record set from which you need to reference your data. So, you can not directly reference field values from it.
Solution:
---------
In order to reach to the needed data you'll have to call one of the methods defined in the `mysqli_result` class (`fetch_all`, `fetch_array`, `fetch_assoc`, etc):
```
//...
$result = $stmt->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
$page = $row['page'];
//...
```
with `$row` representing the fetched record and being an array like this:
```
Array
(
[id] => 13
[page] => 21
...
)
```
For more details read [The `mysqli_result` class](https://secure.php.net/manual/en/class.mysqli-result.php).
About error and exception handling:
-----------------------------------
Please note that a proper [error and exception handling](https://secure.php.net/manual/en/book.errorfunc.php) system is essential in the developing process. [This article](https://phpdelusions.net/articles/error_reporting) describes the steps needed to activate it in an elegant and thoroughly manner.
Extensive example:
------------------
For clarity, I prepared an extensive example with all components needed for accessing a database using the `mysqli` extension. It presents the situation of having to fetch one or more records from a list of users - saved in a db table named `users`. Each user is described by its `id`, `name` and `age`.
It's up to you to implement the error/exception handling system - as described in the above mentioned article.
**index.php:**
*Option 1) Fetching only one record:*
```
php
require 'connection.php';
// Assign the values used to replace the sql statement markers.
$id = 10;
/*
* The SQL statement to be prepared. Notice the so-called markers,
* e.g. the "?" signs. They will be replaced later with the
* corresponding values when using mysqli_stmt::bind_param.
*
* @link http://php.net/manual/en/mysqli.prepare.php
*/
$sql = 'SELECT
id,
name,
age
FROM users
WHERE id = ?';
/*
* Prepare the SQL statement for execution - ONLY ONCE.
*
* @link http://php.net/manual/en/mysqli.prepare.php
*/
$statement = $connection-prepare($sql);
/*
* Bind variables for the parameter markers (?) in the
* SQL statement that was passed to prepare(). The first
* argument of bind_param() is a string that contains one
* or more characters which specify the types for the
* corresponding bind variables.
*
* @link http://php.net/manual/en/mysqli-stmt.bind-param.php
*/
$statement->bind_param('i', $id);
/*
* Execute the prepared SQL statement.
* When executed any parameter markers which exist will
* automatically be replaced with the appropriate data.
*
* @link http://php.net/manual/en/mysqli-stmt.execute.php
*/
$statement->execute();
/*
* Get the result set from the prepared statement.
*
* NOTA BENE:
* Available only with mysqlnd ("MySQL Native Driver")! If this
* is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in
* PHP config file (php.ini) and restart web server (I assume Apache) and
* mysql service. Or use the following functions instead:
* mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
*
* @link http://php.net/manual/en/mysqli-stmt.get-result.php
* @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
*/
$result = $statement->get_result();
/*
* Fetch data and save it into an array:
*
* Array
* (
* [id] => 10
* [name] => Michael
* [age] => 18
* )
*
* @link https://secure.php.net/manual/en/mysqli-result.fetch-array.php
*/
$user = $result->fetch_array(MYSQLI_ASSOC);
/*
* Free the memory associated with the result. You should
* always free your result when it is not needed anymore.
*
* @link http://php.net/manual/en/mysqli-result.free.php
*/
$result->close();
/*
* Close the prepared statement. It also deallocates the statement handle.
* If the statement has pending or unread results, it cancels them
* so that the next query can be executed.
*
* @link http://php.net/manual/en/mysqli-stmt.close.php
*/
$statement->close();
/*
* Close the previously opened database connection.
*
* @link http://php.net/manual/en/mysqli.close.php
*/
$connection->close();
// Reference the values of the fetched data.
echo 'User id is ' . $user['id'] . '
';
echo 'User name is ' . $user['name'] . '
';
echo 'User age is ' . $user['age'] . '
';
```
*Option 2) Fetching multiple records:*
```
php
require 'connection.php';
$id1 = 10;
$id2 = 11;
$sql = 'SELECT
id,
name,
age
FROM users
WHERE
id = ?
OR id = ?';
$statement = $connection-prepare($sql);
$statement->bind_param('ii', $id1, $id2);
$statement->execute();
$result = $statement->get_result();
/*
* Fetch data and save it into an array:
*
* Array
* (
* [0] => Array
* (
* [id] => 10
* [name] => Michael
* [age] => 18
* )
*
* [1] => Array
* (
* [id] => 11
* [name] => Harry
* [age] => 59
* )
* )
*
* @link http://php.net/manual/en/mysqli-result.fetch-all.php
*/
$users = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
$statement->close();
$connection->close();
// Reference the values of the fetched data.
foreach ($users as $key => $user) {
echo 'User id is ' . $user['id'] . '
';
echo 'User name is ' . $user['name'] . '
';
echo 'User age is ' . $user['age'] . '
';
echo '
---
';
}
```
**connection.php:**
```
php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', '<PASSWORD>');
/*
* Error reporting.
*
* Also, define an error handler, an exception handler and, eventually,
* a shutdown handler function to handle the raised errors and exceptions.
*
* @link https://phpdelusions.net/articles/error_reporting Error reporting basics
* @link http://php.net/manual/en/function.error-reporting.php
* @link http://php.net/manual/en/function.set-error-handler.php
* @link http://php.net/manual/en/function.set-exception-handler.php
* @link http://php.net/manual/en/function.register-shutdown-function.php
*/
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */
/*
* Enable internal report functions. This enables the exception handling,
* e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
* (mysqli_sql_exception).
*
* MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
* MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
*
* @link http://php.net/manual/en/class.mysqli-driver.php
* @link http://php.net/manual/en/mysqli-driver.report-mode.php
* @link http://php.net/manual/en/mysqli.constants.php
*/
$mysqliDriver = new mysqli_driver();
$mysqliDriver-report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create a new db connection.
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
// Set the desired connection charset
$connection->set_charset('utf8mb4');
```
**Test data:**
```
id name age
---------------
9 Julie 23
10 Michael 18
11 Harry 59
```
**Create table syntax:**
```
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
Upvotes: 4 [selected_answer] |
2018/03/19 | 1,014 | 3,018 | <issue_start>username_0: Suppose I have data points:
```
x = [(1, 2), (1, 5), (1, 6), (2, 4), (2, 5), (2, 7), (3, 1), (3, 5), (3, 6)]
y = [2.3,5.6,9.0,8.6,4.2,13.5,11.0,1.3,5.0]
```
Now I want to predict the value of `y` for some new pairs, say `(2,3),(3,4)`
Suggest me a python code for the same.
I have tried with interpolation but couldn't get the result, I think some machine learning would do it, but I am really new in machine learning.
Suggest me a python code for the same.
Actual data I am working on is similar to these dummy data.[Want to predict values of missing point in the given image](https://i.stack.imgur.com/oTg1F.png)<issue_comment>username_1: You can use regression to predict. [scikit-learn-linear regression](http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html)
I assume that you have enough data to apply machine learning. After train test split, you need to fit your train data to machine learning model in this case regression. You can do this by using `regression_model.fit(X_train,y_train)`
To be able to predict new points you can use `regression_model.predict(X)`
Do not forget to create your model object before trying these code. For more information [sklearn-linear\_model.LinearRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html)
If you want to predict this particular point on this dataset, I suggest you to establish your model as y = ax1 + bx2 + error. You need to find coefficients 'a' and 'b' [linear\_regression](http://www.statisticshowto.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/)
Upvotes: 2 <issue_comment>username_2: The previous comments are correct, one way is to use scikit-learn. All of its regression classes implement the same methods such that you can run a bunch of kinds of regressions as in the small example below (without train-test split):
```
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, BayesianRidge
from sklearn.metrics import mean_squared_error, median_absolute_error
x = [(1, 2), (1, 5), (1, 6), (2, 4), (2, 5), (2, 7), (3, 1), (3, 5), (3, 6)]
y = [2.3,5.6,9.0,8.6,4.2,13.5,11.0,1.3,5.0]
x = np.array(x)
y = np.array(y)
# collection of regression methods
models = {"OLS":LinearRegression(),
"R":Ridge(),
"BR":BayesianRidge()}
# collection of metrics for regression
metrics = {"mse":mean_squared_error,
"mae":median_absolute_error}
# training
for m in sorted(models):
print("\n",m)
models[m].fit(x,y)
# metrics for comparison of regression methods
for me in sorted(metrics):
print("metric",me,metrics[me](y, models[m].predict(x)))
```
**Edit:**
Prediction of new values can then be done via:
```
x_new = np.array([[2,3],
[3,4]])
for m in sorted(models):
print("\n",m)
print(models[m].predict(x_new))
```
BR
[ 6.7211654 6.7218773]
OLS
[ 6.28459643 6.67948244]
R
[ 6.29948927 6.66721144]
Upvotes: 0 |
2018/03/19 | 209 | 689 | <issue_start>username_0: I am unable to build a simple hello world application using clang-6.0 on bionic beaver, the build command fails with below error.
```
clang++-6.0 -std=c++17 -stdlib=libc++ hello.cc -o hello
/usr/bin/ld: cannot find -lc++abi
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
what is this c++abi library and where can i find it ??
Please advise.<issue_comment>username_1: `sudo apt-get install libc++abi-dev`
command will fix the problem
Upvotes: 6 [selected_answer]<issue_comment>username_2: Thanks @Ravikumar-Tulugu and @Martin-Valgur. In my case (Fedora) I installed the equivalent that is in package lbcxxabi.
Upvotes: 1 |
2018/03/19 | 357 | 1,232 | <issue_start>username_0: Currently I'm using this pattern in code:
```
module.exports.getMySQL = () => {
return process.env.CLEARDB_DATABASE_URL || config.get('MySQL').connection;
}
```
however, node-config claims to be able to integrate these variables into a file as such.
<https://github.com/lorenwest/node-config/wiki/Environment-Variables#custom-environment-variables>
```
{
"Customer": {
"dbConfig": {
"host": "PROD_SERVER"
},
"credit": {
"initialDays": "CR_ID"
},
// Environment variables containing multiple configs
// New as of [email protected]
"settings": {
"adminAccounts": {
"__name": "ADMIN_ACCS",
"__format": "json"
}
}
}
}
```
What exactly is `"PROD_SERVER"`
If I replace this with `"process.env.SOME_ENVIRONMENT_VARIABLE"`, it does not work and my server crashes.
I did verify that `"process.env.SOME_ENVIRONMENT_VARIABLE"` exists using the Heroku GUI.<issue_comment>username_1: `sudo apt-get install libc++abi-dev`
command will fix the problem
Upvotes: 6 [selected_answer]<issue_comment>username_2: Thanks @Ravikumar-Tulugu and @Martin-Valgur. In my case (Fedora) I installed the equivalent that is in package lbcxxabi.
Upvotes: 1 |
2018/03/19 | 384 | 1,094 | <issue_start>username_0: `json` file like this:
```
{"authors":[{"ids":["4888852"],"name":"<NAME>"},{"ids":["3325893"],"name":"<NAME>"},{"ids":["5316482"],"name":"<NAME>"}]}
{"authors":[{"ids":["4836831"],"name":"<NAME>"},{"ids":["4061357"],"name":"<NAME>"}]}
{"authors":[{"ids":["4888852"],"name":"<NAME>"},{"ids":["4061357"],"name":"<NAME>"}]}
```
Code
```
import csv
import json
import pandas as pd
from itertools import islice
from collections import Counter
data=[]
with open('papers-2017-10-30-sample.json',encoding='utf-8') as f:
for line in f:
data.append(json.loads(line))
c = Counter(player['ids'] for player in data)
print(c)
```
I want to count same `ids`'s value and use `name` to group
any ideas? please help<issue_comment>username_1: `sudo apt-get install libc++abi-dev`
command will fix the problem
Upvotes: 6 [selected_answer]<issue_comment>username_2: Thanks @Ravikumar-Tulugu and @Martin-Valgur. In my case (Fedora) I installed the equivalent that is in package lbcxxabi.
Upvotes: 1 |
2018/03/19 | 502 | 1,743 | <issue_start>username_0: I'm trying to set the background color of a text both either to a color, or to 100% transparent (whatever is easiest) but I'm struggling to achieve either.
I've tried "bgColor" as per some other elements but no luck :(
```
$textbox = $section->addTextBox(
array(
'marginTop' => -100,
'marginLeft' => -100,
'posHorizontal' => 'absolute',
'posVertical' => 'absolute',
'align' => 'left',
'positioning' => 'relative',
'width' => 200,
'height' => 40,
'borderColor' => '#eeeeee',
'borderSize' => 0,
'bgColor' => 'black',
)
);
```<issue_comment>username_1: Does anyone how to do this, also have this issue. The documentation has not been updated in years. AddTextBox doesnt exist on docs...
```
'fill' => array('color' => '#990000'),
'bgColor' => '#990000',
'backgroundColor' => '#990000'
```
None of the above work.
Upvotes: 0 <issue_comment>username_2: Try this
```
'fillColor' => 'black'
```
Or
```
'fillColor' => '#BFBFBF'
```
you can find all properties in PhpWord\Style\TextBox.php
Upvotes: 2 <issue_comment>username_3: For anyone looking for this answer here it goes:
There's no answer, textbox don't support any kind of background yet and looks like it wont.
As this [issue](https://github.com/PHPOffice/PHPWord/issues/403) suggests you can achieve the same results in terms of design with a table with a single cell.
Upvotes: 0 <issue_comment>username_4: You will need to install the latest version `composer require phpoffice/phpword:dev-master` to get access to `bgColor` property as it's not included in 1.0.
Upvotes: 0 |
2018/03/19 | 413 | 1,344 | <issue_start>username_0: I am trying to create a few rows, with 2 columns. First column is description text, and the 2nd, is an amount.
The first column shouldn't word-wrap, and as it's text, may take around 80% of the row. The 2nd column is an amount, should be right justified. But when I do the code below, each column is 50%.
```
{trans.payee} - {trans.category}
{trans.amount.toFixed(2)}
```
How do I get the first column to use up as much space as possible, and then 2nd column to only use what it needs. So the 2nd column shouldn't wrap, but should use as little room as possible.
Maybe row/col isn't the right thing to use? Or can it be done?
I'm using Bootstrap 4 - which is a learning curve for me.<issue_comment>username_1: ```
Note: You have not closed second div
```
If you don't give width to div, then it will take equally,
You need to give width to one of the div, so other one can adjust by itself.
```
{trans.payee} - {trans.category}
{trans.amount.toFixed(2)}
```
Upvotes: 0 <issue_comment>username_2: You can use **`col-auto`** on the 2nd column so it uses the least amount of space
<https://www.codeply.com/go/NR35sANtRT>
```
{trans.payee} - {trans.category} can be longer
40.00
```
You can also add `text-truncate` to prevent the 1st column from wrapping if needed.
Upvotes: 3 [selected_answer] |
2018/03/19 | 491 | 1,483 | <issue_start>username_0: I have a json file that comes like this
```
{
"report": {
"description": "Average of the quantity of items per person (total and just non-infected)",
"average_items_quantity_per_person": 164.7473903966597,
"average_items_quantity_per_healthy_person": 172.29787234042553
}
}
```
my report.model.ts
```
export class Report{
constructor(
public description: string,
public average_items_quantity_per_person: number,
public average_items_quantity_per_healthy_person: number
){}
}
```
my report.component.ts

but whenever I try to call in the HTML file
```
{{printa(report)}}
```
I get this error

Does anyone know what this error is, or if I am related to the JSON file with the .model correctly<issue_comment>username_1: ```
Note: You have not closed second div
```
If you don't give width to div, then it will take equally,
You need to give width to one of the div, so other one can adjust by itself.
```
{trans.payee} - {trans.category}
{trans.amount.toFixed(2)}
```
Upvotes: 0 <issue_comment>username_2: You can use **`col-auto`** on the 2nd column so it uses the least amount of space
<https://www.codeply.com/go/NR35sANtRT>
```
{trans.payee} - {trans.category} can be longer
40.00
```
You can also add `text-truncate` to prevent the 1st column from wrapping if needed.
Upvotes: 3 [selected_answer] |
2018/03/19 | 499 | 1,209 | <issue_start>username_0: I have a list containing 600+ elements. The `summary(list)` shows that the elements have a Mode which is either a `"list"`, `"character"` or `"logical"`. How can I remove all the elements that do not have a Mode as `"list"` without having to manually go through and remove them individually?
Thank you.<issue_comment>username_1: You can use `is.list` with `sapply` to return only those `list` elements that are `list`s:
```
lst[sapply(lst, is.list)]
```
Example:
```
lst <- list(
list(a = 1:10, b = 1:10),
"abc",
TRUE);
lst;
#[[1]]
#[[1]]$a
# [1] 1 2 3 4 5 6 7 8 9 10
#
#[[1]]$b
# [1] 1 2 3 4 5 6 7 8 9 10
#
#
#[[2]]
#[1] "abc"
#
#[[3]]
#[1] TRUE
summary(lst);
# Length Class Mode
#[1,] 2 -none- list
#[2,] 1 -none- character
#[3,] 1 -none- logical
# Select list entries that are lists
lst[sapply(lst, is.list)];
#[[1]]
#[[1]]$a
# [1] 1 2 3 4 5 6 7 8 9 10
#
#[[1]]$b
# [1] 1 2 3 4 5 6 7 8 9 10
```
Or another option using `Filter` (thanks to @Frank):
```
Filter(is.list, lst);
```
Upvotes: 2 <issue_comment>username_2: With `purr`, we can use `keep`
```
library(purrr)
keep(lst, is.list)
```
Upvotes: 0 |
2018/03/19 | 396 | 1,355 | <issue_start>username_0: I need to align this long text and it should start from left. As shown in the following image the end of the text is nicely displayed and start is hidden.
How to start the text from left,
```
alignText: 'left'
```
didnt work.
```
Geocoder.geocodePosition({
lat: origin.latitude,
lng: origin.longitude
}).then(res => {
console.log(res[0]);
this._destination.setAddressText(res[0].formattedAddress);
});
```
Here the formattedAddress is very long, I need to show it from the begining.
By default this is working in iOS.
[](https://i.stack.imgur.com/20dAN.png)<issue_comment>username_1: You need to learn about flex box system in react native :
```
flexDirection : 'row' -> used to set the text in row direction.
alignSelf : 'flex-start' -> used to set the start from the left.
```
Also please read it from there [React Native Basics flexbox](https://facebook.github.io/react-native/docs/flexbox.html)
Upvotes: 1 <issue_comment>username_2: try maxLength. assign value for maxlength according to visible text size. Otherwise use multiline=true if you want to show the full text.
ex:
```
```
Read more about it:
<https://reactnative.dev/docs/textinput.html#maxlength>
<https://reactnative.dev/docs/textinput.html#multiline>
Upvotes: 2 |
2018/03/19 | 659 | 2,272 | <issue_start>username_0: I get the following error while restoring database from dump file on server:
>
> ERROR: relation "table\_id\_seq" does not exist
>
> LINE 1: SELECT pg\_catalog.setval('table\_id\_seq', 362, true);
>
>
>
* my local psql version is 10.2
* server psql version is 9.6.8
Here is my dump command:
```
pg_dump -U username -h localhost db_name > filename.sql
```
Here is my restore command on server:
```
psql -U username -h localhost db_name < filename.sql
```
Please help, Thanks.<issue_comment>username_1: You can open the dump file with any text editor (Notepad, Vim, etc.). Search for `table_id_seq`. You should find a statement like
```
CREATE SEQUENCE table_id_seq ...
```
If it is missing then there is something strange with your dump. You might fix that by adding
```
CREATE SEQUENCE table_id_seq;
```
immediately in front of the statement
```
SELECT pg_catalog.setval('table_id_seq', 362, true);
```
from the error message.
But this is just a hack. You were supposed to find out why the dump made that mistake. But that requires more information.
Upvotes: 2 <issue_comment>username_2: After I got information from @username_1 and make some research I found that, in my dump file on section `CREATE SEQUENCE table_id_seq` has a statement `AS integer` that why when I restored into new database it did not create the `nextval()` for the sequence. If I remove the statement `AS integer` from the `CREATE SEQUENCE` section it works find.
In my dump file:
```
CREATE SEQUENCE table_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
```
Remove `AS integer` from dump file
```
CREATE SEQUENCE table_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
```
Upvotes: 5 [selected_answer]<issue_comment>username_3: In my case, the sequence checking is case-sensitive. That's why I was getting the relation error. So maybe it helps some people like me who end up desperately here. I've used a double-quote inside the single quotation mark in the SQL statement.
```sql
SELECT nextval('"USER_ID_seq"');
```
There're some examples in the official documentation:
<https://www.postgresql.org/docs/9.1/functions-sequence.html>
Upvotes: 2 |
2018/03/19 | 1,551 | 5,149 | <issue_start>username_0: This is my HTML page.
In this page I have a textbox and three buttons as shown.
```html
$(document).ready(function(){
$("button").css("color","green");
});
Enter
First
Second
Three
```
If I type in "First" in the textbox and enter I want the button with the id "First" to have it's css changed from "green" to "red".
If I type in "First, Second" in the textbox and enter, I want the button with the id "First" & "Second" to have their CSS changed from green to red and so on.
If the input is invalid then do nothing.
I did some research and found that I can modify the css via jquery's .css() method.
But I am not sure as to which event I can use to handle the enter event on textbox.
Can some one help ?<issue_comment>username_1: At first i was thinking "onChange" would be useful for you, but probably what you want it to surround the input in a form, and then use `onSubmit` which will catch that.
There's a page on w3schools covering it here: <https://www.w3schools.com/jsref/event_onsubmit.asp>
You'd declare it with something like:
```
Enter
$('#inputform').onsubmit = function(){
// button colour-change code goes here
};
```
Upvotes: -1 <issue_comment>username_2: In a chnageColor function, you can use **split()** to split the string by **','** and create an array out of it.
Iterate that array using **forEach** and used the trimmed value of items to select the button and change the color to red.
```js
function changeColor() {
$("button").css("color","green");
let valArr = $('#inputid').val().split(',');
valArr.forEach(m => {
$('#'+m.trim()).css("color", "red")
})
}
```
```html
$(document).ready(function(){
$("button").css("color","green");
});
Enter
First
Second
Three
```
Upvotes: 0 <issue_comment>username_3: You need to track when enter key is pressed. Here is the example.
```js
$("#inputid").keypress(function(e) {
if(e.which == 13) {
var inputdata = $(this).val();
switch(inputdata){
case "First":
$("#first").css("color","red");
break;
default:
console.log("do something when input is invalid");
break;
}
}
});
```
```html
$(document).ready(function(){
$("button").css("color","green");
});
Enter
First
Second
Three
```
Upvotes: 0 <issue_comment>username_4: ```js
$(document).ready(function(){
$("button").css("color","green");
$('#inputid').on('keyup',function(e){
if(e.keyCode == 13)
{
if($(this).val() == 'First')
{
$("#first").css("color","red");
}
}
});
});
```
```html
Enter
First
Second
Three
```
Upvotes: 0 <issue_comment>username_5: Use `keypress` and check if hit enter using key code 13 check `textbox` contain match your condition with using `indexOf`.
```js
$('#inputid').keypress(function(e) {
if (e.which == 13) {
var txt = $(this).val();
if (txt.indexOf('First') != -1) {
$("#first").css("color", "green");
}
if (txt.indexOf('First, Second') != -1) {
$("#first").css("color", "green");
$("#second").css("color", "green");
}
}
});
```
```html
Enter // Type First and enter to see result
First
Second
Three
```
Upvotes: 0 <issue_comment>username_6: ```html
$(document).ready(function(){
$("button").css("color","green");
$('#inputid').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
var idArr=$('#inputid').val().split(',');
$.each(idArr,function(i,v){
$('#'+v.toLowerCase().trim()).css("color","red");
})
}
});
});
Enter
First
Second
Three
```
Upvotes: 0 <issue_comment>username_7: Yes,you need to use css mehhod.Just use the split function either click event of enter button. or if you want to on enter key , you can use keypress and then detect enter key by keycode 13
Below is the code snippet:-
On keypress:-
```js
$("#inputid").keypress(function(e) {
if (e.which == 13) {
var val1 = $('#inputid').val();
if (val1){
var valArr = $('#inputid').val().split(',');
for (i=0;i
```
```html
$(document).ready(function(){
$("button").css("color","green");
});
Enter
First
Second
Three
```
and onclick event,you can use like below:-
```js
$("#enterBtn").click(function(e) {
e.preventDefault();
$("button").css("color","green");
var val1 = $('#inputid').val();
if (val1){
var valArr = $('#inputid').val().split(',');
for (i=0;i
```
```html
$(document).ready(function(){
$("button").css("color","green");
});
Enter
First
Second
Three
```
Upvotes: 0 <issue_comment>username_8: [fiddle](https://jsfiddle.net/1ot1epb7/2/)
```
$(() => {
$("button").css("color","green");
$('#inputid').on("input",(e) => {
$("button").css("color", "green");
var inputValues = $('#inputid').val().split(",");
if(inputValues.length){
inputValues.forEach((item) => {
$('#'+item).css("color","red");
});
}
});
})
Enter
First
Second
Three
```
Upvotes: 0 |
2018/03/19 | 259 | 888 | <issue_start>username_0: i have party id but i want to get party\_name from party table and made a function but its not working can anybody please correct it where i am wrong?
```
function get_partyname($party)
{
global $database;
$sql = 'SELECT party_name from party WHERE id= '.$party;
$result = $conn->query($sql);
$row = $result->fetch_assoc();
extract($row);
return $party_name;
}
$sql = 'SELECT * FROM '.$table_name ;
$result = $conn1->query($sql);
while($row = $result->fetch_assoc())
{
echo $row['id'];
$party_name = get_partyname($row['party']);
echo $party_name;
}
```<issue_comment>username_1: You need to add
```
global $conn;
```
because your database connection cannot be accessed outside the function.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You just have to replace global $database; with global $conn;.That's it.
Upvotes: 0 |
2018/03/19 | 761 | 2,344 | <issue_start>username_0: ```
root@sungil:~/fabric-samples/first-network# export CHANNEL_NAME=mychannel
root@sungil:~/fabric-samples/first-network# ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
2018-03-19 13:11:51.489 KST [common/tools/configtxgen] main -> INFO 001 Loading configuration
2018-03-19 13:11:51.494 KST [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
2018-03-19 13:11:51.495 KST [msp] getMspConfig -> INFO 003 Loading NodeOUs
2018-03-19 13:11:51.495 KST [msp] getMspConfig -> INFO 004 Loading NodeOUs
2018-03-19 13:11:51.510 KST [common/tools/configtxgen] main -> CRIT 005 Error on outputChannelCreateTx: config update generation failure: could not parse application to application group: setting up the MSP manager failed: the supplied identity is not valid: x509: certificate signed by unknown authority (possibly because of "x509: ECDSA verification failure" while trying to verify candidate authority certificate "ca.org2.example.com")
```
I installed hyperledger fabric v1.1.0-rc1 using byfn.sh.
(Reference:
<http://hyperledger-fabric.readthedocs.io/en/lastest/build_network.html>)
But I got some failure. It's Fabric CA problem?
**[executed]**
```
./byfn.sh -m generate
./byfn.sh -m up
../bin/cryptogen generate --config=./crypto-config.yaml
export FABRIC_CFG_PATH=$PWD
../bin/configtxgen -profile TwoOrgsOrdererGenesis -outputBlock ./channel-artifacts/genesis.block
export CHANNEL_NAME=mychannel
./bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
```
my configtx.yaml is <https://github.com/hyperledger/fabric-samples/blob/release-1.1/first-network/configtx.yaml><issue_comment>username_1: I faced a similar issue. What helped me was to start over.
* Bring down the network: `./byfn.sh -m down`
* Clean up the generated artifacts
+ `rm crypto-config`
+ `rm channel-artifacts`
Then issue again the commands. This helped me, the channel.tx and other were successfully created. No need to change the configtx.yaml from the sample.
Upvotes: 2 <issue_comment>username_2: You don't have to delete files you just need to make sure that ./byfn.sh -m down was executed prior to steps in Crypto Generator section
Upvotes: 0 |
2018/03/19 | 451 | 1,382 | <issue_start>username_0: Please [check link](https://codepen.io/soorajbala/pen/JLbOgq?editors=1100) for more details on my code. I need to have the placeholder image aligned to left of the screen i.e. to the bank white space as illustrated by the shared code.
```css
* {
margin: 0;
padding: 0;
}
main{
width: 100%;
display: flex;
flex-direction: row;
justify-content: flex-end;
}
aside {
width: 300px;
height: 100vh;
background-color: red;
}
article {
width: 100%;
max-width: 500px;
height: 100vh;
background-color: green;
}
figure {
padding-top : 50%;
position:relative;
img {
top:0;
left:0;
right:0;
bottom: 0;
position: absolute;
max-width: 100%;
width: 100%;
}
}
```
```html

```<issue_comment>username_1: I faced a similar issue. What helped me was to start over.
* Bring down the network: `./byfn.sh -m down`
* Clean up the generated artifacts
+ `rm crypto-config`
+ `rm channel-artifacts`
Then issue again the commands. This helped me, the channel.tx and other were successfully created. No need to change the configtx.yaml from the sample.
Upvotes: 2 <issue_comment>username_2: You don't have to delete files you just need to make sure that ./byfn.sh -m down was executed prior to steps in Crypto Generator section
Upvotes: 0 |
2018/03/19 | 279 | 1,147 | <issue_start>username_0: **I have 3 application running on Apache server.
When restart server all application get restarted.
Anyone can explain how to restart single application without affecting other applications in linux.**
Thanks in advance!<issue_comment>username_1: You can't restart Apache for a single website.
Runnin `/sbin/service httpd restart` for example will restart Apache as whole, there's no way to restart a single application.
Upvotes: 0 <issue_comment>username_2: Simple workaround is to touch specific web.xml file using command `touch web.xml`.
Tomcat reloads application every time when it notices change in web.xml file, here we are not modifying web.xml file but just touching it.
Upvotes: -1 <issue_comment>username_3: When you say Apache Server, you mean Apache Tomcat? In Tomcat, you can go to the manager page. It's usually in `localhost:8080/manager/html`. On this page you can start, stop, deploy, undeploy, etc. a single web application. See the Tomcat Manager App How To documentation for more details. Then do a `tail -f catalina.out`, it should say what app has been started/stopped/deployed/etc.
Upvotes: 0 |
2018/03/19 | 1,953 | 7,691 | <issue_start>username_0: I am working on a little tool that allows the selection of a single file. Where it will calculate the `SHA2 hash` and shows it in a simple GUI then takes the value and checks if that hash is listed in a blacklist text file. If it is listed then it will flag it as dirty, and if not it will pass it as clean.
But after hitting Google for hours on end and sifting through many online sources I decided let's just ask for advise and help.
That said while my program does work I seem to run into a problem, since no matter what I do ,it only reads the first line of my "*blacklist*" and refuses to read the whole list or to actually go line by line to see if there is a match.
No matter if I got 100 or 1 `SHA2 hash` in it.
So example if I were to have 5 files which I add to the so called *blacklist*. By pre-calculating their `SHA2 value`. Then no matter what my little tool will only flag one file which is blacklisted as a match.
Yet the moment I use the `reset` button and I select a different (also blacklisted) file, it passes it as clean while its not. As far as I can tell it is always the first `SHA2 hash` it seems to flag and ignoring the others. I personally think the program does not even check beyond the first hash.
Now the blacklist file is made up very simple.
\*example:
```
1afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
2afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
4afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
```
....and so on.
So as you can see these fake example hashes are listed without any details.
Now my program is suppose to calculate the hash from a selected file.
Example:
somefile.exe (or any extension)
Its 5KB in size and its SHA2 value would be:
```
3afde1cbccd2ab36f90973cb985072a01ebdc64d8fdba6a895c855d90f925043
```
Well as you can see I took the third hash from the example list right?
Now if I select `somefile.exe` for scanning then it will pass it as clean. While its blacklisted. So if I move this hash to the first position. Then my little program does correctly flag it.
So long story short I assume that something is horrible wrong with my code, even though it seems to be working.
Anyway this is what I got so far:
```
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports MetroFramework.Forms
Public Class Fsmain
Function SHA256_SIG(ByVal file_name As String)
Return SHA256_engine("SHA-256", file_name)
End Function
Function SHA256_engine(ByRef hash_type As String, ByRef file_name As String)
Dim SIG
SIG = SHA256.Create()
Dim hashValue() As Byte
Dim filestream As FileStream = File.OpenRead(file_name)
filestream.Position = 0
hashValue = SIG.ComputeHash(filestream)
Dim hash_hex = PrintByteArray(hashValue)
Stream.Null.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByRef array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("x2")
Next i
Return hex_value.ToLower
End Function
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog = DialogResult.OK Then
Dim path As String = SampleFetch.FileName
Selectfile.Text = path
Dim Sample As String
Sample = SHA256_SIG(path)
SignatureREF.Text = SHA256_SIG(path)
Using f As System.IO.FileStream = System.IO.File.OpenRead("blacklist.txt")
Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
While Not s.EndOfStream
Dim line As String = s.ReadLine()
If (line = Sample) Then
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Dirty"
Resetme.Visible = True
RemoveMAL.Visible = True
Else
Result.Visible = True
SignatureREF.Visible = True
Result.Text = "Clean"
Resetme.Visible = True
RemoveMAL.Visible = False
End If
End While
End Using
End Using
End If
End Sub
Private Sub Fsmain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub Resetme_Click(sender As Object, e As EventArgs) Handles Resetme.Click
Selectfile.Text = Nothing
SignatureREF.Text = Nothing
Result.Visible = False
SignatureREF.Visible = False
Resetme.Visible = False
RemoveMAL.Visible = False
End Sub
Private Sub RemoveMAL_Click(sender As Object, e As EventArgs) Handles RemoveMAL.Click
Dim ask As MsgBoxResult = MsgBox("Would you like to remove the Dirty file?", MsgBoxStyle.YesNo, MessageBoxIcon.None)
If ask = MsgBoxResult.Yes Then
System.IO.File.Delete(Selectfile.Text$)
Else
MsgBox("You sure you want to keep this file?")
Dim filepath As String = IO.Path.Combine("c:\Dirty\", "Dirty.txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(" " & DateTime.Now)
sw.WriteLine(" " & Selectfile.Text)
sw.WriteLine(" " & SignatureREF.Text)
sw.WriteLine(" " & Result.Text)
sw.WriteLine("-------------------")
sw.Close()
End Using
End If
End Sub
End Class
```
So if any of you guys can have a look at it and point out errors, or even can come up with a fix that would be great.<issue_comment>username_1: If you have a `String` and you want to test whether it matches a line of a text file then you can use this simple one-liner:
```
If IO.File.ReadLines(filePath).Contains(myString) Then
```
Upvotes: 0 <issue_comment>username_2: The simplest thing you can do to make your procedure working, is testing whether a defined condition is verified. Terminate the test if that condition is met.
Using a boolean variable, report the result of the test and take action accordingly.
The `Using` statement takes care of disposing the `StreamReader`.
You could modify you procedure this way:
```
Private Sub Browsebutton_Click(sender As Object, e As EventArgs) Handles Browsebutton.Click
If SampleFetch.ShowDialog <> DialogResult.OK Then Exit Sub
Dim sample As String = SHA256_SIG(SampleFetch.FileName)
SignatureREF.Text = sample
Dim isDirty As Boolean = False
Using reader As StreamReader = New StreamReader("blacklist.txt", True)
Dim line As String = String.Empty
While reader.Peek() > 0
line = reader.ReadLine()
If line = sample Then
isDirty = True
Exit While
End If
End While
End Using
If isDirty Then
'(...)
RemoveMAL.Visible = True
Result.Text = "Dirty"
Else
'(...)
RemoveMAL.Visible = False
Result.Text = "Clean"
End If
End Sub
```
Upvotes: 1 |
2018/03/19 | 572 | 2,185 | <issue_start>username_0: I am trying to deploy a stack of services in a swarm on a local machine for testing purpose and i want to build the docker image whenever i run or deploy a stack from the manager node.
Is it possible what I am trying to achieve..<issue_comment>username_1: On Docker Swarm you can't build an image specified in a Docker Compose file:
>
> **Note:** This option is ignored when deploying a stack in swarm mode with a (version 3) Compose file. The `docker stack` command accepts only pre-built images. - [*from docker docs*](https://docs.docker.com/compose/compose-file/#build)
>
>
>
You need to create the image with [`docker build`](https://docs.docker.com/engine/reference/commandline/build/) (on the folder where the `Dockerfile` is located):
```
docker build -t imagename --no-cache .
```
After this command the image (named `imagename`) is now available on the local registry.
You can use this image on your Docker Compose file like the following:
```
version: '3'
services:
example-service:
image: imagename:latest
```
Upvotes: 3 <issue_comment>username_2: You need to build the image with docker build. Docker swarm doesn't work with tags to identify images. Instead it remembers the image id (hash) of an image when executing stack deploy, because a tag might change later on but the hash never changes.
Therefore you should reference the hash of your image as shown by `docker image ls` so that docker swarm will not try to find your image on some registry.
```
version: '3'
services:
example-service:
image: imagename:97bfeeb4b649
```
Upvotes: 1 <issue_comment>username_3: While updating a local image you will get an error as below
```
image IMAGENAME:latest could not be accessed on a registry to record
its digest. Each node will access IMAGENAME:latest independently,
possibly leading to different nodes running different
versions of the image.
```
To overcome this issue start the service forcefully as follows
```
docker service update --image IMAGENAME:latest --force Service Name
```
In the above example it is as
**docker service update --image imagename:97bfeeb4b649 --force Service Name**
Upvotes: 2 |
2018/03/19 | 730 | 2,708 | <issue_start>username_0: This started just today, in the past I have been able to upload to repos without issue.
When I tried to add a new project to a new repo, I was given an error "cannot connect to the repmote repository at in the gui window.
At first I suspected a connection problem so i tried to push another, existing project, using that project's default settings, and was given the dialog box error:
Git command returned with the following error:
: cannot open git-receive-pack
NetBeans IDE [](https://i.stack.imgur.com/o8KJS.png)8.0.2[](https://i.stack.imgur.com/S8dkQ.png)<issue_comment>username_1: On Docker Swarm you can't build an image specified in a Docker Compose file:
>
> **Note:** This option is ignored when deploying a stack in swarm mode with a (version 3) Compose file. The `docker stack` command accepts only pre-built images. - [*from docker docs*](https://docs.docker.com/compose/compose-file/#build)
>
>
>
You need to create the image with [`docker build`](https://docs.docker.com/engine/reference/commandline/build/) (on the folder where the `Dockerfile` is located):
```
docker build -t imagename --no-cache .
```
After this command the image (named `imagename`) is now available on the local registry.
You can use this image on your Docker Compose file like the following:
```
version: '3'
services:
example-service:
image: imagename:latest
```
Upvotes: 3 <issue_comment>username_2: You need to build the image with docker build. Docker swarm doesn't work with tags to identify images. Instead it remembers the image id (hash) of an image when executing stack deploy, because a tag might change later on but the hash never changes.
Therefore you should reference the hash of your image as shown by `docker image ls` so that docker swarm will not try to find your image on some registry.
```
version: '3'
services:
example-service:
image: imagename:97bfeeb4b649
```
Upvotes: 1 <issue_comment>username_3: While updating a local image you will get an error as below
```
image IMAGENAME:latest could not be accessed on a registry to record
its digest. Each node will access IMAGENAME:latest independently,
possibly leading to different nodes running different
versions of the image.
```
To overcome this issue start the service forcefully as follows
```
docker service update --image IMAGENAME:latest --force Service Name
```
In the above example it is as
**docker service update --image imagename:97bfeeb4b649 --force Service Name**
Upvotes: 2 |
2018/03/19 | 1,035 | 4,209 | <issue_start>username_0: I have been reading about unit tests & [Clean architecture](https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html) and tried to implement something that would involve those two things.
It is my understanding that a Clean architecture is structured so that the methods of the Interactor object can be unit-tested.
But when the use case is something like "Create a file which content is computed from some data in some format", I get confused because it's not unitary (there's the computation of the file content, and the creation of the file, which are both *in* the use case)
Here's some pseudo-code illustrating my situation :
```
/* We are in an Interactor (i.e. UseCaseObject)
* This method 1)computes fileContent and 2)writes it into a file.
*/
public void CreateFileFromData(someDataInSomeFormat) {
var parsedData = SomeParser.Parse(someDataInSomeFormat);
string fileContent = ???;
WriteFile(fileContent);
}
```
My questions are the following :
1. Must a method defined in the Interactor be unitary ? (as in, do only one thing)
2. Must a method defined in the Interactor be unit-tested ? (I see a function, unitary or not, as a testable unit, please correct me if this is incorrect)
3. Which class must hold the computation of fileContent in a Clean architecture ?<issue_comment>username_1: You not telling from where data for computation will be "loaded", but for example lets assume that data will be read from another file.
Your interactor will have three dependecies
- read file
- calculate data for new file
- write file
```
public class Interactor
{
public Interactor(IReader reader, ICalculator calculator, IWriter writer)
{ }
public void DoJob()
{
var data = reader.Read();
var calculatedData = calculator.Calculate(data);
writer.Write(calculatedData);
}
}
```
With this approach `Interactor` will have responsibility to "combine" steps required to accomplished a task.
You can simply test Interactor by mocking all dependencies.
Where:
`IReader` and `IWriter` are *Gateways*
`ICalculator` is implementation detail of *UseCase* which used by `Interactor`
>
> Must a method defined in the Interactor be unitary ? (as in, do only
> one thing)
>
>
>
Method should do one thing - execute use case related task. If task requires using of gateways(external resources) or task is to complicated to keep it in one method - you will introduce all required units as dependencies and interactor responsibility will be to "glue" them together.
>
> Must a method defined in the Interactor be unit-tested ? (I see a
> function, unitary or not, as a testable unit, please correct me if
> this is incorrect)
>
>
>
Abstract only gateways(external resources) - Then you can test whole logic of interactor. If you writing test first - you will write tests and whole logic can be in the one function(it could/should be ugly spagetti code, which makes tests pass). Then when you see whole picture of implementation you can start moving staff around by moving things to dedicated classes.
>
> Which class must hold the computation of fileContent in a Clean
> architecture ?
>
>
>
It can be interactor, if it is simple one line computation. But I prefer to introduce dedicated class for computation and introduce it as dependency. While tests will remain in interactor and dedicated computation class will be tested through interactor tests
Upvotes: 3 [selected_answer]<issue_comment>username_2: One core aspect of Clean Architecture is that all application business logic is in Interactor methods. This means u also want to have ur major test focus on Interactors usually using unit tests and low level acceptance tests.
When designing ur Interactor methods u should still follow SRP: there should be only one reason to change.
U can also combine Interactors to follow SRP.
If the computation of the file content is application business logic for u it should be in an Interactor method.
For a more detailed discussion about Interactors pls have a look at my post: <https://username_2.github.io/Implementing-Clean-Architecture-UseCases/>
Upvotes: 0 |
2018/03/19 | 834 | 2,635 | <issue_start>username_0: I have generated a list of buttons , and would like each one to independently change colour when click, so they go red/green alternately on each click.
```
php
$getInfo = getAllRows();
$button = '<button type="button" id ="toggle" ';?>
//there are 5 values to iterate over
php foreach ($getInfo):
echo $button;
?
php endforeach ?
$('#toggle').click(function(){
$(this).toggleClass('green');
});
.green
{
background-color:green;
}
```
The problem Im having is that only the first button seems to be toggling colour , the others dont do anything when I click! Also Im unsure how to make it toggle from red/green alternately.
Any help would be great cheers!<issue_comment>username_1: The problem is with the `id`. It seems all the button will have same `id` which is wrong markup.
Try by replacing `id` with a common class
```
$button = ''
```
In js
```
$('.someCommonCLass').click(function(){
$(this).toggleClass('green');
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: As you are generating a list of buttons so you should use class instead of `id`
Try this:
```
$button = ''
$('.toggle').click(function(){
$(this).toggleClass('green');
});
```
Upvotes: 0 <issue_comment>username_3: [Here's a JSFiddle](https://jsfiddle.net/ta3pLnjs/1/). Like others have suggested, you want to output your buttons with a `class` instead of an `id`, to make your buttons easier to select with jQuery. Here's an example, with nice CSS. Your buttons should be formatted like this.
```
label
```
Here's a working SO Snippet.
```js
$('.toggle').click(function(){
$(this).toggleClass('green');
});
```
```css
.toggle {
background-color:#df0606;
padding:7px;
border:1px solid red;
color:white;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.toggle:hover {
background-color:#cd0101;
padding:7px;
border:1px solid red;
color:#ff2a31;
font-size:1.18em;
box-shadow:2px 4px #510809;
margin-left:4px;
margin-right:4px;
}
.green {
color:white;
padding:7px;
border:1px solid lime;
background-color:green;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.green:hover {
color:lime;
padding:7px;
border:1px solid lime;
background-color:#12de09;
font-size:1.18em;
box-shadow:2px 4px #044f12;
margin-left:4px;
margin-right:4px;
}
```
```html
These buttons generated with PHP:
One
Two
Three
Here's some text. Text text text.
```
Upvotes: 1 |
2018/03/19 | 763 | 2,327 | <issue_start>username_0: I have some basic html:
```
```
JS
```
$("button").on("click", function() {
var pathClass = $("path").attr("class");
var curClass = $(this).attr("data-date");
if($(this).hasClass(curClass)) {
<-- save the other class `BYE` in a variable -->
}
});
```
I am trying to save in a variable the class which doesn't match the data-date attribute.<issue_comment>username_1: The problem is with the `id`. It seems all the button will have same `id` which is wrong markup.
Try by replacing `id` with a common class
```
$button = ''
```
In js
```
$('.someCommonCLass').click(function(){
$(this).toggleClass('green');
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: As you are generating a list of buttons so you should use class instead of `id`
Try this:
```
$button = ''
$('.toggle').click(function(){
$(this).toggleClass('green');
});
```
Upvotes: 0 <issue_comment>username_3: [Here's a JSFiddle](https://jsfiddle.net/ta3pLnjs/1/). Like others have suggested, you want to output your buttons with a `class` instead of an `id`, to make your buttons easier to select with jQuery. Here's an example, with nice CSS. Your buttons should be formatted like this.
```
label
```
Here's a working SO Snippet.
```js
$('.toggle').click(function(){
$(this).toggleClass('green');
});
```
```css
.toggle {
background-color:#df0606;
padding:7px;
border:1px solid red;
color:white;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.toggle:hover {
background-color:#cd0101;
padding:7px;
border:1px solid red;
color:#ff2a31;
font-size:1.18em;
box-shadow:2px 4px #510809;
margin-left:4px;
margin-right:4px;
}
.green {
color:white;
padding:7px;
border:1px solid lime;
background-color:green;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.green:hover {
color:lime;
padding:7px;
border:1px solid lime;
background-color:#12de09;
font-size:1.18em;
box-shadow:2px 4px #044f12;
margin-left:4px;
margin-right:4px;
}
```
```html
These buttons generated with PHP:
One
Two
Three
Here's some text. Text text text.
```
Upvotes: 1 |
2018/03/19 | 812 | 2,465 | <issue_start>username_0: I am new to graphQL, When I am trying to define a schema with hyphen/dash it shows error. But underscore is not making any issues.
```
# Type of Hello
enum HowAreYou{
Hello-Hello
Hai-Hai
}
throw (0, _error.syntaxError)(source, position, 'Invalid number, expected digit but got: ' + printCharCode(code) + '.');
^
GraphQLError: Syntax Error GraphQL request (176:9) Invalid number, expected digit but got: "H".
175: enum HowAreYou{
176: Hello-Hello
^
177: Hai-Hai
```<issue_comment>username_1: The problem is with the `id`. It seems all the button will have same `id` which is wrong markup.
Try by replacing `id` with a common class
```
$button = ''
```
In js
```
$('.someCommonCLass').click(function(){
$(this).toggleClass('green');
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: As you are generating a list of buttons so you should use class instead of `id`
Try this:
```
$button = ''
$('.toggle').click(function(){
$(this).toggleClass('green');
});
```
Upvotes: 0 <issue_comment>username_3: [Here's a JSFiddle](https://jsfiddle.net/ta3pLnjs/1/). Like others have suggested, you want to output your buttons with a `class` instead of an `id`, to make your buttons easier to select with jQuery. Here's an example, with nice CSS. Your buttons should be formatted like this.
```
label
```
Here's a working SO Snippet.
```js
$('.toggle').click(function(){
$(this).toggleClass('green');
});
```
```css
.toggle {
background-color:#df0606;
padding:7px;
border:1px solid red;
color:white;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.toggle:hover {
background-color:#cd0101;
padding:7px;
border:1px solid red;
color:#ff2a31;
font-size:1.18em;
box-shadow:2px 4px #510809;
margin-left:4px;
margin-right:4px;
}
.green {
color:white;
padding:7px;
border:1px solid lime;
background-color:green;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.green:hover {
color:lime;
padding:7px;
border:1px solid lime;
background-color:#12de09;
font-size:1.18em;
box-shadow:2px 4px #044f12;
margin-left:4px;
margin-right:4px;
}
```
```html
These buttons generated with PHP:
One
Two
Three
Here's some text. Text text text.
```
Upvotes: 1 |
2018/03/19 | 675 | 2,559 | <issue_start>username_0: I want to make a validation when the user clik the jbutton1 if the textboxt field empty the jlabel value will show "Input name cannot be empty". I'm beginner.
Here my false code :
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.text == ""){
jLabel1.setText("Input name cannot be empty");
}else{
jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}
```<issue_comment>username_1: Use equals() instead of == as-
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.equals(""){
jLabel1.setText("Input name cannot be empty");
}else{
jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}
```
Upvotes: 1 <issue_comment>username_2: Avoid using `==` as it is not correct. `isEmpty()` method will do the trick. Make sure to `trim();` for removing any white spaces beforehand.
Try to use this :
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().trim().isEmpty()){
jLabel1.setText("Input name cannot be empty");
} else {
jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}
}
```
Upvotes: 1 <issue_comment>username_3: Use `.equals()` method of `String` instead of `==`. To get Text from `jTextField1` use `getText()` method.
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().equals(""){
jLabel1.setText("Input name cannot be empty");
}else{
jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}
```
Check this [What is the difference between == vs equals() in Java?](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java)
Upvotes: 0 <issue_comment>username_4: First, you need to replace all whitespace to check if the input has any characters and then compare the length or using .equals():
```
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = jTextField1.getText().replaceAll("\\s+","");
if(text.length() <= 0){
jLabel1.setText("Input name cannot be empty");
}else{
jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}
```
Upvotes: 0 |
2018/03/19 | 475 | 1,513 | <issue_start>username_0: I am trying to group items within a PHP foreach by their 'field->value' and get the sum of each group separately. This code below works, but I feel like there is a more efficient way of doing it?
Thanks in advance.
```html
php
$number_1 = 0;
$number_2 = 0;
$number_3 = 0;
foreach ( $fields as $field ) {
if($field-value == 1) {
$number_1 += $field->number;
}
if($field->value == 2) {
$number_2 += $field->number;
}
if($field->value == 3) {
$number_3 += $field->number;
}
}
echo $number_1;
echo $number_2;
echo $number_3;
?>
```<issue_comment>username_1: In this case you can use variable variables.
Generally I would rather recommend an array but it's your choice.
```
foreach ( $fields as $field ) {
${"number_" . $field->value} += $field->number;
}
```
Array version.
```
foreach ( $fields as $field ) {
$arr["number_" . $field->value] += $field->number;
}
// Either output as array or extract values to separate variables.
Echo $arr["number_1"];
//Or
Extract($arr);
Echo $number_1;
```
Edit had number where it should be value.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Don't use separate variables, use an array with `$field->value` as the index.
```
$numbers = array();
foreach ($fields as $field) {
if (isset($numbers[$field->value])) {
$numbers[$field->value] += $field->number;
} else {
$numbers[$field->value] = $field->number;
}
}
```
Upvotes: 1 |
2018/03/19 | 418 | 1,498 | <issue_start>username_0: I have a javascript function using jQuery to make a POST request to a web service. The web service response has a header "Set-Cookie: name=value; domain=api.mydomain.com; path=/", and a JSON body.
I expected the browser to set the cookie, but it does not. Am I mistaken about how this should work? Is there another way to make the browser set the cookie returned in the response header?
```
$.ajax(
{
type: "POST",
url: "https://api.mydomain.com/service",
data: body,
success: handleSuccess,
error: handleFailure
}
);
```<issue_comment>username_1: In this case you can use variable variables.
Generally I would rather recommend an array but it's your choice.
```
foreach ( $fields as $field ) {
${"number_" . $field->value} += $field->number;
}
```
Array version.
```
foreach ( $fields as $field ) {
$arr["number_" . $field->value] += $field->number;
}
// Either output as array or extract values to separate variables.
Echo $arr["number_1"];
//Or
Extract($arr);
Echo $number_1;
```
Edit had number where it should be value.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Don't use separate variables, use an array with `$field->value` as the index.
```
$numbers = array();
foreach ($fields as $field) {
if (isset($numbers[$field->value])) {
$numbers[$field->value] += $field->number;
} else {
$numbers[$field->value] = $field->number;
}
}
```
Upvotes: 1 |
2018/03/19 | 450 | 1,614 | <issue_start>username_0: I have imported a .csv file in my python program which contains a number of columns using pandas module. In my code, I just imported the first three columns. The code and the sample file are as follows.
```
import pandas as pd
fields = ['TEST ONE', 'TEST TWO', 'TEST THREE']
df1=pd.read_csv('List.csv', skipinitialspace=True, usecols=fields)
```
***sample file***

---
How can I find the difference of the columns **TEST ONE** and **TEST TWO** in my python program and store it in separate place/column/array inside the code so that the values can be extracted from it whenever needed. I want to find the mean and the maximum value of the new column which is generated as the difference of the first two columns.<issue_comment>username_1: ```
Difference = df1['TEST ONE'] - df['TEST TWO']
```
Difference will be pandas series. on that you can use mean and max
```
Difference.mean()
Difference.max()
```
Upvotes: 1 <issue_comment>username_2: Do something like this.
```
df1['diff'] = df1['TEST ONE'] - df1['TEST TWO']
#The Dataframe would be df1 throughout
# This will store it as a column of that same dataframe.
# When you need the difference, use that column just like normal pandas column.
mean_of_diff = df1['diff'].mean()
max_of_diff = df1['diff'].max()
# For third value of difference use the third index of dataframe
third_diff = df1.loc[2, 'diff']
```
Note: I have used 2 as index starts from 0. Also index can be a string or date as well. Pass approrpriate index value to get your desired result.
Upvotes: 3 [selected_answer] |
2018/03/19 | 813 | 2,602 | <issue_start>username_0: **Using google finance & yahoo finance currency conversion for codeigniter.. Worked fine for 2-4 months but now suddenly conversion getting disable in between??**
My Code Snippet (Helper File Code):
```
php
if (!function_exists('convertCurrency')) {
function convertCurrency($amount,$from_Currency,$to_Currency) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$get = @file_get_contents("https://finance.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency");
$get = explode("<span class=bld",$get);
$get = explode("",$get[1]);
$converted_currency = preg_replace("/[^0-9\.]/", null, $get[0]);
return number_format($converted_currency,2,'.','');
}
}
```
Calling that function in controllers as well as view files as below:
```
php echo convertCurrency($amount, "INR", "USD");?
```
**Worked well for 2-4 months but now its getting disable in between??**
**I also tried it with CURL, but not getting response from link.**
please suggest me proper idea??<issue_comment>username_1: Google has shutdown that service in these days.
The only alternative solutions I've found are :
* ~~<http://www.xe.com/it/currencyconverter/convert/?Amount=1&From=USD&To=EUR>~~ Warning : Automated extraction of rates is prohibited under the Terms of Use of xe.com
* free to use API (with some limits) <https://currencylayer.com/>
See also this response with other solutions : <https://stackoverflow.com/a/10040996/1798842>
Upvotes: 1 <issue_comment>username_2: The following code works. Give a try :)
```
$url = "http://www.xe.com/currencyconverter/convert/?
Amount=1&From=USD&To=INR";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('uccResultAmount', $rawdata);
@$data = explode('uccToCurrencyCode', $data[1]);
$amount = preg_replace('/[^0-9,.]/', '', $data[0]);
```
Upvotes: 0 <issue_comment>username_3: You can also use:
```
$res = file_get_contents("https://finance.google.com/bctzjpnsun/converter?a=1&from=USD&to=CAD");
```
it is google calculator and will work.
Now you have to parse this response:
```
$res = explode("",$res);
$res = explode("",$res[1]);
$rate= preg_replace("/[^0-9\.]/", null, $get[0]);
```
Upvotes: -1 |
2018/03/19 | 910 | 3,471 | <issue_start>username_0: I'm creating an activity for Sign up and Login with Firebase
I have a User class like this
```
public class User {
private final String mProviderId;
private final String mEmail;
private final String mPhoneNumber;
private final String mName;
private final Uri mPhotoUri;
}
```
When a user signs up for a new account I am doing this
```
auth.createUserWithEmailAndPassword(et_email.getText().toString(), et_pass.getText().toString())
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(AuthResult authResult) {
//Save User to db
User user = new User();
user.setmEmail(et\_email.getText().toString());
user.setmName(et\_fullname.getText().toString());
user.setPassword(<PASSWORD>());
//Use email to key
users.child(user.getEmail())
.setValue(user).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
//
}
});
}
});
```
So the primary\_key for each user is the email address
I wonder is there a way to use the push() method in Firebase to create a User (auto generate primary\_key) and get the key that Firebase provide for each User and store it in attribute "mProviderId"?, Is this the right way the create a User in Firebase?
Thanks for reading.
**Update date 3/22/2018 - think I found the answer**
After a few days of research and coding I found that the correct way to create a User is to use the UID (unique identifier) which Firebase auto generates for you. And store it in the Database along with the User's information (UID as key, User's information as value. This way is recommended by sir **@Doug Stevenson**.
You can do something like this:
```
firebaseAuth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
// Get User Firebase id
String uid = task.getResult().getUser().getUid();
// Create a User
User user = new User();
user.setUserProvideId(uid);
user.setUserName(name);
user.setUserPassword(<PASSWORD>);
// Put the User to the FirebaseDatabase with User's information. Use "uid" as a Key and user object as Value.
databaseReference.child("users").child(uid).setValue(user);
}
});
```
Thanks to everyone for answering my question.<issue_comment>username_1: Yes you can get push key from in this way.
```
String providerId = users.push().getKey();
users.setProviderId(providerId);
users.child(user.getEmail())
.set(user)...
```
Note: Push key is generated by firebase it is guranted to be unique.
if you are using firebase auth then `auth.getUser().getUid();` is also a better option to indicate unique user.
Hope this will help you.
Upvotes: 0 <issue_comment>username_2: It's conventional to use the uid (unique id) of the [FirebaseUser](https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseUser) to identify the location in the database where their information is stored. The uid is, by definition, unique.
```
String uid = authResult.getUser().getUid();
```
Upvotes: 2 <issue_comment>username_3: yes you can use firebase key because is genarate unique there for i am always used that key for id in table.
```
String id=mFirebaseDatabase.push().getKey();
User user = new User(id,name);
mFirebaseDatabase.child(id).setValue(user); // you can also used id as a child node.
```
Upvotes: 0 |
2018/03/19 | 476 | 1,626 | <issue_start>username_0: I'm new to programming so the question may be a little simple for most of the users, here's my question:
I want to use innerHTML to send info to a div tag that I have in my HTML
```
//I want the info to print inside this div
```
This is my JS code:
```
function asterisks(){
var line= 0 ;
var sum = "" ;
line= parseFloat(document.getElementById("numberBox1").value);
for (var i = 1; i <= line; i++) {
sum += "*";
console.log(sum);
}
document.getElementById("display").innerHTML += sum;
}
```
This is the basic ladder of asterisks that you may already know, using the:
console.log(sum);
In the console I, in fact see the next: (supposing a ladder of 5 asterisks)
```
*
**
***
****
*****
```
But in the div in my html I only see the last row, I mean:
```
*****
```
At this moment I already understood that what its happening is that the information is in fact printing just that it changes so fast that I only get to see the last line...why is happening this? Any help/ideas/comments will be much appreciated,
Thanks.<issue_comment>username_1: You have to do something like this.
```js
function asterisks(){
var line= 0 ;
var sum = "" ;
line= parseFloat(document.getElementById("numberBox1").value);
for (var i = 1; i <= line; i++) {
sum += "*";
console.log(sum);
document.getElementById("display").innerHTML += sum + "
";
}
}
```
```html
//I want the info to print inside this div
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use append in place of innerHTML which will concatenate all your output.
Upvotes: 0 |
2018/03/19 | 867 | 3,024 | <issue_start>username_0: I facing some error when i want to send some data on the server. And this the problem is when i converting the image into Base64 code, then it will create some problem. Please help me to resolve this issue. The data could not be in correct format and status code is 500. I don't know how to resolve this.
Error:
```
{ URL: http://192.168.1.58/api/visitor/store } { Status Code: 500, Headers {
"Cache-Control" = (
"no-cache, private"
);
Connection = (
close
);
"Content-Type" = (
"text/html; charset=UTF-8"
);
Date = (
"Mon, 19 Mar 2018 05:11:06 GMT"
);
Server = (
"Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1"
);
"Transfer-Encoding" = (
Identity
);
Vary = (
Authorization
);
"X-Powered-By" = (
"PHP/7.1.1"
);
"X-RateLimit-Limit" = (
60
);
"X-RateLimit-Remaining" = (
59
);
} }
The data couldn’t be read because it isn’t in the correct format.
```
My Code is :
```
func apiToSaveData(strURL: String)
{
let myURL = URL(string: strURL)
let request = NSMutableURLRequest(url: myURL!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let token = "Bearer " + strToken
request.setValue(token, forHTTPHeaderField: "Authorization")
var postString: [String : String] = ["" : ""]
if let navController = self.navigationController, navController.viewControllers.count >= 2
{
//Comes from After VerifyOTP after Returning Screen
let viewController = navController.viewControllers[navController.viewControllers.count - 2]
if viewController.restorationIdentifier == "VerifyOTP"
{
postString = ["image": strEncodedImg, "name": tfName.text!, "phone": tfMobile.text!, "email": tfEmail.text!, "otp": strOTP]
}
else if viewController.restorationIdentifier == "VisitorVC"
{
let imgObj = otlBtnTakeImage.imageView?.image
let imgData: Data = UIImagePNGRepresentation(imgObj!)!
let strEncodedImg1 = imgData.base64EncodedString()
print("ENcodedImage: \(strEncodedImg1)")
postString = ["image": strEncodedImg1, "name": tfName.text!, "phone": tfMobile.text!, "email": tfEmail.text!]
}
}
}
```<issue_comment>username_1: You have to do something like this.
```js
function asterisks(){
var line= 0 ;
var sum = "" ;
line= parseFloat(document.getElementById("numberBox1").value);
for (var i = 1; i <= line; i++) {
sum += "*";
console.log(sum);
document.getElementById("display").innerHTML += sum + "
";
}
}
```
```html
//I want the info to print inside this div
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use append in place of innerHTML which will concatenate all your output.
Upvotes: 0 |
2018/03/19 | 269 | 1,151 | <issue_start>username_0: I have some experience with Angular 1.x, and right now I am building a stack for couple of new projects.
* I want to have responsive grid, so I would like to use Bootstrap.
* I want to use Angular, so I am going with latest Angular
* I want to have material design... so I can choose <https://material.angular.io/>
... but I found <https://mdbootstrap.com/angular/>, which looks like some kind of combination of Bootstrap and Material Design which suppose to work as well with latest Angular.
I am confused and I am not sure what are main differences between those two approaches.<issue_comment>username_1: Material Angular allows you to use Flex Layout which gives you a responsive grid if you spend the time to learn it.
I've been using it for multiple projects and it is great.
Upvotes: 2 <issue_comment>username_2: Taking into account all your 3 requirements mdbootstrap sounds like a perfect match. It's built with Bootstrap 4 and Angular 6.
It has definitely more components and features than Material Angular, though the extended version is paid. You can check the free version (MIT) and give it a try.
Upvotes: 2 |
2018/03/19 | 357 | 1,329 | <issue_start>username_0: Am opening the aspx page in a popup from Window.open using javascript as below.
```
function OpenPopupWindow() {
var userWidth = screen.availWidth;
var userHeight = screen.availHeight;
leftPos = (userWidth - 500) / 2,
topPos = (userHeight - 500) / 2;
settings = 'modal,scrollBars=no,resizable=no,titlebar=no,status=no,toolbar=no,menubar=no,location=no,directories=no,left=' + leftPos + ',top=' + topPos + ',width=500, height=500';
window.open("EnhanceTerms.aspx", "window", settings);
}
```
As I expected, the address bar is not showing when i open this page in firefox and IE, but in Chrome it is still showing.
And also how to hide the minimize and maximize from the pop up.
please help me on this.<issue_comment>username_1: Material Angular allows you to use Flex Layout which gives you a responsive grid if you spend the time to learn it.
I've been using it for multiple projects and it is great.
Upvotes: 2 <issue_comment>username_2: Taking into account all your 3 requirements mdbootstrap sounds like a perfect match. It's built with Bootstrap 4 and Angular 6.
It has definitely more components and features than Material Angular, though the extended version is paid. You can check the free version (MIT) and give it a try.
Upvotes: 2 |
2018/03/19 | 507 | 2,054 | <issue_start>username_0: I am trying to add splash screen to my react native android app but its giving me weird behaviour whenever I get a (remote/local) notification and on click to the notification component mounting the screen again that already mounted by showing splash again. I added splash by following [this article](https://medium.com/handlebar-labs/how-to-add-a-splash-screen-to-a-react-native-app-ios-and-android-30a3cec835ae) of <NAME>.
I don't know this behaviour is because of the react native single activity android app or may be I am adding the splash activity above the main activity. I am using [this react-native-splash-screen package](https://github.com/crazycodeboy/react-native-splash-screen) .
I have also created a [git repo for the Splash test](https://github.com/Shhzdmrz/SplashTest) for the above approach. Please Have a look on it.
I also tried splash without adding another activity using [this rn-splash-screen package](https://github.com/mehcode/rn-splash-screen) but that will give me white screen before splash or you can say on the cold start.
As I am not a native android developer but I want to make a splash like twitter, uber which show splash on the cold start. [react-native-splash-screen package](https://github.com/crazycodeboy/react-native-splash-screen) giving me ability to show splash on cold start but because of the abouve mentioned issue I cannot use it. Can anyone please guide me how to resolve this issue and achieve this type of splash screen.<issue_comment>username_1: Material Angular allows you to use Flex Layout which gives you a responsive grid if you spend the time to learn it.
I've been using it for multiple projects and it is great.
Upvotes: 2 <issue_comment>username_2: Taking into account all your 3 requirements mdbootstrap sounds like a perfect match. It's built with Bootstrap 4 and Angular 6.
It has definitely more components and features than Material Angular, though the extended version is paid. You can check the free version (MIT) and give it a try.
Upvotes: 2 |
2018/03/19 | 510 | 1,651 | <issue_start>username_0: * if there are five "short numbers" or all six are "short numbers" (short number is 1 <= number < 25)
* if there are five "large numbers" or all six are "large numbers" (large number is defined as 25 <= number <= 49)
* if at least five out of six numbers are even
* if at least five out of six numbers are odd
* if at least three numbers are successive numbers (e.g., [13, 14, 15, 28, 35, 49] --> draw new six. Or another example is e.g., [5, 6, 7, 8, 21, 38] --> draw new six numbers)
I started programming the first two in my list:
```
import random
def lottery_six():
setOfSix = set()
while len(setOfSix) < 6:
setOfSix.add(random.randint(1,49))
lottery = list(setOfSix)
return lottery
def generateLottery(lottery):
abc = set()
while (all(i >= 25 for i in lottery) == True) or (all(i < 25 for i in lottery) == True) or \
(sum(i >= 25 for i in lottery) >= 5) or (sum(i < 25 for i in lottery) >= 5):
abc = lottery_six()
return abc
print(generateLottery(lottery_six()))
```
However, that does not work. Why? And how can I fix it?<issue_comment>username_1: Material Angular allows you to use Flex Layout which gives you a responsive grid if you spend the time to learn it.
I've been using it for multiple projects and it is great.
Upvotes: 2 <issue_comment>username_2: Taking into account all your 3 requirements mdbootstrap sounds like a perfect match. It's built with Bootstrap 4 and Angular 6.
It has definitely more components and features than Material Angular, though the extended version is paid. You can check the free version (MIT) and give it a try.
Upvotes: 2 |
2018/03/19 | 418 | 1,423 | <issue_start>username_0: **Below is my code**
```
HTML/PHP:
php $nay = $row['id']; ?
```
**Script:**
```
var idMap;
function myFunction(id) {
var x = document.getElementById("<?php echo $nay; ?>");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
```
**Desire Output:**
i want to connect the function to the onclick function by using ID but the problem i am facing is due to loop it is just working on the last value of the list whereas i want it to display to all the values displayed but it is not getting connected by the id.
Please help me with the connection of PHP and JS.<issue_comment>username_1: In the value of password just used.
[](https://i.stack.imgur.com/gSp59.jpg)
and in your onclick function just used.
```
onclick="myFunction(this.id)"
```
Upvotes: -1 <issue_comment>username_2: You have made mistake in javascript code.
In this line `var x = document.getElementById(id);` you were using php code so it was printing last row's id in js function. But it should be dynamic and passed through event caller function only to make it dynamic.
Use this code snippet and it should work fine.
```
function myFunction(id) {
var x = document.getElementById(id);
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
```
Upvotes: 1 [selected_answer] |
2018/03/19 | 473 | 1,620 | <issue_start>username_0: Trying to learn how to get a role name from the role table by linking it to the user table with role\_id in user table and user\_id in the role table.
I'm getting this error
```
Class 'App\Role' not found (View: C:\
```
All of my Role related files all reference role and files are names, RoleController and Role.php with a view called index.blade.php.
heres my role class:
```
php
namespace Laravel;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//
protected $fillable = [
'name',
];
public function users()
{
return $this-belongsToMany('App\User');
}
}
```
Its been pointed out to me its probably a namespace issue but everyting else seems to point to Laravel like RoleController has:
```
namespace Laravel\Http\Controllers;
use Laravel\Role;
use Illuminate\Http\Request;
```
and user model has:
```
namespace Laravel;
```
So Why is this not working for me? as far as I can tell everything is named right.<issue_comment>username_1: You should try this way:
**Role.php**
```
php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//
protected $fillable = [
'name',
];
public function users()
{
return $this-belongsToMany('App\User');
}
}
```
Use in `Controller` like:
```
use App\Role;
```
Upvotes: 1 <issue_comment>username_2: The `App` namespace is used default by Laravel, cause it use the *PSR-4 autoloading standard*.
If you want to use your `Laravel` namespace, try to change your application name `app:name` by the artisan command like this `php artisan app:name Laravel`
Upvotes: 1 [selected_answer] |
2018/03/19 | 296 | 811 | <issue_start>username_0: Draining of Dataflow streaming job does not end while 1 days.
No error log on stack driver also.
job ID is
>
> 2018-03-09\_00\_40\_49-15224076611250277770
>
>
> 2018-02-12\_22\_35\_23-4736481063361562693
>
>
>
What's the problem?
And, How can I know when this drainig job complete? (predict time)<issue_comment>username_1: Have you tried to update your job with higher machine type? Maybe it is just a too heavy process for it to drain (lots of data is included).
Upvotes: 0 <issue_comment>username_2: Streaming pipelines that throw unhandled exceptions while processing data currently can not be drained.
<https://issuetracker.google.com/issues/147124216>
<https://cloud.google.com/dataflow/docs/resources/faq#how-are-java-exceptions-handled-in-cloud-dataflow>
Upvotes: 1 |
2018/03/19 | 691 | 2,188 | <issue_start>username_0: I have included a gif image in react native project and its working perfectly in IOS without any issues.
my Js file
```
```
For android, I came across a library(FRESCO) which supports gif in android.
>
> compile 'com.facebook.fresco:animated-gif:1.8.1'
>
>
>
Android build.gradle
```
dependencies {
compile project(':react-native-sensitive-info')
compile project(':react-native-i18n')
compile project(':react-native-device-info')
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.facebook.react:react-native:+"
compile 'com.facebook.fresco:animated-gif:1.8.1'
}
```
Its not displaying gif after including this library.
I have tried some other versions of same library but its not working.
```
compile 'com.facebook.fresco:fresco:1.5.0'
compile 'com.facebook.fresco:animated-gif:1.5.0'
compile 'com.facebook.fresco:animated-gif:0.+'
compile 'com.facebook.fresco:animated-gif:0.12.0'
compile 'com.facebook.fresco:animated-base-support:0.14.1'
compile 'com.facebook.fresco:animated-gif:0.14.1'
```
If I use these below two lines application closes without any error.
```
compile 'com.facebook.fresco:fresco:1.8.1'
compile 'com.facebook.fresco:animated-gif:1.8.1'
```
Please help me how to resolve this.<issue_comment>username_1: Here in this way I resolved this.
1) Removed all existing Fresco dependencies like fresco.fresco , animated.gif etc..
2). Tried React-native-fast image based on community suggestions.Linked to both ios and android platforms. Getting error --Native component for fast image view does not exist. Dropped plan of using this npm library.
3) Added only below line to android/build-gradle .
>
> compile 'com.facebook.fresco:animated-gif:1.3.0'
>
>
>
4)Tap Sync Now option in android studio so that it will reflect grade changes.
5) Clean Project.
6) Rebuild Project.
you can take both debug and release builds.
It works fine.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Add in your `build.gradle`:
```
compile 'com.facebook.fresco:fresco:1.9.0'
compile 'com.facebook.fresco:animated-gif:1.9.0'
```
Upvotes: 1 |
2018/03/19 | 2,062 | 6,784 | <issue_start>username_0: Edit: When I first click the button, the text is printed in the left column (no matter which selection is made). When I click the button again, the text is printed in the right column (again, irrespective of the selection. I really don't get it.
I'm trying to print input from a form into a div. This is the source HTML in need to modify (it's for a university class):
```
Exercise
---------
Print
Choose left or right
Left column
Right column
#### Output
```
There's already some CSS inlcuded in the header:
```
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
What I need to achieve: text is entered into the field. Next, to the input field, there is an option to select either "left" or "right". Depending on the selection, the input is to be printed either in the left or right part of the screen on the click of a button. This is what I have - but it only prints to the left, no matter the selection. What am I missing?
```
jQuery(document).ready(function() {
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else {
$('div.right').html($('.input').val());
}
});
});
```
Sorry if this is very basic - I am completely new to JS and jQuery.<issue_comment>username_1: There's nothing wrong in your JS, just need basic styling to be done.
```js
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
Upvotes: 0 <issue_comment>username_2: give a name to select tag
```
$('select[name=selector]').val() === "left" )
```
Upvotes: -1 <issue_comment>username_3: [fiddle](https://jsfiddle.net/LtL0qdfx/7/)
HTML
```
Print
Left column
Right column
```
CSS
to make text align left or right base on the classname apply to the printValue element
```
.text-left{ text-align:left; }
.text-right{ text-align:right; }
```
JS
on positionChange first clear previously applied classes `text-left` or `text-right` and addClass based on dropdown value and change the current html on the element.
```
const positionChange = () => {
$(".printValue")
.removeClass("text-left")
.removeClass("text-right");
$(".printValue")
.addClass("text-"+$("#columnChange").val())
.html($(".input").val());
};
```
Two handler bind on change of dropdown value and on button click which call positionChange function once those event trigger.
```
$("#columnChange").on("change", () => {
positionChange();
});
$(".button").on("click", () => {
positionChange();
});
```
Upvotes: 0 <issue_comment>username_4: Your code is working fine. But for the view purpose, you didn't see changes happened it in a proper way. The reason behind is the floating elements not started in a new line. You can fix this in many ways.
**If you are ready to modify the HTML then you can use below solution.** Add your float elements inside one `div` like below.
```
Print
Left column
Right column
```
```js
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else {
$('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
**If you don't want to touch the HTML/CSS, you want to achieve it only through the JS then use below solution.** Just add or one empty div before the div has class `left` like below.
```
$('div.left').before('
'); //or
$('div.left').before('');
```
The idea is the same like first solution to start your floating `div` should start with the new line.
```js
$('div.left').before('
');
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") { $('div.left').html($('.input').val());
} else { $('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
**EDIT**
As per your new structure you have some of the questions.
`When I first click the button, the text is printed in the left column (no matter which selection is made). When I click the button again, the text is printed in the right column (again, irrespective of the selection.`
For fixing the above issue just add into your floating div. And do the proper checking in the `if` condition. Because if you didn't select anything from the dropdown, the value of the input is `Choose left or right`. So you have to check the value in both the cases of `if` condition like below.
```js
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else if ($('select').val() == "right"){
$('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1; clear:both;}
.left, .right {
float: left;
width:40%;
}
```
```html
Exercise
---------
Print
Choose left or right
Left column
Right column
#### Output
```
Upvotes: 0 |
2018/03/19 | 1,904 | 6,312 | <issue_start>username_0: i want to update two columns "ORDER\_NetTotal" which is of type TEXT and "ORDER\_TOTAL\_QTY" which is of type INTEGER with a where condition on "DBHelper.ORDER\_CONFIRM\_MASTER\_ID" which is primary key. The problem is that "ORDER\_TOTAL\_QTY" gets updated while "ORDER\_NetTotal" does not get updated with update query. below is my code.
```
public int updateOrderQtyMaster(int deliveryId, int newQty, Float newTotalAmount) {
Log.d("updateParameter : ", newQty + " " + newTotalAmount);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_NetTotal, String.valueOf(newTotalAmount));
values.put(DBHelper.ORDER_TOTAL_QTY, newQty);
Log.d("updateDelivery", values.toString());
try {
return db.update(DBHelper.TBL_ORDER_CONFIRM_MASTER, values, DBHelper.ORDER_CONFIRM_MASTER_ID + " = " + deliveryId, null);
} catch (Exception e) {
Utility.logCatMsg("Exception in updateOrderQtyMaster Method in SQLite: " + e.getMessage());
return 0;
}
}
```<issue_comment>username_1: There's nothing wrong in your JS, just need basic styling to be done.
```js
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
Upvotes: 0 <issue_comment>username_2: give a name to select tag
```
$('select[name=selector]').val() === "left" )
```
Upvotes: -1 <issue_comment>username_3: [fiddle](https://jsfiddle.net/LtL0qdfx/7/)
HTML
```
Print
Left column
Right column
```
CSS
to make text align left or right base on the classname apply to the printValue element
```
.text-left{ text-align:left; }
.text-right{ text-align:right; }
```
JS
on positionChange first clear previously applied classes `text-left` or `text-right` and addClass based on dropdown value and change the current html on the element.
```
const positionChange = () => {
$(".printValue")
.removeClass("text-left")
.removeClass("text-right");
$(".printValue")
.addClass("text-"+$("#columnChange").val())
.html($(".input").val());
};
```
Two handler bind on change of dropdown value and on button click which call positionChange function once those event trigger.
```
$("#columnChange").on("change", () => {
positionChange();
});
$(".button").on("click", () => {
positionChange();
});
```
Upvotes: 0 <issue_comment>username_4: Your code is working fine. But for the view purpose, you didn't see changes happened it in a proper way. The reason behind is the floating elements not started in a new line. You can fix this in many ways.
**If you are ready to modify the HTML then you can use below solution.** Add your float elements inside one `div` like below.
```
Print
Left column
Right column
```
```js
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else {
$('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
**If you don't want to touch the HTML/CSS, you want to achieve it only through the JS then use below solution.** Just add or one empty div before the div has class `left` like below.
```
$('div.left').before('
'); //or
$('div.left').before('');
```
The idea is the same like first solution to start your floating `div` should start with the new line.
```js
$('div.left').before('
');
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") { $('div.left').html($('.input').val());
} else { $('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
**EDIT**
As per your new structure you have some of the questions.
`When I first click the button, the text is printed in the left column (no matter which selection is made). When I click the button again, the text is printed in the right column (again, irrespective of the selection.`
For fixing the above issue just add into your floating div. And do the proper checking in the `if` condition. Because if you didn't select anything from the dropdown, the value of the input is `Choose left or right`. So you have to check the value in both the cases of `if` condition like below.
```js
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else if ($('select').val() == "right"){
$('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1; clear:both;}
.left, .right {
float: left;
width:40%;
}
```
```html
Exercise
---------
Print
Choose left or right
Left column
Right column
#### Output
```
Upvotes: 0 |
2018/03/19 | 2,645 | 9,006 | <issue_start>username_0: I am integrating my website with my phone to send sms using smsGatway.me i have already downloaded the apk every thing is fine the problem is with the php code i have downloaded from their website it has many errors
This is the oho code
```
php
class SmsGateway {
static $baseUrl = "https://smsgateway.me";
function __construct($email,$password) {
$this-email = $email;
$this->password = $password;
}
function createContact ($name,$number) {
return $this->makeRequest('/api/v3/contacts/create','POST',['name' => $name, 'number' => $number]);
}
function getContacts ($page=1) {
return $this->makeRequest('/api/v3/contacts','GET',['page' => $page]);
}
function getContact ($id) {
return $this->makeRequest('/api/v3/contacts/view/'.$id,'GET');
}
function getDevices ($page=1)
{
return $this->makeRequest('/api/v3/devices','GET',['page' => $page]);
}
function getDevice ($id)
{
return $this->makeRequest('/api/v3/devices/view/'.$id,'GET');
}
function getMessages($page=1)
{
return $this->makeRequest('/api/v3/messages','GET',['page' => $page]);
}
function getMessage($id)
{
return $this->makeRequest('/api/v3/messages/view/'.$id,'GET');
}
function sendMessageToNumber($to, $message, $device, $options=[]) {
$query = array_merge(['number'=>$to, 'message'=>$message, 'device' => $device], $options);
return $this->makeRequest('/api/v3/messages/send','POST',$query);
}
function sendMessageToManyNumbers ($to, $message, $device, $options=[]) {
$query = array_merge(['number'=>$to, 'message'=>$message, 'device' => $device], $options);
return $this->makeRequest('/api/v3/messages/send','POST', $query);
}
function sendMessageToContact ($to, $message, $device, $options=[]) {
$query = array_merge(['contact'=>$to, 'message'=>$message, 'device' => $device], $options);
return $this->makeRequest('/api/v3/messages/send','POST', $query);
}
function sendMessageToManyContacts ($to, $message, $device, $options=[]) {
$query = array_merge(['contact'=>$to, 'message'=>$message, 'device' => $device], $options);
return $this->makeRequest('/api/v3/messages/send','POST', $query);
}
function sendManyMessages ($data) {
$query['data'] = $data;
return $this->makeRequest('/api/v3/messages/send','POST', $query);
}
private function makeRequest ($url, $method, $fields=[]) {
$fields['email'] = $this->email;
$fields['password'] = $<PASSWORD>;
$url = smsGateway::$baseUrl.$url;
$fieldsString = http_build_query($fields);
$ch = curl_init();
if($method == 'POST')
{
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fieldsString);
}
else
{
$url .= '?'.$fieldsString;
}
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER , false); // we want headers
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec ($ch);
$return['response'] = json_decode($result,true);
if($return['response'] == false)
$return['response'] = $result;
$return['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);
return $return;
}
}
```
?>
and the error from wammp is like these

DOES IT HAS ANY THING WITH CURL I HAVE ALREADY ENABLED CURL BUT STILL HAVE THE ERROR ...PLEASE HELP ME<issue_comment>username_1: There's nothing wrong in your JS, just need basic styling to be done.
```js
jQuery(document).ready(function(){
$('.button').click(function(){
$('.input').val();
if ($('select').val() == "left"){
$('div.left').html($('.input').val());
}
else {
$('div.right').html($('.input').val());
}
});
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
Upvotes: 0 <issue_comment>username_2: give a name to select tag
```
$('select[name=selector]').val() === "left" )
```
Upvotes: -1 <issue_comment>username_3: [fiddle](https://jsfiddle.net/LtL0qdfx/7/)
HTML
```
Print
Left column
Right column
```
CSS
to make text align left or right base on the classname apply to the printValue element
```
.text-left{ text-align:left; }
.text-right{ text-align:right; }
```
JS
on positionChange first clear previously applied classes `text-left` or `text-right` and addClass based on dropdown value and change the current html on the element.
```
const positionChange = () => {
$(".printValue")
.removeClass("text-left")
.removeClass("text-right");
$(".printValue")
.addClass("text-"+$("#columnChange").val())
.html($(".input").val());
};
```
Two handler bind on change of dropdown value and on button click which call positionChange function once those event trigger.
```
$("#columnChange").on("change", () => {
positionChange();
});
$(".button").on("click", () => {
positionChange();
});
```
Upvotes: 0 <issue_comment>username_4: Your code is working fine. But for the view purpose, you didn't see changes happened it in a proper way. The reason behind is the floating elements not started in a new line. You can fix this in many ways.
**If you are ready to modify the HTML then you can use below solution.** Add your float elements inside one `div` like below.
```
Print
Left column
Right column
```
```js
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else {
$('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
**If you don't want to touch the HTML/CSS, you want to achieve it only through the JS then use below solution.** Just add or one empty div before the div has class `left` like below.
```
$('div.left').before('
'); //or
$('div.left').before('');
```
The idea is the same like first solution to start your floating `div` should start with the new line.
```js
$('div.left').before('
');
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") { $('div.left').html($('.input').val());
} else { $('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1;}
.left, .right {
float: left;
width: 40%;
}
```
```html
Print
Left column
Right column
```
**EDIT**
As per your new structure you have some of the questions.
`When I first click the button, the text is printed in the left column (no matter which selection is made). When I click the button again, the text is printed in the right column (again, irrespective of the selection.`
For fixing the above issue just add into your floating div. And do the proper checking in the `if` condition. Because if you didn't select anything from the dropdown, the value of the input is `Choose left or right`. So you have to check the value in both the cases of `if` condition like below.
```js
$('.button').click(function() {
$('.input').val();
if ($('select').val() == "left") {
$('div.left').html($('.input').val());
} else if ($('select').val() == "right"){
$('div.right').html($('.input').val());
}
});
```
```css
h3 {font-family: helvetica;}
body {background-color: #ededed;}
.main {margin: auto; margin-top: 100px; font-family: helvetica; max-width: 900px; }
.content {background-color: white; padding: 40px;}
footer {text-align: center;}
#output {background-color: #F2F5F1; clear:both;}
.left, .right {
float: left;
width:40%;
}
```
```html
Exercise
---------
Print
Choose left or right
Left column
Right column
#### Output
```
Upvotes: 0 |
2018/03/19 | 1,160 | 3,931 | <issue_start>username_0: Hi I have a list with Person class as follows
```
public class person
{
public int age;
public string name;
}
```
I am trying to do the following.
```
static void Main(string[] args)
{
List person1 = new List();
person1.Add(new person { age = 10, name = "P1" });
person1.Add(new person { age = 11, name = "Q1" });
person1.Add(new person { age = 12, name = "R1" });
List person2 = new List(person1);
person2[0].name = "P2";
Console.WriteLine("---------Person1---------");
foreach (person P in person1)
{
Console.WriteLine("Age=" + P.age);
Console.WriteLine("Name=" + P.name);
}
Console.WriteLine("---------Person2---------");
foreach (person P in person2)
{
Console.WriteLine("Age=" + P.age);
Console.WriteLine("Name=" + P.name);
}
}
```
The Output is that the value of first object in both the lists is changed to P2 while I expect to change it only in `person2` list. I thought the list items would be copied into `person2` list.
MSDN [here](https://msdn.microsoft.com/en-us/library/fkbw11z0(v=vs.110).aspx) says that the elements are copied to the new list which is not happening in above case. what am I missing here?<issue_comment>username_1: The mistake you're making here is with reference variables. What's held in the list are references to objects of type `person`. When you copy the list, it only copies the references to these objects, so each list contains references to exactly the same set of objects.
For a more in depth example of what I'm talking about, consider the following code:
```
person me = new person { age = 20, name = "username_1" };
person you = me;
you.name = "Programmerzzz";
Console.WriteLine(me.name); // Outputs Programmerzzz
```
This is essentially what you're doing in your example. The `me` variable doesn't get copied, a reference to it just gets passed to the `you` variable. Then the object at that reference location is changed. The key here being that both variables point to the same location.
If you want to make a deep copy of the list, you'll have to do so manually. For example:
```
List person2 = new List();
foreach (person p in person1) {
person2.Add(new person { age = p.age, name = p.name });
}
```
For more reading about reference types, see [this excellent explanation](https://stackoverflow.com/a/5057284/8718143).
Upvotes: 1 <issue_comment>username_2: Class is copy by reference, struct is copy by value.
So you change the people's value , you will link to a original reference.
```
public Struct person
{
public int age;
public string name;
}
```
And if you use struct, try again, you will see different
Upvotes: 0 <issue_comment>username_3: You're copying by reference and not by value. First thing to do is fix your class. So you can create 'person' objects using a constructor. The code below creates a new object rather than copying the reference of the former list.
```
public static void Main()
{
Console.WriteLine("Program Started!");
List person1 = new List();
person1.Add(new person(10, "P1" ));
person1.Add(new person( 11, "Q1" ));
person1.Add(new person(12, "R1" ));
List person2 = new List();
foreach(person p in person1)
{
person2.Add(new person(p)); //WE COPY BY VALUE. BY ALLOCATING SPACE FOR A NEW OBJECT.
}
person2[0].name = "P2";
Console.WriteLine("---------Person1---------");
foreach (person P in person1)
{
Console.WriteLine("Age=" + P.age);
Console.WriteLine("Name=" + P.name);
}
Console.WriteLine("---------Person2---------");
foreach (person P in person2)
{
Console.WriteLine("Age=" + P.age);
Console.WriteLine("Name=" + P.name);
}
Console.WriteLine("Program Ended!");
Console.ReadKey();
}
public class person
{
public int age;
public string name;
public person(person p) {
this.age = p.age;
this.name = p.name;
}
public person(int \_age, string \_name)
{
this.age = \_age;
this.name = \_name;
}
}
```
Upvotes: 0 |
2018/03/19 | 1,882 | 7,425 | <issue_start>username_0: I'm seeking help on how to load a data stored in a Firebase Database into a `recyclerview`.
The below screenshot indicates how I would like for the data to be structured when loaded into the `recyclerview`.
I am able to access the data from individual paths such as "Upcoming/Events/03/23" using the `addEventListener` but unable to load dynamically into a `recyclerview` in the format above.
See Code below that I have below to load the children under the different nodes, but i'm able to load it into the `recyclerview`
```
private ListView mUserList;
private ArrayList mUpcomingList = new ArrayList<>();
final ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple\_expandable\_list\_item\_1,mUpcomingList);
mUserList.setAdapter(arrayAdapter);
String CurrentString = date.toString().trim();
StringTokenizer tokens = new StringTokenizer(CurrentString, "/");
String first = tokens.nextToken();
String second = tokens.nextToken();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Upcoming/Events").child(first);
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
Public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"Listing children");
for (DataSnapshot child: dataSnapshot.getChildren()) {
mUpcomingList.add(child.getKey());
arrayAdapter.notifyDataSetChanged();
}
```
Your help is appreciated.<issue_comment>username_1: when you used then you make recyclerview adatper and bind this adapter into a recycler view . used below code for display firebase all the data and change according your need and make changes.
RecyclerView Adapter::
```
public class DisplayAllData extends RecyclerView.Adapter{
private List mUserLsit=new ArrayList<>();
private Context mContext;
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row\_layout,parent,false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext,List mUserLsit) {
this.mContext=mContext;
this.mUserLsit = mUserLsit;
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user=mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
@Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName,mTvEmail,mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail=itemView.findViewById(R.id.rlTvEmail);
mTvName=itemView.findViewById(R.id.rlTvName);
mTvPwd=itemView.findViewById(R.id.rlTvPwd);
}
}
}
```
In Adapter take a simple layout and make three textview control and bind data into that.
then after take activity layout and define recycler view in xml. then after used below code to read firebase database record and display recyclerview.
```
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List mUserList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display\_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
```
Upvotes: 2 <issue_comment>username_2: You have to use **FirebaseRecyclerAdapter**,
as
```
FirebaseRecyclerAdapter Adapter = new FirebaseRecyclerAdapter(
Model.class, //Name of model class
R.layout.row, //Row layout to show data
viewHolder.class, //Name of viewholder class
mDatabaseRef // Database Refernce
) {
@Override
protected void populateViewHolder(VieHolder viewHolder, Model model, int position) {
//Your Method to load Data
}
};
RecyclerView.setAdapter(Adapter);
```
For this you have to create two other classes, One is viewholder ( to display data) and second model class ( refers to name of nodes from where you are fetching data ).
Upvotes: 2 <issue_comment>username_3: ```
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder()
.setQuery(cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products"), Cart.class).build();
FirebaseRecyclerAdapter adapter =
new FirebaseRecyclerAdapter(options) {
@Override
protected void onBindViewHolder(@NonNull CartViewHolder holder, int position, @NonNull final Cart model) {
holder.txtProductQuantity.setText("Quantity = " + model.getQuantity());
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "৳");
int oneTypeProductPrice = ((Integer.valueOf(model.getPrice()))) \* Integer.valueOf(model.getQuantity());
overTotalPrices = overTotalPrices + oneTypeProductPrice;
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
Intent intent = new Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
if (i == 1){
cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(CartActivity.this,"Item removed successfully.",Toast.LENGTH\_LONG).show();
Intent intent = new Intent(CartActivity.this, HomeActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart\_items\_layout, parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
```
Upvotes: 0 |
2018/03/19 | 2,014 | 7,642 | <issue_start>username_0: I have 3 pages to implement this scenario.
Currently,
1. If I go to the first page and, click to navigate to the 2nd page. And then, on the 2nd page, I click the back button. It works fine (i.e, Navigates to 1st page).
2. Now, from 1st page, I go to the second page and, click to navigate to the 3rd page. And then, in the 3rd page, I click on back button, it redirects to the 2nd page as expected.
Now if I click on the back button on the second page, it goes to the 3rd page again. Where I want that to be redirected to the 1st page.
Here, actually according to code, it is working fine but my requirement is that
1. i have 2 pages company and companyApp where both pages have same guide and pin pages.. So, i want the guide page to redirect to company page, if i had been to guide page from company page even though guide page has been and come from images page.
2. If i had been to guide page from compnay app page then it must redirect to company app page even though it is again directed to images page and all.
So, can anyone help me to solve this:
TS:
```
// 1st Page:
goToGuide1(company){
this.router.navigate(['/guide',company.user._id]);
}
// 2nd page:
import {Location} from '@angular/common';
constructor(private _location: Location) {}
goToCompany1() {
this._location.back();
}
goImg(guide) {
this.router.navigate(['/guideimg', guide._id]);
}
// 3rd page
goToGuide1() {
this.router.navigate(['/guide',this.user_id])
}
```
Here on the 2nd page:
If I go to the Image page and click on back button, it comes to the guide page but doesn't go to the 1st page.<issue_comment>username_1: when you used then you make recyclerview adatper and bind this adapter into a recycler view . used below code for display firebase all the data and change according your need and make changes.
RecyclerView Adapter::
```
public class DisplayAllData extends RecyclerView.Adapter{
private List mUserLsit=new ArrayList<>();
private Context mContext;
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row\_layout,parent,false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext,List mUserLsit) {
this.mContext=mContext;
this.mUserLsit = mUserLsit;
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user=mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
@Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName,mTvEmail,mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail=itemView.findViewById(R.id.rlTvEmail);
mTvName=itemView.findViewById(R.id.rlTvName);
mTvPwd=itemView.findViewById(R.id.rlTvPwd);
}
}
}
```
In Adapter take a simple layout and make three textview control and bind data into that.
then after take activity layout and define recycler view in xml. then after used below code to read firebase database record and display recyclerview.
```
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List mUserList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display\_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
```
Upvotes: 2 <issue_comment>username_2: You have to use **FirebaseRecyclerAdapter**,
as
```
FirebaseRecyclerAdapter Adapter = new FirebaseRecyclerAdapter(
Model.class, //Name of model class
R.layout.row, //Row layout to show data
viewHolder.class, //Name of viewholder class
mDatabaseRef // Database Refernce
) {
@Override
protected void populateViewHolder(VieHolder viewHolder, Model model, int position) {
//Your Method to load Data
}
};
RecyclerView.setAdapter(Adapter);
```
For this you have to create two other classes, One is viewholder ( to display data) and second model class ( refers to name of nodes from where you are fetching data ).
Upvotes: 2 <issue_comment>username_3: ```
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder()
.setQuery(cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products"), Cart.class).build();
FirebaseRecyclerAdapter adapter =
new FirebaseRecyclerAdapter(options) {
@Override
protected void onBindViewHolder(@NonNull CartViewHolder holder, int position, @NonNull final Cart model) {
holder.txtProductQuantity.setText("Quantity = " + model.getQuantity());
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "৳");
int oneTypeProductPrice = ((Integer.valueOf(model.getPrice()))) \* Integer.valueOf(model.getQuantity());
overTotalPrices = overTotalPrices + oneTypeProductPrice;
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
Intent intent = new Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
if (i == 1){
cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(CartActivity.this,"Item removed successfully.",Toast.LENGTH\_LONG).show();
Intent intent = new Intent(CartActivity.this, HomeActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart\_items\_layout, parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
```
Upvotes: 0 |
2018/03/19 | 1,720 | 6,613 | <issue_start>username_0: When I am trying to run one of my Java application (which is deployed in IBM Websphere App server), I am getting the below error,
>
> java.lang.UnsatisfiedLinkError: PATH/file.so (EDC5253S An AMODE64
> application is attempting to load an AMODE31 DLL load module.
> (errno2=**some\_address**)) at
> java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:1344)
>
>
>
Did anyone face the same issue of AMODE64 ?
Or could someone provide info on how to compile code to AMODE64.
Any reference in this would also be of great help.
Thanks in advance.<issue_comment>username_1: when you used then you make recyclerview adatper and bind this adapter into a recycler view . used below code for display firebase all the data and change according your need and make changes.
RecyclerView Adapter::
```
public class DisplayAllData extends RecyclerView.Adapter{
private List mUserLsit=new ArrayList<>();
private Context mContext;
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row\_layout,parent,false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext,List mUserLsit) {
this.mContext=mContext;
this.mUserLsit = mUserLsit;
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user=mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
@Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName,mTvEmail,mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail=itemView.findViewById(R.id.rlTvEmail);
mTvName=itemView.findViewById(R.id.rlTvName);
mTvPwd=itemView.findViewById(R.id.rlTvPwd);
}
}
}
```
In Adapter take a simple layout and make three textview control and bind data into that.
then after take activity layout and define recycler view in xml. then after used below code to read firebase database record and display recyclerview.
```
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List mUserList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display\_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
```
Upvotes: 2 <issue_comment>username_2: You have to use **FirebaseRecyclerAdapter**,
as
```
FirebaseRecyclerAdapter Adapter = new FirebaseRecyclerAdapter(
Model.class, //Name of model class
R.layout.row, //Row layout to show data
viewHolder.class, //Name of viewholder class
mDatabaseRef // Database Refernce
) {
@Override
protected void populateViewHolder(VieHolder viewHolder, Model model, int position) {
//Your Method to load Data
}
};
RecyclerView.setAdapter(Adapter);
```
For this you have to create two other classes, One is viewholder ( to display data) and second model class ( refers to name of nodes from where you are fetching data ).
Upvotes: 2 <issue_comment>username_3: ```
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder()
.setQuery(cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products"), Cart.class).build();
FirebaseRecyclerAdapter adapter =
new FirebaseRecyclerAdapter(options) {
@Override
protected void onBindViewHolder(@NonNull CartViewHolder holder, int position, @NonNull final Cart model) {
holder.txtProductQuantity.setText("Quantity = " + model.getQuantity());
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "৳");
int oneTypeProductPrice = ((Integer.valueOf(model.getPrice()))) \* Integer.valueOf(model.getQuantity());
overTotalPrices = overTotalPrices + oneTypeProductPrice;
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
Intent intent = new Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
if (i == 1){
cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(CartActivity.this,"Item removed successfully.",Toast.LENGTH\_LONG).show();
Intent intent = new Intent(CartActivity.this, HomeActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart\_items\_layout, parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
```
Upvotes: 0 |
2018/03/19 | 1,636 | 6,349 | <issue_start>username_0: I got this question from one of the Person:-
A user enters the software name
in this format `\_\_.tar.gz` Like: `OW_XYZ_5.4.tar.gz`
Find if the input file name is in valid formate(tar.gz) and if it contain all 3 part of the name.
Please help me to solve this question using javascript/jquery.<issue_comment>username_1: when you used then you make recyclerview adatper and bind this adapter into a recycler view . used below code for display firebase all the data and change according your need and make changes.
RecyclerView Adapter::
```
public class DisplayAllData extends RecyclerView.Adapter{
private List mUserLsit=new ArrayList<>();
private Context mContext;
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row\_layout,parent,false);
return new ItemViewHolder(view);
}
public DisplayAllData(Context mContext,List mUserLsit) {
this.mContext=mContext;
this.mUserLsit = mUserLsit;
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
User user=mUserLsit.get(position);
holder.mTvName.setText(user.name);
holder.mTvEmail.setText(user.email);
holder.mTvPwd.setText(user.pwd);
}
@Override
public int getItemCount() {
return mUserLsit.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView mTvName,mTvEmail,mTvPwd;
public ItemViewHolder(View itemView) {
super(itemView);
mTvEmail=itemView.findViewById(R.id.rlTvEmail);
mTvName=itemView.findViewById(R.id.rlTvName);
mTvPwd=itemView.findViewById(R.id.rlTvPwd);
}
}
}
```
In Adapter take a simple layout and make three textview control and bind data into that.
then after take activity layout and define recycler view in xml. then after used below code to read firebase database record and display recyclerview.
```
public class DisplayActivity extends AppCompatActivity {
private RecyclerView mRvData;
private DisplayAllData allDataAdapter;
private DatabaseReference mDatabase;
private TextView mTvEmpty;
private FirebaseDatabase mFirebaseInstance;
private List mUserList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display\_data);
initView();
}
private void initView() {
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mRvData = findViewById(R.id.rvData);
mTvEmpty = findViewById(R.id.dlTvEmpty);
mRvData.setLayoutManager(new LinearLayoutManager(this));
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user);
}
allDataAdapter = new DisplayAllData(DisplayActivity.this, mUserList);
mRvData.setAdapter(allDataAdapter);
allDataAdapter.notifyDataSetChanged();
if (mUserList.isEmpty())
mTvEmpty.setVisibility(View.VISIBLE);
else
mTvEmpty.setVisibility(View.GONE);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
```
Upvotes: 2 <issue_comment>username_2: You have to use **FirebaseRecyclerAdapter**,
as
```
FirebaseRecyclerAdapter Adapter = new FirebaseRecyclerAdapter(
Model.class, //Name of model class
R.layout.row, //Row layout to show data
viewHolder.class, //Name of viewholder class
mDatabaseRef // Database Refernce
) {
@Override
protected void populateViewHolder(VieHolder viewHolder, Model model, int position) {
//Your Method to load Data
}
};
RecyclerView.setAdapter(Adapter);
```
For this you have to create two other classes, One is viewholder ( to display data) and second model class ( refers to name of nodes from where you are fetching data ).
Upvotes: 2 <issue_comment>username_3: ```
final DatabaseReference cartListRef = FirebaseDatabase.getInstance().getReference().child("Cart List");
FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder()
.setQuery(cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products"), Cart.class).build();
FirebaseRecyclerAdapter adapter =
new FirebaseRecyclerAdapter(options) {
@Override
protected void onBindViewHolder(@NonNull CartViewHolder holder, int position, @NonNull final Cart model) {
holder.txtProductQuantity.setText("Quantity = " + model.getQuantity());
holder.txtProductName.setText(model.getPname());
holder.txtProductPrice.setText("Price = " + model.getPrice() + "৳");
int oneTypeProductPrice = ((Integer.valueOf(model.getPrice()))) \* Integer.valueOf(model.getQuantity());
overTotalPrices = overTotalPrices + oneTypeProductPrice;
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CharSequence options[] = new CharSequence[]
{
"Edit",
"Remove"
};
AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
builder.setTitle("Cart Options");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0){
Intent intent = new Intent(CartActivity.this, ProductDetailsActivity.class);
intent.putExtra("pid", model.getPid());
startActivity(intent);
}
if (i == 1){
cartListRef.child("User View")
.child(Prevalent.currentOnlineUser.getPhoneNumber())
.child("Products")
.child(model.getPid())
.removeValue()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(CartActivity.this,"Item removed successfully.",Toast.LENGTH\_LONG).show();
Intent intent = new Intent(CartActivity.this, HomeActivity.class);
startActivity(intent);
}
}
});
}
}
});
builder.show();
}
});
}
@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart\_items\_layout, parent, false);
CartViewHolder holder = new CartViewHolder(view);
return holder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
```
Upvotes: 0 |
2018/03/19 | 1,134 | 3,999 | <issue_start>username_0: Basically an integer variable should allow only integer values to be set for its variable. Then how come such special words as follows are allowed?
```
int a = 200L;
int a = 200U;
int a = 200F;
```
I found this when i run the program, it ran perfectly without giving any error. Other letters are not allowed as expected. But why these?<issue_comment>username_1: L, U and F means long, unsigned and float respectively.
so, the code means
```
int a = (long) 200;
int a = (unsigned) 200;
int a = (float) 200;
```
Upvotes: 0 <issue_comment>username_2: What you do is called implicit conversion.
If you are using gcc compiler you can add
```
-Wconversion
```
(not part of -Wall) option to check any implicit conversion that may alter the value.
Without any option, conversion from signed to unsigned is not warned by default. So you need to active
```
-Wsign-conversion
```
If you want an explicit conversion, it will not be warned by those 2 options.
```
int percent = (int)((int)4.1)*.5;
```
Upvotes: 0 <issue_comment>username_3: What happens is that you are telling the compiler to convert the value into a different type of data. That is to say:
```
int a = 200L; // It's like saying: Hey C++, convert this whole to Long
int a = 200U; // And this to Unsigned
int a = 200F; // And this one to Float
```
There is no error because the compiler understands that these letters at the end indicate a type of conversion.
Upvotes: -1 <issue_comment>username_4: Two different things are going on here.
1) Some letters when stuck on the end of a number take on meaning. 'l' is for long, 'u' is for unsigned, and 'f' is for float.
* "Long" is generally 64 bits wide vs int's 32 bits... but that can
vary wildly from machine to machine. DO NOT depend on bit width of
int and long.
* "Unsigned" means it doesn't bother to track positive or
negative values... assuming everything is positive. This about
doubles how high an integer can go. Look up "two's complement" for
further information.
* "Float" means "floating point". Non whole numbers. 1.5, 3.1415, etc. They can be very large, or very precise, but not both. Floats ARE 32 bits. "Double" is a 64-bit floating point value, which can permit some extreme values of size or precision.
2) Type Coercion, pronounced "co ER shun".
The compiler knows how to convert (coerce) from long to int, unsigned to int, or float to int. They're all just numbers, right? Note that converting from float to into "truncates" (drops) anything after a decimal place. `((int)3.00000001) == 3`. `((int)2.9999999) == 2`
If you dial your warnings up to max sensitivity, I believe those statements will all trigger warnings because all those conversions could potentially lose data... though the exact phrasing of that warning will vary from compiler to compiler.
***Bonus Information:***
You can trigger this same behavior (accidentally) with classes.
```
struct Foo {
Foo(int bar) {...}
};
Foo baz = 42;
```
The compiler will treat the above constructor as an option when looking to convert from int to Foo. The compiler is willing to hop through more than one hoop to get there... so `Foo qux = 3.14159;` would also compile. This is also true of other class constructors... so if you have some other class that takes a foo as it's only constructor param, you can declare a variable of that class and assign it something that can be coerced to a foo... and so on:
```
struct Corge {
Corge(Foo foo) {...}
};
corge grault = 1.2345; // you almost certainly didn't intend what will happen here
```
That's three layers of coercion. double to int, into to foo, and foo to corge. Bleh!
You can block this with the `explicit` keyword:
```
struct Foo {
explicit Foo(int bar) {...}
};
Foo baz = 1; // won't compile
```
I wish they'd made `explicit` the default and used some keyword to define conversion constructors instead, but that change would almost certainly break someone's code, so it'll never happen.
Upvotes: 0 |
2018/03/19 | 393 | 1,237 | <issue_start>username_0: Suppose I have table `employee`
```
+--------------+--------+------------+
| id | e_name | leder_id |
+--------------+--------+------------+
| 1 | abc | 2 |
| 2 | def | 4 |
| 3 | ghi | 2 |
| 4 | jkl | 1 |
| 5 | mno | 3 |
+--------------+--------+------------+
```
...and I want output like this by using SQL. where every `e_name` has a leader and their `leder_id` is given.
```
+--------------+---------+
|e_name | l_name |
+--------------+--------+
| abc | def |
| def | jkl |
| ghi | def |
| jkl | abc |
| mno | ghi |
+--------------+--------+
```<issue_comment>username_1: Do the *SELF JOIN*
```
SELECT
e.e_name, el.e_name as l_name
FROM employee e
INNER JOIN employee el on el.id = e.leder_id
```
In case some employee has no any leader use `LEFT OUTER JOIN` instead.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here you go :
```
SELECT
e.e_name as e_name ,
l.e_name as l_name
FROM
employee e,
employee l
WHERE
e.leder_id = l.id
```
Upvotes: 2 |
2018/03/19 | 537 | 1,702 | <issue_start>username_0: I am trying to upload files larger than 1Mb with spring boot
```
hereorg.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl.(FileUploadBase.java:618) ~[tomcat-embed-core-8.5.28.jar:8.5.28]
```<issue_comment>username_1: If you are using application.yml
```
spring:
http:
multipart:
enabled: true
max-file-size: 50MB
max-request-size: 50MB
```
or
If you are using application.properties
```
spring.http.multipart.max-file-size=50MB
spring.http.multipart.max-request-size=50MB
```
Hope it will works
Upvotes: 2 <issue_comment>username_2: File uploading problem solved by this configuration in application.yml:
```
spring:
data:
mongodb:
host: localhost
port: 27017
database: testone
servlet:
multipart:
enabled: true
maxFileSize: 500MB
maxRequestSize: 500MB
file-size-threshold: 500MB
```
Upvotes: 2 <issue_comment>username_3: If you are using Spring 2.0 or higher add the below code which is working for me
>
> application.properties
>
>
>
```
spring.servlet.multipart.max-file-size=128MB
spring.servlet.multipart.max-request-size=128MB
spring.servlet.multipart.enabled=true
```
>
> application.yml
>
>
>
```
spring:
http:
multipart:
enabled: true
max-file-size: 128MB
max-request-size: 128MB
```
If you just want to control the `multipart properties` then `multipart.max-file-size` and `multipart.max-request-size` properties should work.
Upvotes: 3 |
2018/03/19 | 781 | 2,920 | <issue_start>username_0: I am trying to display a simple form (3 fields) on a webpage using Django but no fields are displaying - see code below.
I've gone through the Django doc, MDN doc, most of the StackOverflow posts here, but it's still not working.
I was able to see, using {% debug %}, that there is no object `EmailInput` on the page.
At this point, I am not sure what is causing this issue. Any help would be very much appreciated.
Thanks
---
**forms.py**
```
from django import forms
class EmailInput(forms.Form):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
```
**views.py**
```
from django.shortcuts import render
from .models import journalEntry
from django.http import HttpResponseRedirect
from django.urls import reverse
from journal.forms import EmailInput
def index(request):
post = journalEntry.objects.filter(status__exact='f')
latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5]
return render(request, 'journal_index.html', context = {'post':post,'latest_post':latest_post})
def email_input(request):
if request.method == 'POST':
form = EmailInput(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('journal-index'))
else:
form = EmailInput()
return render(request, 'journal_index.html',{'form':form})
```
**journal\_index.html**
```
{% extends "base_generic.html" %}
{% block content %}
{% csrf\_token %}
{{ form }}
{% endblock content %}
```
**urls.py**
from django.conf.urls import url
from . import views
```
urlpatterns = [
url(r'^$', views.index, name='journal-index'),
]
```<issue_comment>username_1: It is because you are not even calling email\_input.
you need to bind it to a url like this `urlpatterns = [
url(r'^$', views.email_input),
]`
Upvotes: 0 <issue_comment>username_2: If you want to display it in the index page then you have to send it as a context variable in your `index` function. And now it will be available in your `journal_index.html` template file.
```
def index(request):
post = journalEntry.objects.filter(status__exact='f')
latest_post = journalEntry.objects.filter(status__exact='f').order_by('-created')[:5]
form = EmailInput()
context = {
'post': post,
'latest_post': latest_post,
'form': form
}
return render(request, 'journal_index.html', context = context)
```
The code from your `email_input` function is not called anywhere so there is no way this form could be displayed. Also you have to figure out where do you want to display this form. If you don't want to display it together with the stuff from your index page then you would have to create a new template file, add the form there and add a new url path to display that page.
Upvotes: 2 [selected_answer] |
2018/03/19 | 699 | 2,210 | <issue_start>username_0: I have a problem with my ajax, it can't display data from database.
**Controller**
```
public function rating() {
$rating = $this->db->select_avg('hasil_rating')
->get('tb_rating')->row_array();
echo json_encode($rating);
}
```
**Ajax**
```
function rate() {
$.ajax({
type: 'POST',
url: 'php echo base_url()."rate/rating"?',
dataType: 'json',
success: function(data) {
$('#aaaa').val(data);
}
});
```
**input**
```
```
when I used `val()` the result is **[object Object]** and when I used `html()` the result is **empty**. But when I use `console.log(data)` it works.<issue_comment>username_1: You need to first decode the json in your ajax success.
Use this.
```
function rate() {
$.ajax({
type: 'POST',
url: 'php echo base_url()."rate/rating"?',
dataType: 'json',
success: function(data) {
var d = $.parseJSON(data);
$('#aaaa').val(d.value);
}
});
```
Using this you can access different values from data and set the value in your html.
Update
------
In your controller you can return the value using json\_encode like
```
echo json_encode(array("success"=>true,"msg1"=>"test ajax","msg2"=>"test ajax 2"));
```
In your ajax success function to get the value of msg1 you can use
```
var d = $.parseJSON(data);
alert(d.msg1); //will return "test ajax"
alert(d.msg2); //will return "test ajax 2"
```
By this way you can access each and every value from your json object.
Upvotes: 0 <issue_comment>username_2: Just convert json object to string and it will work.
```
$('#aaaa').val(data.someVar);
```
For example,
```
var jsonVal = {val1:'one',val2:'two'};
alert(jsonVal); // it will print [object][object]
alert(jsonVal.val1); // one
alert(jsonVal.val2); // two
alert(JSON.stringify(jsonVal)) // it will print {val1:'one',val2:'two'}
```
Hope it will help you.
Upvotes: 2 [selected_answer]<issue_comment>username_3: You have to require **$.pasrseJSON** before use the data
```
function rate() {
$.ajax({
type: 'POST',
url: 'php echo base_url()."rate/rating"?',
dataType: 'json',
success: function(data) {
data=$.parseJSON(data);
$('#aaaa').val(data.var_name);
}
});
```
Upvotes: 0 |
2018/03/19 | 832 | 3,019 | <issue_start>username_0: I had been trying to store a field as type keyword to support case-sensitive text search,
But when I try to store text with length above 32766 characters it is failing to store it, giving the below exception
```
Elasticsearch exception [type=illegal_argument_exception, reason=Document contains at least one immense term in field="case_message_message.lowcase" (whose UTF8 encoding is longer than the max length 32766), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '[-32, -80, -84, -32, -79, -122, -32, -80, -126, -32, -80, -105, -32, -80, -77, -32, -79, -126, -32, -80, -80, -32, -79, -127, 58, 32, -32, -80, -107, -32]...', original message: bytes can be at most 32766 in length; got 37632]
```
Is there is any way to store this text above 32766,
Elastic search version 6.1.2
Any help is really appreciated.
UPDATE 1:
This is the mapping of my index I had using a custom normalizer and also normalizer
```
{
"org-16-database": {
"mappings": {
"org-16-table": {
"properties": {
"My field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
},
"lowcase": {
"type": "keyword",
"normalizer": "my_normalizer"
}
},
"fielddata": true
}
}
}
}
}
}
```
Settings
```
{
"org-16-database": {
"settings": {
"index": {
"number_of_shards": "5",
"provided_name": "org-16-database",
"creation_date": "1521198435444",
"analysis": {
"normalizer": {
"my_normalizer": {
"filter": [
"lowercase"
],
"type": "custom"
}
}
},
"number_of_replicas": "1",
"uuid": "lN-7iYloQWy7oaD3uMIYGQ",
"version": {
"created": "6010299"
}
}
}
}
}
```<issue_comment>username_1: Can you try with the Length Token filter
Vist : <https://www.elastic.co/guide/en/elasticsearch/reference/6.1/analysis-length-tokenfilter.html#analysis-length-tokenfilter>
Upvotes: 0 <issue_comment>username_2: As written in the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/ignore-above.html) when you create a new keyword field, by default is enabled the param ignore\_above. This option is also useful for protecting against Lucene’s term byte-length limit of 32766. You could increase this limit modifying your mapping, without reindex. The max value allowed is 10922
Upvotes: 1 |
2018/03/19 | 1,013 | 2,929 | <issue_start>username_0: I am trying to make the deploy of my microservice in docker, but I have a problem with the petitions, I made the MS in dotnet core 2 with postgresql in Ubuntu 16.04. I don't know if the error is the dockerfile or the docker-compose.yml or the deploy. I have these files like this:
### dockerfile
```
FROM microsoft/dotnet:2.0-sdk
WORKDIR /rooms_ms
# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
#RUN dotnet ef database update
ENTRYPOINT ["dotnet", "out/rooms_ms.dll"]
```
### docker-compose.yml
```
version: '2'
services:
rooms_ms:
build:
context: ./
dockerfile: dockerfile
environment:
DB_CONNECTION_STRING: "host=postgres_image;port=5432;
database=2E_room_db;username=username;password=<PASSWORD>"
rooms_db:
image: postgres:alpine
ports:
- "5432:5432"
environment:
POSTGRES_USER: "username"
POSTGRES_PASSWORD: "<PASSWORD>"
POSTGRES_DB: "2E_room_db"
```
### terminal
```
~/Documents/room_ms$ docker-compose up
Starting roomms_rooms_db_1 ...
Recreating roomms_rooms_ms_1 ... done
Attaching to roomms_rooms_db_1, roomms_rooms_ms_1
rooms_db_1 | 2018-03-19 05:12:21.281 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
rooms_db_1 | 2018-03-19 05:12:21.281 UTC [1] LOG: listening on IPv6 address "::", port 5432
rooms_ms_1 | warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
rooms_ms_1 | No XML encryptor configured. Key {c7c3f612-32d0-454c-9501-e51dc159e9b4} may be persisted to storage in unencrypted form.
rooms_ms_1 | Hosting environment: Production
rooms_db_1 | 2018-03-19 05:12:21.703 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
rooms_ms_1 | Content root path: /rooms_ms
rooms_ms_1 | Now listening on: http://localhost:4040
rooms_db_1 | 2018-03-19 05:12:23.579 UTC [17] LOG: database system was shut down at 2018-03-19 05:08:59 UTC
```
### Postman
[postman response](https://i.stack.imgur.com/vSlHT.png)
### Docker rancher
[rancher node with the microservice and database](https://i.stack.imgur.com/b9LP4.png)
I hope you can help me with this problem, thank you very much.<issue_comment>username_1: Can you try with the Length Token filter
Vist : <https://www.elastic.co/guide/en/elasticsearch/reference/6.1/analysis-length-tokenfilter.html#analysis-length-tokenfilter>
Upvotes: 0 <issue_comment>username_2: As written in the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/ignore-above.html) when you create a new keyword field, by default is enabled the param ignore\_above. This option is also useful for protecting against Lucene’s term byte-length limit of 32766. You could increase this limit modifying your mapping, without reindex. The max value allowed is 10922
Upvotes: 1 |
2018/03/19 | 343 | 1,066 | <issue_start>username_0: I'm new to regex, so I've done a bit research.
My filter should only allow:
* a-Z
* 0-9 (meaning 0 to 9)
* ()
* []
I've found [this](https://stackoverflow.com/questions/2896450/allow-only-a-za-z0-9-in-string-using-php) regex:
```
"/^[a-zA-Z0-9]+$/"
```
I edited it to allow ()
```
"/^[a-zA-Z0-9()]+$/"
```
But how to make the regex allowing [] too? Seems like [] need to be escaped somehow.<issue_comment>username_1: Can you try with the Length Token filter
Vist : <https://www.elastic.co/guide/en/elasticsearch/reference/6.1/analysis-length-tokenfilter.html#analysis-length-tokenfilter>
Upvotes: 0 <issue_comment>username_2: As written in the [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/ignore-above.html) when you create a new keyword field, by default is enabled the param ignore\_above. This option is also useful for protecting against Lucene’s term byte-length limit of 32766. You could increase this limit modifying your mapping, without reindex. The max value allowed is 10922
Upvotes: 1 |
2018/03/19 | 533 | 1,492 | <issue_start>username_0: I have 2 tables as follows:
tbl\_emp
```
emp_code name
1 A
2 B
3 C
4 D
```
tbl\_from\_to
```
col_from col_to
4 2
1 2
2 3
3 4
```
what I wanted is an output like this:
```
res_from res_to
D B
A B
B C
C D
```
I tried:
```
select emp.name, emp.name
from tbl_emp emp
join tbl_from_to
on emp.emp_code = ft.col_from
or --also tried and
emp.emp_code = ft.col_to
```
and the result is like this
```
res_from res_to
D D
A A
B B
C C
```<issue_comment>username_1: Try joining the bridge table to the employee table *twice*:
```
SELECT
t1.name AS res_from,
t2.name AS res_to
FROM tbl_from_to tf
LEFT JOIN tbl_emp t1
ON tf.col_from = t1.emp_code
LEFT JOIN tbl_emp t2
ON tf.col_to = t2.emp_code;
```
[](https://i.stack.imgur.com/5jhBC.png)
The demo below is given in SQL Server (because I struggle to set up Oracle demos), but it should literally run cut-and-paste into Oracle.
[Demo
----](http://rextester.com/NBGC56473)
Upvotes: 3 [selected_answer]<issue_comment>username_2: This ought to do the trick:
```
select e1.name as res_from, e2.name as res_to
from tbl_from_to ft
join tbl_emp e1 on e1.emp_code = ft.col_from
join tbl_emp e2 on e1.emp_code = ft.col_to
```
I hope this helps.
Upvotes: 2 |
2018/03/19 | 646 | 1,705 | <issue_start>username_0: Schema is like this
```
{
"_id":ObjectId('5aaa41f96f69440f82ef45a7')
"name":"test",
"password" : "<PASSWORD>",
"userInfo" : {
"userName" : "usha",
"organization" : [1,2]
}
}
```
If i am using a query like this then it is replacing userInfo object rather then updating it.
```
db.user.update({"_id":ObjectId('5aaa41f96f69440f82ef45a7')},{$set :{"userInfo":{"userName":"kanha"}}})
after using this query it is giving this result
{
"_id":ObjectId('5aaa<PASSWORD>')
"name":"test",
"password" : "<PASSWORD>",
"userInfo" : {
"userName" : "kanha"
}
}
```
It is deleting organizations from userInfo
expected Result
```
{
"_id":ObjectId('5aaa41f9<PASSWORD>')
"name":"test",
"password" : "<PASSWORD>",
"userInfo" : {
"userName" : "kanha",
"organization" : [1,2]
}
}
```<issue_comment>username_1: Try joining the bridge table to the employee table *twice*:
```
SELECT
t1.name AS res_from,
t2.name AS res_to
FROM tbl_from_to tf
LEFT JOIN tbl_emp t1
ON tf.col_from = t1.emp_code
LEFT JOIN tbl_emp t2
ON tf.col_to = t2.emp_code;
```
[](https://i.stack.imgur.com/5jhBC.png)
The demo below is given in SQL Server (because I struggle to set up Oracle demos), but it should literally run cut-and-paste into Oracle.
[Demo
----](http://rextester.com/NBGC56473)
Upvotes: 3 [selected_answer]<issue_comment>username_2: This ought to do the trick:
```
select e1.name as res_from, e2.name as res_to
from tbl_from_to ft
join tbl_emp e1 on e1.emp_code = ft.col_from
join tbl_emp e2 on e1.emp_code = ft.col_to
```
I hope this helps.
Upvotes: 2 |
2018/03/19 | 620 | 1,889 | <issue_start>username_0: I'm trying to write a simple code in order to read the stdin then use it so I tried to type little program in order to put my stdin in a defined size table and it looks like this:
```
#include
#include
#include
#include
int main(int argc, char \*argv[]){
int c , i = 0 ;
char str[1024];
while(c != EOF){
c = fgetc(stdin);
str[i]=c;
i++;
}
printf("%s\n",str);
return 0;
}
```
When I run the program with
```
$ test < file.json
```
I get:
```
{
"num": 8
}�@/�
```
I can't explain the last four undefined characters. I'm guessing it's relative to the `fgetc()` pointer. I want to stop at the EOF.
I've looked everywhere, and I can't understand. I'm still learning C language, so my goal is to read the stdin which is a JSON file with the command
```
$ test < file.json
```
then use Jansson to extract and use the data, but my problem is reading the file with that command.<issue_comment>username_1: You need to null-terminate your string :
```
while (c != EOF) {
c = fgetc(stdin);
str[i]=c;
i++;
}
str[i] = '\0';
```
And yes, you should initialize `c` prior to checking if it is `EOF`.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Three problems:
* `%s` expects a NUL-terminated string, but you did not add a NUL.
* You are checking the value of `c` before assigning a value to `c`.
* Your buffer can only hold 1023 characters plus a NUL, but you have no check for that.
Fixed:
```
int main() {
size_t len = 0;
size_t size = 1024;
char* str = malloc(size);
while (1) {
int c = fgetc(stdin);
if (c == EOF)
break;
str[len++] = c;
if (len == size) {
size = (double)size * 1.2;
str = realloc(str, size);
}
}
str[len] = 0;
...
free(str);
return 0;
}
```
(Doesn't check for `malloc` and `realloc` errors.)
Upvotes: 1 |
2018/03/19 | 571 | 1,888 | <issue_start>username_0: I want to implement a process as below:
When a http request is in progress, display a loader. When the requests finish hide the loader.<issue_comment>username_1: >
> I assume that you want to show a loader when a http request is on progress.
>
>
>
```
import axios from 'axios'
export default {
data: () => {
loading: false
},
methods: {
makeRequest () {
this.loading = true //the loading begin
axios.get('/example')
.then(response => { ... }) // code to run on success
.catch(error => { ... }) // code to run on error
.finally(() => (this.loading = false)) // set loading to false when request finish
}
}
}
```
*Note that I am using [axios](https://github.com/axios/axios) in the example, but the logic works with other htpp libraries or [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)*
Upvotes: 6 [selected_answer]<issue_comment>username_2: **Only for Nuxt.js users**
the example that roli wrote up is great, but ideally **you don't want to repeat yourself** on every request that you make. so I would suggest you do like this
thanks to: <https://stackoverflow.com/a/58084093/1031297>
Add ['@nuxtjs/axios']....
Add or Modify **plugins/axios.js**
```
export default ({ app, $axios ,store }) => {
$axios.interceptors.request.use((config) => {
store.commit("SET_DATA", { data:true, id: "loading" });
return config;
}, (error) => {
return Promise.reject(error);
});
$axios.interceptors.response.use((response) => {
store.commit("SET_DATA", { data:false, id: "loading" });
return response;
}, (error) => {
return Promise.reject(error);
});
}
```
**with the store being**
```
export default {
state: () => ({
loading: false
}),
mutations: {
SET_DATA(state, { id, data }) {
state[id] = data
}
},
actions: {
}
}
```
Upvotes: -1 |
2018/03/19 | 2,387 | 9,153 | <issue_start>username_0: I am inserting and updating the records through the same button. But I want the primary key(req\_no) to be auto generated during insert operation only and not on update. How to do it ?
Getting the error: Failed to convert parameter value from a String to a Decimal at cmnd.ExecuteNonQuery();
here is the code:
```
public partial class Service_master : System.Web.UI.Page
{
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["constring"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
Session["UserName"] = "laxmi";
this.TextBox9.Text = DateTime.Today.ToString("dd/MMM/yyyy");
lb1.Text = Session["UserName"].ToString();
if (!IsPostBack)
{
BindDropDownList();
BindDropDowns();
Bindservcd();
}
}
private void Autogenrate()
{
int r;
try
{
con.Open();
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
string sqlcmd = "Select max(req_no)as req_no from service_master";
OleDbCommand cmd = new OleDbCommand(sqlcmd, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
string d = dr[0].ToString();
if (d == "")
{
TextBox1.Text = "1" ;
}
else
{
r = Convert.ToInt32(dr[0]);
r = r + 1;
TextBox1.Text = r.ToString();
}
}
con.Close();
}
catch (Exception ex)
{
WebMsgBox.Show("null is not allowed");
}
}
public bool uniquereq_no(string req_no)
{
string strreqno;
string querye = "select count(req_no) as req_no from service_master where req_no='"+ this.TextBox1.Text.ToString()+"'" ;
OleDbCommand cmnd = new OleDbCommand(querye, con);
OleDbDataReader dr;
dr = cmnd.ExecuteReader();
while (dr.Read())
{
try
{
strreqno = dr["req_no"].ToString();
return (strreqno != "0");
if (strreqno != "0")
{
WebMsgBox.Show("already exists");
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
protected void Button1_Click(object sender, EventArgs e)
{
string UserName = "UserName";
Session["UserName"] = lb1.Text;
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
TextBox TextBox9 = (TextBox)FindControl("TextBox9");
TextBox TextBox2 = (TextBox)FindControl("TextBox2");
TextBox TextBox3 = (TextBox)FindControl("TextBox3");
TextBox TextBox4 = (TextBox)FindControl("TextBox4");
DropDownList DropDownList3 = (DropDownList)FindControl("DropDownList3");
DropDownList DropDownList1 = (DropDownList)FindControl("DropDownList1");
TextBox TextBox5 = (TextBox)FindControl("TextBox5");
TextBox TextBox6 = (TextBox)FindControl("TextBox6");
DropDownList DropDownList2 = (DropDownList)FindControl("DropDownList2");
TextBox TextBox7 = (TextBox)FindControl("TextBox7");
TextBox TextBox8 = (TextBox)FindControl("TextBox8");
{
con.Open();
OleDbCommand cmnd = con.CreateCommand();
cmnd.CommandType = CommandType.StoredProcedure;
if (uniquereq_no(TextBox1.Text)== true)
{
cmnd.CommandText = "upd_ser_mas";
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value =
Convert.ToString(this.TextBox1.Text);
cmnd.Parameters.Add("xreq_dt", OleDbType.Date).Value =
Convert.ToDateTime(TextBox9.Text);
cmnd.Parameters.Add("xreq_by", OleDbType.VarChar, 7).Value = Convert.ToString(Session["UserName"]);
cmnd.Parameters.Add("xser_cd", OleDbType.VarChar, 16).Value = Convert.ToString(TextBox3.Text);
cmnd.Parameters.Add("xserv_desc", OleDbType.VarChar, 40).Value = Convert.ToString(TextBox4.Text);
cmnd.Parameters.Add("xserv_grp_cd", OleDbType.VarChar, 3).Value = Convert.ToString(DropDownList3.SelectedItem.Value);
cmnd.Parameters.Add("xbase_uom_cd", OleDbType.VarChar, 3).Value = Convert.ToString(DropDownList1.SelectedItem.Value);
cmnd.Parameters.Add("xsac_cd", OleDbType.VarChar, 16).Value = Convert.ToString(TextBox5.Text);
cmnd.Parameters.Add("xser_long_desc", OleDbType.VarChar, 100).Value = Convert.ToString(TextBox6.Text);
cmnd.Parameters.Add("xtax_ind", OleDbType.Char, 1).Value = Convert.ToString(DropDownList2.SelectedItem.Value);
cmnd.Parameters.Add("xactive_ind", OleDbType.Char, 1).Value = Convert.ToString(TextBox7.Text);
cmnd.Parameters.Add("xdel_ind", OleDbType.Char, 1).Value = Convert.ToString(TextBox8.Text);
WebMsgBox.Show("Data Successfully Updated");
}
else
{
Autogenrate();
cmnd.CommandText = "ins_ser_mas";
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = Convert.ToString(this.TextBox1.Text);
cmnd.Parameters.Add("xreq_dt", OleDbType.Date).Value = Convert.ToDateTime(TextBox9.Text);
cmnd.Parameters.Add("xreq_by", OleDbType.VarChar, 7).Value = Convert.ToString(Session["UserName"]);
cmnd.Parameters.Add("xser_cd", OleDbType.VarChar, 16).Value = Convert.ToString(TextBox3.Text);
cmnd.Parameters.Add("xserv_desc", OleDbType.VarChar, 40).Value = Convert.ToString(TextBox4.Text);
cmnd.Parameters.Add("xserv_grp_cd", OleDbType.VarChar, 3).Value = Convert.ToString(DropDownList3.SelectedItem.Value);
cmnd.Parameters.Add("xbase_uom_cd", OleDbType.VarChar, 3).Value = Convert.ToString(DropDownList1.SelectedItem.Value);
cmnd.Parameters.Add("xsac_cd", OleDbType.VarChar, 16).Value = Convert.ToString(TextBox5.Text);
cmnd.Parameters.Add("xser_long_desc", OleDbType.VarChar, 100).Value = Convert.ToString(TextBox6.Text);
cmnd.Parameters.Add("xtax_ind", OleDbType.Char, 1).Value = Convert.ToString(DropDownList2.SelectedItem.Value);
cmnd.Parameters.Add("xactive_ind", OleDbType.Char, 1).Value = Convert.ToString(TextBox7.Text);
cmnd.Parameters.Add("xdel_ind", OleDbType.Char, 1).Value = Convert.ToString(TextBox8.Text);
WebMsgBox.Show("The data for request number" + TextBox1.Text + "is saved");
}
cmnd.ExecuteNonQuery();
con.Close();
}
}
```<issue_comment>username_1: `OleDbType.Numeric` has equivalent data type of `System.Decimal` as given in [`OleDbType` enumeration reference](https://support.microsoft.com/en-us/help/320435/info-oledbtype-enumeration-vs-microsoft-access-data-types). You need to use decimal conversion with `decimal.Parse` or `Convert.ToDecimal` for this line since `TextBox1.Text` returns string value:
```
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = decimal.Parse(this.TextBox1.Text);
```
Or you can use safer `decimal.TryParse` method:
```
decimal xreqNo;
bool isDecimalValue = decimal.TryParse(this.TextBox1.Text, out xreqNo);
if (isDecimalValue)
{
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = xreqNo;
}
```
Upvotes: 1 <issue_comment>username_2: Few things in your code could be corrected
1) No need to use `ExecuteReader`. Use `ExecuteScalar` instead. Since its just one value being returned. (In `SQL` mentioned after point 2 below)
2) Changed `sql` query to do the +1 part of code. (*If your db supports ISNull)*. Otherwise there could be something similar in your db.
```
//SQL query will find max and will do +1
var sqlcmd = "Select IsNull(max(req_no),0) + 1 as req_no from service_master";
var cmd = new OleDbCommand(sqlcmd, con);
var outval = cmd.ExecuteScalar();
//now outval will have value
TextBox1.Text = outval.ToString();
```
3) You are assigning `string` values to parameters but the types assigned are different.
```
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = Convert.ToString(this.TextBox1.Text);
```
TextBox1.Text is itself `string`, you dont have to use `Convert.ToString`. OR use correct conversion like `Convert.ToInt32`, etc since your parameter is `OledbType.Numeric`, etc
Also, Why you have to use `FindControl`? Remove `FindControl`
```
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
```
`TextBox1` can be referred directly.
Upvotes: 0 |
2018/03/19 | 687 | 2,210 | <issue_start>username_0: tell me please how the figure for example 1222333,00 make the format thus 1 222 333.00 in php
```
echo "|";
echo " ";
echo $rs->Fields(1)->Name();
echo " |";
echo " ";
echo round(($rs->Fields(1)->value\*1),3)."";
echo " |";
echo "
";
```<issue_comment>username_1: `OleDbType.Numeric` has equivalent data type of `System.Decimal` as given in [`OleDbType` enumeration reference](https://support.microsoft.com/en-us/help/320435/info-oledbtype-enumeration-vs-microsoft-access-data-types). You need to use decimal conversion with `decimal.Parse` or `Convert.ToDecimal` for this line since `TextBox1.Text` returns string value:
```
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = decimal.Parse(this.TextBox1.Text);
```
Or you can use safer `decimal.TryParse` method:
```
decimal xreqNo;
bool isDecimalValue = decimal.TryParse(this.TextBox1.Text, out xreqNo);
if (isDecimalValue)
{
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = xreqNo;
}
```
Upvotes: 1 <issue_comment>username_2: Few things in your code could be corrected
1) No need to use `ExecuteReader`. Use `ExecuteScalar` instead. Since its just one value being returned. (In `SQL` mentioned after point 2 below)
2) Changed `sql` query to do the +1 part of code. (*If your db supports ISNull)*. Otherwise there could be something similar in your db.
```
//SQL query will find max and will do +1
var sqlcmd = "Select IsNull(max(req_no),0) + 1 as req_no from service_master";
var cmd = new OleDbCommand(sqlcmd, con);
var outval = cmd.ExecuteScalar();
//now outval will have value
TextBox1.Text = outval.ToString();
```
3) You are assigning `string` values to parameters but the types assigned are different.
```
cmnd.Parameters.Add("xreq_no", OleDbType.Numeric, 8).Value = Convert.ToString(this.TextBox1.Text);
```
TextBox1.Text is itself `string`, you dont have to use `Convert.ToString`. OR use correct conversion like `Convert.ToInt32`, etc since your parameter is `OledbType.Numeric`, etc
Also, Why you have to use `FindControl`? Remove `FindControl`
```
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
```
`TextBox1` can be referred directly.
Upvotes: 0 |
2018/03/19 | 270 | 963 | <issue_start>username_0: My question is about how to make searching query with two option. for example search by name and by keyword with sqlite database in android. can i make two tables for name and keyword or just one table?<issue_comment>username_1: Something like this should work:
```
Cursor cusror = db.rawQuery("SELECT * FROM " + TABLE_A + " WHERE " + column_1_id + " = " + col_1_value + " AND " + column_2_id + " = " + col_2_value);
```
In your case, one table should be enough with `name` and `keyword` as column. Modify above query as required, like below.
```
column_1_id -> name
column_2_id -> keyword
```
Upvotes: 1 <issue_comment>username_2: you can make single table and insert record when you search that time fire sql search query like below ..
```
String selectQuery = "SELECT * FROM " + MY_ITEMS_TABLE_NAME + " WHERE name=" + namevalue +", keyword=" +keywordvalue;
Cursor c = db.rawQuery(selectQuery, null);
```
Upvotes: 0 |
2018/03/19 | 701 | 2,759 | <issue_start>username_0: I am new to react and was experimenting when I noticed a behavior with controlled form elements. I have a controlled input element whose value is bound to the state of the parent component and its onChange handler takes the typed value from the user and updates the state. So every-time, the user types something, the input value reflects the change. This is the desirable effect. It works great when the input is created in the render function. But in case , the input is initialized through a class variable which is set in the constructor, the same input does not update its value when state changes. The only difference being where the input element is initialized first. What would cause such a behavior?
Any help is appreciated!
Here is an example of what code that causes the faulty behavior might look like:
```js
class App extends React.Component {
constructor(props){
super(props);
this.state = {
val : '',
}
this.handleChange = this.handleChange.bind(this);
this.input = (
);
}
handleChange(e){
this.setState({val:e.target.value});
}
render() {
return (
{ this.input ? this.input : null }
);
}
}
```
```html
```<issue_comment>username_1: You have stored (or cached) your input into a variable outside of the render. So when your component updates, it just renders the cached version of your input again and again.
You need to define `this.input` as a function returning the , like this:
```
this.input = () => (
);
```
And call `this.input()` in the render. Now, the input will be updated at each render.
However, if what you want is just to create a reference to the input (`this.input`), **I would rather recommend to make this reference inside the render, by using [the special prop `ref`](https://reactjs.org/docs/refs-and-the-dom.html)**:
```
render() {
(this.input = input)} // the magic happens here
/>
}
```
In doing so, you don't need to define `this.input` as a function in your constructor.
Upvotes: 2 <issue_comment>username_2: The constructor for a React component is called only before it is mounted.
If you define some variable in constructor, it will store its value not reference and will not be re render again.
Refer [react constructor](https://reactjs.org/docs/react-component.html#constructor)
The functions which are called on props/state change are
* componentWillReceiveProps()
* shouldComponentUpdate()
* componentWillUpdate()
* render()
* componentDidUpdate()
and in case you want to store the reference of any element, you can use **refs**.
```
render() {
(this.input = ele)}
/>
}
```
read more about [refs](https://reactjs.org/docs/refs-and-the-dom.html)
Upvotes: 3 [selected_answer] |
2018/03/19 | 666 | 2,083 | <issue_start>username_0: For the given array
```
int arr[0] = {0,1,0,0,0};
```
I need to return the starting index of the longest run of 0's
So in this case
`findIndex(arr)`
would return another array `result = {2,3}`. 2 represents the starting index of the run and 3 represents the length of the run.
Here's my attempt which can only find the length but not the index
```
int findLongestConseqSubseq(int arr[], int n)
{
int max = 1;
int current = 1;
int i;
for (i = 1; i < n; i++) {
if (arr[i - 1] == arr[i])
{ /* the run continues */
current++;
max = current > max ? current : max;
}
else
{ /* the run was broken */
current = 1;
}
}
return max;
}
```
Any ideas?<issue_comment>username_1: Instead of saving just the `max`, save the index as well.Instead of returning the longest length of `0`s from `findLongestConseqSubseq()`, you could return a `pair` where first element would represent the index and second element would represent the max length.
```
pair findLongestConseqSubseq(int arr[], int n)
{
pair max; //starting index, length
max.second = 1;
max.first=0;
pair current;
current.second = 1;
current.first=0;
int i;
for (i = 1; i < n; i++) {
if (arr[i] == arr[i-1])
{ /\* the run continues \*/
current.second++;
if (current.second > max.second)
{
max.second = current.second;
max.first = current.first;
}
}
else
{
current.second=1;
current.first=i;
}
}
return max;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use two variable `curr_index` & `max_index` to store the index of the current run and longest run and update them whenever you update the max value.
Also, you don't need to update the max every time you find a match just update it when the run completes.
```
int curr_index = 0, max_index = 0;
if (arr[i - 1] == arr[i]) {
/* the run continues */
current++;
}
else {
/* the run was broken */
if(current > max) {
max = current;
max_index = index;
curr_index = i;
}
current = 1;
}
```
Upvotes: 0 |
2018/03/19 | 356 | 1,343 | <issue_start>username_0: I have some misunderstanding issues with HL7 specially in PID segment.
if we have a patient has two different names, how can we build the PID-5 using the two names?
Example
the previous name
<NAME>
the current name
<NAME>
Any idea guys<issue_comment>username_1: PID-5 is a repeating field:
|name-1^components~name-2^components|
if a system doesn't support repeating components, it doesn't support multiple names
Upvotes: 1 <issue_comment>username_2: You may use the repeating character to separate the two names within PID.5, but ultimately it depends on what the system you're integrating with accepts. I found a standard HL7 spec from one EMR vendor that states if the HL7 version is greater than 2.2, PID.5.7 will populate with L, and if there are multiple other names PID.5.7 will populate with an M. The M may be a required flag to show that there is an additional name. For HL7 versions less than 2.2 PID.5.7 may not be used. You may need to have additional carats put in place until the 7th sub-component for it to work as well.
I tested this in our test system and the result is below. You can see the M was used multiple times because there were multiple other versions of this person's name. Hope this helps! Thanks!
|TEST^FAITH^^^^^M~test^hello^^^^^M~maiden^faith^^^^^M|
Upvotes: 0 |
2018/03/19 | 1,188 | 4,165 | <issue_start>username_0: i am trying to submit form after 10 seconds with form value. I am not able to include setTimeout with submit function.
```js
setTimeout(function() {
$('#FrmID').submit();
}, 10000);
$(document).ready(function() {
$("#submit").click(function() {
var grp_id = $("#grp_id").val();
var datastr = 'grp_id=' + grp_id;
$.ajax({
type: 'POST',
url: 'start_calculate.php',
data: datastr,
success: function() {
//$("#msg").html("Student Successfully Added");
//$("#msg").html("response");
}
});
});
});
```
```html
Done !
```<issue_comment>username_1: You can use following code.
```
$(document).ready(function() {
$("#submit").click(function() {
setTimeout(function() {
var grp_id = $("#grp_id").val();
var datastr = 'grp_id=' + grp_id;
$.ajax({
type: 'POST',
url: 'start_calculate.php',
data: datastr,
success: function() {
//$("#msg").html("Student Successfully Added");
//$("#msg").html("response");
}
});
}, 10000);
});
});
```
On click of submit just execute your code after delay.
Upvotes: 0 <issue_comment>username_2: The problem with your code is that you've not bound the submit handler to the form. Instead, you're binding it to the `click` event of the submit button.
You need to bind the handler code to the `submit` event of the form instead:
```js
setTimeout(function() {
$('#FrmID').submit();
}, 10000);
$(document).ready(function() {
$("#FrmID").submit(function() {
var grp_id = $("#grp_id").val();
var datastr = 'grp_id=' + grp_id;
$.ajax({
type: 'POST',
url: 'start_calculate.php',
data: datastr,
success: function() {
//$("#msg").html("Student Successfully Added");
//$("#msg").html("response");
}
});
});
});
```
```html
Done !
```
Upvotes: 1 <issue_comment>username_3: You can create a function for submit, then call it after click on `success`:
```js
$(document).ready(function() {
function submitForm() {
setTimeout(function() {
$('#FrmID').submit();
}, 10000);
}
$("#submit").click(function() {
var grp_id = $("#grp_id").val();
var datastr = 'grp_id=' + grp_id;
$.ajax({
type: 'POST',
url: 'start_calculate.php',
data: datastr,
success: function() {
//$("#msg").html("Student Successfully Added");
//$("#msg").html("response");
submitForm();
}
});
});
});
```
```html
Done !
```
**In Action:**
```js
$(document).ready(function() {
function submitForm() {
i = 1;
setInterval(function() {
console.log(i++);
}, 1000);
setTimeout(function() {
$('#FrmID').submit();
alert("Student Successfully Added");
}, 10000);
}
$("#submit").click(function(e) {
e.preventDefault();
submitForm();
});
});
```
```html
Done !
```
---
And if you want to submit form automatically without press any key to submit you can try this. You should move your code inside the `setTimeout` function:
```js
$(document).ready(function() {
setTimeout(function() {
$('#FrmID').submit(function() {
var grp_id = $("#grp_id").val();
var datastr = 'grp_id=' + grp_id;
$.ajax({
type: 'POST',
url: 'start_calculate.php',
data: datastr,
success: function() {
//$("#msg").html("Student Successfully Added");
//$("#msg").html("response");
}
});
});
}, 10000);
});
```
```html
Done !
```
Or you can try `delay()`
```
$(document).ready(function() {
$('#FrmID').delay(10000).submit(function() {
var grp_id = $("#grp_id").val();
var datastr = 'grp_id=' + grp_id;
$.ajax({
type: 'POST',
url: 'start_calculate.php',
data: datastr,
success: function() {
//$("#msg").html("Student Successfully Added");
//$("#msg").html("response");
}
});
});
});
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,062 | 3,217 | <issue_start>username_0: I have two arrays
```
Device = ["Washington DC","Newyork","San Diego","Florida"]
Device1 = ["Washington DC","Newyork","San Diego","Florida"]
```
when I do this to delete spaces from elements of one of the arrays
```
Device.each do |x|
x.gsub!(' ','')
puts x
end
```
spaces from elements of other array also been deleted. When I do puts for both arrays this is what I am getting
```
["WashingtonDC","Newyork","SanDiego","Florida"]
["WashingtonDC","Newyork","SanDiego","Florida"]
```
Please tell me what wrong I am doing or what should I do to delete spaces from one of the array's elements only<issue_comment>username_1: Most likely your arrays do not contain different strings but *references* to the same string object. When you modify one, then you modify all occurences.
```
string = "a reference"
array_1 = [string]
array_2 = [string]
array_1[0].gsub!(" ", "")
puts array_1 #> areference
puts array_2 #> areference
```
this is because you have a reference to the same string object in both arrays and you modify it inplace
```
puts array_1[0].object_id == array_2[0].object_id #> true
```
Try out following to see the difference
```
string_1 = "now it works"
array_1 = [string_1]
string_2 = "now it works"
array_2 =[string_2]
array_1[0].gsub!(" ", "")
puts array_1 #> nowitworks
puts array_2 #> now it works
```
You could also cretae a new array and leave the original array and the object it contains unchanged:
```
array_1 = ["hey there"]
array_1_no_spaces = array_1.map do |string|
string.gsub(" ", "") # just gsub, not gsub!
end
```
A note on your code: please follow the best practices and name your variables in lower snake-case-case:
```
device
list_of_something
...
```
CamelCase style is used for classes:
```
class Device
end
```
Upvotes: 1 <issue_comment>username_2: If you have assigned same `value` to the different `variables` like below:
```
device = ["Washington DC","Newyork","San Diego","Florida"]
device1 = ["Washington DC","Newyork","San Diego","Florida"]
```
then your below code **definitely** **works fine**:
```
device.each do |x|
x.gsub!(' ','')
puts x
end
```
after executing above code, your variables looks like:
```
> device
#=> ["WashingtonDC", "Newyork", "SanDiego", "Florida"]
> device1
#=> ["Washington DC", "Newyork", "San Diego", "Florida"]
```
**BUT**
if you assigned some value to `variable` through `variable` then each variables contains same object.
```
> array = ["Washington DC","Newyork","San Diego","Florida"]
#=> ["Washington DC", "Newyork", "San Diego", "Florida"]
> device = array
> device1 = array
> array.object_id
#=> 8031080
> device.object_id
#=> 8031080
> device1.object_id
#=> 8031080
```
so when you perform any action on any variable like `array`, `device` or `device1` it will reflects all variables.
You need to make duplicate copy of object. can assign like:
```
> array = ["Washington DC","Newyork","San Diego","Florida"]
> device = array.dup
> device1 = array.dup
> array.object_id
#=> 7077120
> device.object_id
#=> 7005100
> device1.object_id
#=> 6977660
```
I hope now this simple answer makes you clear and easy understanding.
Upvotes: 1 [selected_answer] |
2018/03/19 | 1,470 | 5,053 | <issue_start>username_0: Recently I am trying to solve a problem where I have to render a document tree menu (hierarchical) from a nested JSON coming from a request call.
**Say my JSON looks like this**
```
[{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, {
"title": "Cloths",
"path": "/root",
"children": [{
"title": "T shirt",
"path": "/root/Cloths",
"children": []
}, {
"title": "Shirt",
"path": "/root/Cloths",
"children": []
}]
}]
```
**I have to create the following DOM from the above JSON**
[](https://i.stack.imgur.com/RI2Ho.png)
SOLVED through jQuery:
======================
I have the function ready to convert the JSON to DOM: in normal jQuery I would do something like the following:
```
$(function(){
function get_tree(tree_data){
dom += '';
for(var i in tree\_data){
if(tree\_data[i].children.length > 0){
dom += '* ';
dom += '['+tree\_data[i].title+'](#)';
get\_tree(tree\_data[i].children);
dom += '* ';
}
else{
dom += '* '+tree\_data[i].title+'
'
}
}
dom+= '
'
}
var tree_data = JSON.parse($('pre').text());
var dom= '';
get\_tree(tree\_data);
dom+= '
'
$('div').append(dom);
})
```
In REACT.JS I tried this (ofcrse it doesn't works):
===================================================
```
export default class DocTree extends Component{
state = {treeData: [{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, ...
}]
}
render(){
const tree_data = this.state.treeData;
function get_tree(tree_data, dom){
for(var i in tree\_data)
if(tree\_data[i].children.length > 0)
* [{tree\_data[i].title}](#)
get\_tree(tree\_data[i].children);
* else
* {tree\_data[i].title}
var dom =
get\_tree(tree\_data);
return(
{dom}
);
}
}
```
I dont exactly how to achieve the same through React.js syntax
>
> Please help me with - **How do it in React.js** (am using React.js 16.2.0)
>
>
><issue_comment>username_1: You cannot use for loop within JSX, and secondly you can recursively render your tree after mapping over each object
```js
const data =[{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, {
"title": "Cloths",
"path": "/root",
"children": [{
"title": "T shirt",
"path": "/root/Cloths",
"children": []
}, {
"title": "Shirt",
"path": "/root/Cloths",
"children": []
}]
}]
const MyComponent = ({data}) => {
return (
{data.map((m, index) => {
return (* {m.title}
{m.children && }
);
})}
);
}
class App extends React.Component {
render() {
return
}
}
ReactDOM.render(, document.getElementById('root'));
```
```html
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You've misunderstood JSX.
Let consider it just like a server-side language (eg: PHP, ASP),
What you're doing is `embed HTML and JSX`, just like `embed HTML and PHP`.
**Why?**
JSX is js and a JSX element is an object under the hood.
You can run some hello world JSX on <https://babeljs.io/repl/> to see how JSX was transpile into ES5 (in case of ES5 browser), you'll understand JSX.
For more detail, you should read React fundamental, especially [JSX in depth](https://reactjs.org/docs/jsx-in-depth.html "JSX in depth")
---
Finally, this is the modification needed to work:
```
function get_tree(tree_data, dom){
var elems = [];
for(var i in tree_data)
if(tree_data[i].children.length > 0)
elems.push(- [{tree\_data[i].title}](#)
{get\_tree(tree\_data[i].children)}
)
else
elems.push(- {tree\_data[i].title}
)
return {elems}
}
```
Btw, your code is bad in practice because you're new in React, you should consider `@username_1` idea and follow his practice.
Upvotes: 2 |
2018/03/19 | 928 | 3,048 | <issue_start>username_0: I am a newbie to Selenium and HTML. I'm testing a website using Selenium WebDriver, but the driver can't find an element.
My code is:
```
browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)
data = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#search_result_former > div.re-content.search-mode-content > div.list-container > ul > li:nth-child(1) > div > div.item-footer > div > a:nth-child(1)')))
```
The HTML is:
```
[详览](javascript:;)
[法律状态](javascript:;)
[申请人](javascript:;)
[+ 分析库](javascript:;)
[收藏](javascript:;)
[翻译](javascript:;)
```
The result after I run my code:
```
*raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:*
```
Actually, I can see the element. I mean, the element has been loaded. I have tried `XPATH`, but it doesn't work.<issue_comment>username_1: You cannot use for loop within JSX, and secondly you can recursively render your tree after mapping over each object
```js
const data =[{
"title": "Food",
"path": "/root",
"children": [{
"title": "Veg",
"path": "/root/Food",
"children": [{
"title": "Carrot",
"path": "/root/Food/Veg",
"children": [{
"title": "Ooty carrot",
"path": "/root/Food/Veg/Brinjal",
"children": []
}]
}]
}]
}, {
"title": "Cloths",
"path": "/root",
"children": [{
"title": "T shirt",
"path": "/root/Cloths",
"children": []
}, {
"title": "Shirt",
"path": "/root/Cloths",
"children": []
}]
}]
const MyComponent = ({data}) => {
return (
{data.map((m, index) => {
return (* {m.title}
{m.children && }
);
})}
);
}
class App extends React.Component {
render() {
return
}
}
ReactDOM.render(, document.getElementById('root'));
```
```html
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: You've misunderstood JSX.
Let consider it just like a server-side language (eg: PHP, ASP),
What you're doing is `embed HTML and JSX`, just like `embed HTML and PHP`.
**Why?**
JSX is js and a JSX element is an object under the hood.
You can run some hello world JSX on <https://babeljs.io/repl/> to see how JSX was transpile into ES5 (in case of ES5 browser), you'll understand JSX.
For more detail, you should read React fundamental, especially [JSX in depth](https://reactjs.org/docs/jsx-in-depth.html "JSX in depth")
---
Finally, this is the modification needed to work:
```
function get_tree(tree_data, dom){
var elems = [];
for(var i in tree_data)
if(tree_data[i].children.length > 0)
elems.push(- [{tree\_data[i].title}](#)
{get\_tree(tree\_data[i].children)}
)
else
elems.push(- {tree\_data[i].title}
)
return {elems}
}
```
Btw, your code is bad in practice because you're new in React, you should consider `@username_1` idea and follow his practice.
Upvotes: 2 |
2018/03/19 | 465 | 1,634 | <issue_start>username_0: I am trying to retrieve the values of `wInstockArray` in a table view cell. Currently the the `wInstockArray` is empty I am inserting a string on a button click and appending in array. but when I retried the values in `cellForRowAtIndexath` method it gives error
>
> Index out of range
>
>
>
What I have defined is :
```
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wInstockArray.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let firstCell = firstTableView.dequeueReusableCell(withIdentifier: "firstCell")! as UITableViewCell
if wInstockArray.count == 0 {
print("no widgets in instock")
} else {
firstCell.textLabel?.text = wInstockArray[indexPath.row]
print("\(wInstockArray.count)") //prints 1
return firstCell
}
}
```
inside button click action
```
wInstockArray.append(item)
```<issue_comment>username_1: In `numberOfRowsInSection` method return wInstockArray array count
```
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wInstockArray.count
}
```
Inside the button click action, reload the tableView
```
wInstockArray.append(item)
tableView.reloadData()
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Inside button click method, please reload your table.
```
YOUR_TABLE.reloadData()
```
and update this method,
```
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wInstockArray.count
}
```
Upvotes: 1 |
2018/03/19 | 493 | 1,638 | <issue_start>username_0: I have this model
```
class Permission extends Model
{
public function details(): MorphToMany
{
return $this->morphedByMany('App\Models\Details', 'model', 'model_has_permissions', 'permission_id', 'model_id');
}
}
class Details extends Model
{
public function permission()
{
return $this->morphedByMany('App\Models\Permission','model','model_has_permissions','model_id','permission_id');
}
}
```
I'm execute this query
```
Details::with('permission')->find(55);
```
and got empty array
why happen this?and what is the correct query?<issue_comment>username_1: You have a typo in your `permission()` method
change this
```
return $this->morphedByMany('App\Models\Permission','model','.model_has_permissions','model_id','permission_id');
```
to this
```
return $this->morphedByMany('App\Models\Permission','model','model_has_permissions','model_id','permission_id');
```
Upvotes: 1 <issue_comment>username_2: I don't think it's possible to chain `find` after `with`. Here are your options.
1. Lazy Loading.
```
Details::find(55)->load('permissions');
```
2. Eager loading with `where` clause
```
Details::with('permissions')->where('id', 55)->get();
```
**UPDATE**
Shouldn't this be `morphToMany`?
```
public function details(): MorphToMany
{
return $this->morphedByMany('App\Models\Details', 'model', 'model_has_permissions', 'permission_id', 'model_id');
}
```
Or this?
```
public function permission()
{
return $this->morphedByMany('App\Models\Permission','model','model_has_permissions','model_id','permission_id');
}
```
Upvotes: 0 |
2018/03/19 | 748 | 1,930 | <issue_start>username_0: I need a macro that will apply the below-mentioned formula in column J if the value of a cell in column C is "Hits\_US" and the value of a cell in column D is "harry". Below is the formula
```
=((Column G*32)+(Column H*28)+300)/60
```
Please note that there will be other values in column J. So, only if the condition is met, the formula has to be applied.
I tried to do this in parts. I first tried to multiply the value in column G by 32. But it did not work.
```
For i = 1 To 10
If Sheets(1).Range("C" & i).Value = "Hits_US" And Range("D" & i).Value <> "harry" Then
Cells(i, 10) = Cells(i, 7) * 32
End If
Next i
```<issue_comment>username_1: You should be able to avoid a loop
```
Sheets(1).Range("J1:J10").Formula = "=IF(AND(C1=""Hits_US"",D1=""Harry""),(G1*32+H1*28+300)/60,"""")"
```
For all rows in J, based on how many entries are in column C
```
With Sheets(1)
.Range("J1:J" & .Range("C" & Rows.Count).End(xlUp).Row).Formula = "=IF(AND(C1=""Hits_US"",D1<>""Harry""),(G1*32+H1*28+300)/60,"""")"
End With
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want to leave a formula in cells then I'd go with R1C1 notation:
```
Sheets(1).Range("J1:J10").FormulaR1C1 = "=IF(AND(RC3=""Hits_US"",RC4=""harry""),(RC7*32+RC8*28+300)/60,"""")"
```
While if you want to leave only the formula results then you have to possibilities:
1. have formulas do the math and then leave only values
```
With Sheets(1).Range("J1:J10")
.FormulaR1C1 = "=IF(AND(RC3=""Hits_US"",RC4=""harry""),(RC7*32+RC8*28+300)/60,"""")"
.Value = .Value
End With
```
2. have VBA do the math and write its results directly
```
With Sheets(1)
For i = 1 To 10
If .Range("C" & i).Value = "Hits_US" And .Range("D" & i).Value = "harry" Then
.Cells(i, 10) = (.Cells(i, 7) * 32 + .Cells(i, 8) * 28 + 300) / 60
End If
Next
End With
```
Upvotes: 0 |
2018/03/19 | 752 | 2,933 | <issue_start>username_0: ```
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ `setValue:forUndefinedKey:`]: this class is not \*\*key value coding-compliant\*\* for the key signinbutton.'
```
I'm getting an error after building and launching my iOS app. I see that other people have got this error before, but after trying all the solutions, none of them have worked for me. It's not a naming issue, or a bad connection, as far as I can tell. I've deleted the app, restarted, etc. I've tried with different outlets. This is how it goes: my app works perfectly, then I add any sort of `@IBOutlet` to my `ViewController`, all looks good. Build and run, and the app loads to a blank screen and I get that error in my console.
I've been trying every solution on stackoverflow for the past 6 hours. None of them work.
This is my `ViewController`.
```
import UIKit
class UIView: UIViewController {
@IBOutlet weak var signInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
}
```
My `AppDelegate` file is just as it comes default.
```
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
```
and so on...
Why isn't this working?
**EDIT: Changing the class to `class HomeViewController: UIViewController` does nothing.**
Note: This is ***not*** a duplicate question. No solution posted on Stack Overflow has worked so far for me.<issue_comment>username_1: Kindly create the outlet of signinbutton in your view controller[To Learn more about outlets and Actions](https://www.youtube.com/watch?v=z-ZaRC8L6uE)
Upvotes: 0 <issue_comment>username_2: Change the name of your controller to some name.
```
class UIView: UIViewController // This is wrong
```
`class HomeViewController: UIViewController` : This is right
Also update the class of controller in `storyboard`: Select controller in storyboard. Change `file's owner`.
Upvotes: 3 [selected_answer]<issue_comment>username_3: Simple, if your class is a **UIView**, either subclass **UIView** or your custom UIView subclass.
If your class is a **UIViewController**, either subclass **UIViewController** or your custom UIViewController subclass.
```
UIView: UIViewController doesnt make sense to the compiler.
```
I would like to mention some background info:
x : y means,
x is a subclass of y, since you mention it is your **ViewController** file, so in order for your code to compile, you can simply change the name of your class from UIView to a custom name
Also UIViewController is another Class in UIKit, just like UIView or UITableView, but not the controller of the child class.
Meanning when x : y, y is not the controller of x, but indeed x is the controller, and x is subclassed from Y
Upvotes: 0 <issue_comment>username_4: Don't use **UIView** as the class name, because there's a **system** of UIView classes.
Upvotes: 0 |
2018/03/19 | 494 | 1,588 | <issue_start>username_0: Is it possible to train the current deeplab model in TensorFlow to reasonable accuracy using 4 GPUs with 11GB? I seem to be able to fit 2 batches per GPU, so am running a total batch size of 8 across 4 clones.
Following the [instructions included with the model](https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/cityscapes.md), I get a mean IoU of < 30% after 90,000 iterations.
```
PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim python deeplab/train.py \
--logtostderr --training_number_of_steps=90000 \
--train_split="train" --model_variant="xception_65" \
--atrous_rates=6 --atrous_rates=12 --atrous_rates=18 \
--output_stride=16 --decoder_output_stride=4 --train_crop_size=769 \
--train_crop_size=769 --train_batch_size=8 --num_clones=4 \
--dataset="cityscapes" \
--tf_initial_checkpoint=deeplab/models/xception/model.ckpt \
--train_logdir=$LOGDIR \
--dataset_dir=deeplab/datasets/cityscapes/tfrecord
```
I have tried with batch norm both enabled and disabled without much difference in outcome.
Thanks!<issue_comment>username_1: if you check this link <https://github.com/tensorflow/models/blob/master/research/deeplab/g3doc/model_zoo.md>
It has links to pretrained models for MobileNet v2 and DeepLab trained on Cityscapes. You can modify the existing shell scripts present here to train on cityscapes.
Upvotes: 0 <issue_comment>username_2: It seems I needed a much larger step length than the default. 1e-2 gives results closer to the published results, with batch size 15 and a smaller crop window size.
Upvotes: 2 [selected_answer] |
2018/03/19 | 376 | 1,466 | <issue_start>username_0: I was trying to use acorn.js along with yeoman to add code to existing js files .I have tried to work with esprima and acorn to do this job but I cannot find any documentation about adding node to the AST.<issue_comment>username_1: I believe this is what you are looking for <https://github.com/SBoudrias/ast-query>
Upvotes: -1 <issue_comment>username_2: What I found useful was using estraverse with acorn. You can convert your JS files into AST using acorn and then easily add or replace nodes with estraverse according to the ECMAscript.
What you need to look for is the estraverse.replace(..) API.
Upvotes: -1 <issue_comment>username_3: (three years late but here's the answer)
You need to first understand that one does not simply add a new node to the AST tree anywhere. Since you indicated that you want to add code to js files, you'll need to add it to a node with a `body`. How you manipulate the `body` is the same as how you do with arrays (using acorn as an example). The following is an example of how you add a node to a `FunctionDeclaration` node.
```js
// astNode is a FunctionDeclaration node with a body that contains more nodes
// newNode is the code you want to insert
astNode.body.push(newNode); // add node at the end of the function block
astNode.body.unshift(newNode); // add node at the beginning of the function block
astNode.body.splice(index, 0, newNode); // add node at index
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 734 | 2,873 | <issue_start>username_0: What is the difference between writing Spring boot REST API backed SPA
1. inside one project, javascript served from Spring's app server
2. two projects, Spring backend server app and javascript frontend in separate node server
Are there any benefits of the first over the other other. For me separate project are more clean. I'm pretty new to javascript so I'm affraid to clutter the java project with all the folder, files and javascript build processes. Also there are more i.e. separate vuejs templates than vuejs-spring-boot templates.
Is there any way, to somehow connect both solutions, by generating one js file for the SPA and serv it from Spring.
Regarding authentication I can utilize Spring MVC in first option, the second one is asking for some token authentication.<issue_comment>username_1: >
> You can use both ways,but separating the frontend from backend will make your application **reusable**.
>
>
>
*I mean if you want your vue.js project to connect with another api for example with Laravel,then you have to make only the backend and let your frontend as it is.*
*In the other hand you can keep your api backend as it is and for frontend you can use angular or react.So then you have to make only the frontend and let your api as it is.*
>
> Also in my opinion it is great to use separate project when you working on group.Because it is more clear and gives you flexibility to manage the frontend and backend easily.
>
>
>
*Actually i am working on project and i am making the frontend and someone else is making the backend.*
>
> I always prefer to separate backend from frontend so in my opinion
> that is the best way.But ofcourse you can use both ways.
>
>
>
Upvotes: 1 <issue_comment>username_2: >
> Is there any way, to somehow connect both solutions, by generating one js file for the SPA and serv it from Spring.
>
>
>
You can copy the `dist` content into `src/main/resources` in SpringBoot:
```
npm run build
```
And that HTML/JS will be served from Spring.
However, this process is take time and not fits with daily development.
During development, you can let dev server proxy all API request to the actual backend:
`
```
// config/index.js
module.exports = {
// ...
dev: {
proxyTable: {
// proxy all requests starting with /api to jsonplaceholder
'/api': {
target: 'http://jsonplaceholder.typicode.com:8000', // <-- Spring app running here
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
```
`
Refer: <https://vuejs-templates.github.io/webpack/proxy.html>
The above example will proxy the request `/api/posts/1` to `http://jsonplaceholder.typicode.com/posts/1`.
So, in client side, you can develop normally, and run in dev mode
`npm run dev`
Hope this help!
Upvotes: 3 [selected_answer] |
2018/03/19 | 957 | 3,465 | <issue_start>username_0: Since std::vector::push\_back(obj) creates a copy of the object, would it be more efficient to create it within the push\_back() call than beforehand?
```
struct foo {
int val;
std::string str;
foo(int _val, std::string _str) :
val(_val), str(_str) {}
};
int main() {
std::vector list;
std::string str("hi");
int val = 2;
list.push\_back(foo(val,str));
return 0;
}
// or
int main() {
std::vector list;
std::string str("hi");
int val = 2;
foo f(val,str);
list.push\_back(f);
return 0;
}
```<issue_comment>username_1: ```
list.push_back(foo(val,str));
```
asks for a `foo` object to be constructed, and then passed into the vector. So both approaches are similar in that regard.
However—with this approach a c++11 compiler will treat the `foo` object as a "temporary" value (rvalue) and will use the `void vector::push_back(T&&)` function instead of the `void vector::push_back(const T&)` one, and that's indeed to be faster in most situations. You could also get this behavior with a previously declared object with:
```
foo f(val,str);
list.push_back(std::move(f));
```
Also, note that (in c++11) you can do directly:
```
list.emplace_back(val, str);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You ‘d better use
```
emplace_back(foo(val,str))
```
if you are about creating and pushing new element to your vector. So you perform an in-place construction.
If you’ve already created your object and you are sure you will never use it alone for another instruction, then you can do
```
push_back(std::move(f))
```
In that case your f object is dangled and his content is owned by your vector.
Upvotes: 0 <issue_comment>username_3: It's actually somewhat involved. For starters, we should note that [`std::vector::push_back`](http://en.cppreference.com/w/cpp/container/vector/push_back) is overloaded on the two reference types:
```
void push_back( const T& value );
void push_back( T&& value );
```
The first overload is invoked when we pass an lvalue to `push_back`, because only an lvalue reference type can bind to an lvalue, like `f` in your second version. And in the same fashion, only an rvalue reference can bind to an rvalue like in your first version.
Does it make a difference? Only if your type benefits from move semantics. You didn't provide any copy or move operation, so the compiler is going to implicitly define them for you. And they are going to copy/move each member respectively. Because `std::string` (of which you have a member) actually does benefit from being moved if the string is very long, you might see better performance if you choose not to create a named object and instead pass an rvalue.
But if your type doesn't benefit from move semantics, you'll see no difference whatsoever. So on the whole, it's safe to say that you lose nothing, and can gain plenty by "creating the object at the call".
Having said all that, we mustn't forget that a vector supports another insertion method. You can forward the arguments for `foo`'s constructor directly into the vector via a call to [`std::vector::emplace_back`](http://en.cppreference.com/w/cpp/container/vector/emplace_back). That one will avoid any intermediate `foo` objects, even the temporary in the call to `push_back`, and will create the target `foo` directly at the storage the vector intends to provide for it. So `emplace_back` may often be the best choice.
Upvotes: 2 |
2018/03/19 | 1,219 | 3,882 | <issue_start>username_0: I running Kubernetes cluster on premises, initialized using KubeAdm. I configured [flannel](https://kubernetes.io/docs/concepts/cluster-administration/networking/#flannel) networking plugin.
When I exposing service as a NodePort, I'm not able to receive external IP. What do I miss?
[](https://i.stack.imgur.com/TRjmN.png)
My deployment yaml looks as the following:
```
apiVersion: v1
kind: Service
metadata:
name: testapp
labels:
run: testapp
spec:
type: NodePort
ports:
- port: 8080
targetPort: 80
protocol: TCP
name: http
- port: 443
protocol: TCP
name: https
selector:
run: testapp
---------
apiVersion: apps/v1
kind: Deployment
metadata:
name: testapp
spec:
selector:
matchLabels:
run: testapp
replicas: 2
template:
metadata:
name: testapp
labels:
run: testapp
spec:
containers:
- image: [omitted]
name: testapp
ports:
- containerPort: 80
livenessProbe:
httpGet:
path: /api/health
port: 80
```
**Environment details:**
Kubernetes version:
```
Client Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.3", GitCommit:"<PASSWORD>", GitTreeState:"clean", BuildDate:"2018-02-07T12:22:21Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"9", GitVersion:"v1.9.3", GitCommit:"<PASSWORD>d0864b52323b", GitTreeState:"clean", BuildDate:"2018-02-07T11:55:20Z", GoVersion:"go1.9.2", Compiler:"gc", Platform:"linux/amd64"}
```
Running Ubuntu Server 16.04 on vSphere VM (on-prem).<issue_comment>username_1: You will not see an "External-IP" value here if you using a node port.
From [documentation](https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport):
>
> If you set the type field to "NodePort", the Kubernetes master will allocate a port from a flag-configured range (default: 30000-32767), and **each Node will proxy that port** (the same port number on every Node) into your Service. That port will be reported in your Service’s spec.ports[\*].nodePort field.
>
>
>
So, you don't have a one IP which can be shown there. You can connect to any of your nodes to defined NodePort.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You would not get an external IP when exposing service as a nodeport. Exposing Service on a Nodeport means that your service would be available on externally via the NodeIP of any node in the cluster at a random port between 30000-32767(default behaviour) .
In your case , the port on which your service is exposed is port 31727.
Each of the nodes in the cluster proxy that port (the same port number on every Node) into the pod where your service is launched.
Easiest way to see this using
```
kubectl describe service
```
Check for detail of the Nodeport in the result above.
Later get any the node Ip of any of the nodes in the cluster using
```
kubectl get nodes -o wide
```
You can now access your service externally using `:`
Additionally, if you want a fixed Node port, you can specify that in the yaml.
PS: Just make sure you add a security rule on your nodes to allow traffic on the particular port.
Upvotes: 4 <issue_comment>username_2: In NodePort you won't get an external IP ,
Try to use type:LoadBalancer instead of NodePort to get external IP that's what you actually want ,
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
selector:
```
app.kubernetes.io/name: MyApp
```
ports:
```
- protocol: TCP
port: 80
targetPort: 9376
```
clusterIP: 10.0.171.239
type: LoadBalancer
status:
loadBalancer:
```
ingress:
- ip: 192.0.2.127
```
Upvotes: 0 |
2018/03/19 | 1,663 | 4,348 | <issue_start>username_0: I want to change value in pandas DataFrame by condition that data[Bare Nuclei'] != '?'
```
import pandas as pd
import numpy as np
column_names = ['Sample code number', 'Clump Thickness',
'Uniformity of Cell Size', 'Uniformity of Cell Shape',
'Marginal Adhesion', 'Single Epithelial Cell Size',
'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli',
'Mitoses', 'Class']
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data', names = column_names )
mean = 0
n = 0
for index,row in data.iterrows():
if row['Bare Nuclei'] != '?':
n += 1
mean += int(row['Bare Nuclei'])
mean = mean / n
temp = data
index = temp['Bare Nuclei'] == '?'
temp[index,'Bare Nuclei'] = mean
```
**this is jupyter notebook give me error:**
[](https://i.stack.imgur.com/EeN4v.png)
I want to know how to change value in dataframe and why my way is wrong? Could you help me, I look forward your help!!<issue_comment>username_1: For last line add [`DataFrame.loc`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html), because need change column of `DataFrame`:
```
temp.loc[index,'Bare Nuclei'] = mean
```
---
But in pandas is the best avoid loops, because slow. So better solution is [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html) `?` to `NaN`s and then [`fillna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html) by `mean`s:
```
data['Bare Nuclei'] = data['Bare Nuclei'].replace('?', np.nan).astype(float)
#more general
#data['Bare Nuclei'] = pd.to_numeric(data['Bare Nuclei'], errors='coerce')
data['Bare Nuclei'] = data['Bare Nuclei'].fillna(data['Bare Nuclei'].mean())
```
Alternative solution:
```
mask = data['Bare Nuclei'] == '?'
data['Bare Nuclei'] = data['Bare Nuclei'].mask(mask).astype(float)
data['Bare Nuclei'] = data['Bare Nuclei'].fillna(data['Bare Nuclei'].mean())
```
Verify solution:
```
column_names = ['Sample code number', 'Clump Thickness',
'Uniformity of Cell Size', 'Uniformity of Cell Shape',
'Marginal Adhesion', 'Single Epithelial Cell Size',
'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli',
'Mitoses', 'Class']
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data', names = column_names )
#print (data.head())
```
---
```
#get index values by condition
L = data.index[data['Bare Nuclei'] == '?'].tolist()
print (L)
[23, 40, 139, 145, 158, 164, 235, 249, 275, 292, 294, 297, 315, 321, 411, 617]
#get mean of values converted to numeric
print (data['Bare Nuclei'].replace('?', np.nan).astype(float).mean())
3.5446559297218156
print (data.loc[L, 'Bare Nuclei'])
23 ?
40 ?
139 ?
145 ?
158 ?
164 ?
235 ?
249 ?
275 ?
292 ?
294 ?
297 ?
315 ?
321 ?
411 ?
617 ?
Name: <NAME>, dtype: object
#convert to numeric - replace `?` to NaN and cast to float
data['Bare Nuclei'] = data['Bare Nuclei'].replace('?', np.nan).astype(float)
#more general
#data['Bare Nuclei'] = pd.to_numeric(data['Bare Nuclei'], errors='coerce')
#replace NaNs by means
data['Bare Nuclei'] = data['Bare Nuclei'].fillna(data['Bare Nuclei'].mean())
```
---
```
#verify replacing
print (data.loc[L, 'Bare Nuclei'])
23 3.544656
40 3.544656
139 3.544656
145 3.544656
158 3.544656
164 3.544656
235 3.544656
249 3.544656
275 3.544656
292 3.544656
294 3.544656
297 3.544656
315 3.544656
321 3.544656
411 3.544656
617 3.544656
Name: <NAME>, dtype: float64
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: temp[index,'Bare Nuclei'] is a mix of boolean indexing and column selection using label which will not work.
Instead, change
```
index = temp['Bare Nuclei'] == '?'
temp[index,'Bare Nuclei'] = mean
```
to
```
s=temp['Bare Nuclei']
temp['Bare Nuclei']=s.where(s!='?',mean)
```
where(s!='?',mean) actually means change the value of the element to 'mean' where the condition s!='?' does not meet (kind of confusion at first glance)
Upvotes: 1 |
2018/03/19 | 1,223 | 4,488 | <issue_start>username_0: Facing an error in a PHP page which was working fine before i made some minute changes.
The error cause is : $type = (int)$\_POST['type'];
Error is : syntax error, unexpected '' (T\_ENCAPSED\_AND\_WHITESPACE), expecting identifier (T\_STRING) or variable (T\_VARIABLE) or number(T\_NUM\_STRING)
**FUll code is as follows.**
```
php
require_once '../library/config.php';
require_once '../library/functions.php';
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'search' :
search();
break;
default :
// if action is not defined or unknown
// move to main user page
header('Location: index.php');
}
/*
search() function used to search hadrware, software with user given criteria.
*/`
function search()
{
$type = $_POST['type'];
$name = $_POST['name'];
$hsql = "SELECT a.hostname, a.username, a.cpumodel, a.servicetag, a.monitormodel, a.phonext
FROM assets a WHERE a.username LIKE '%$name%' ";
$ssql = "SELECT a.hostname, a.username, a.cpumodel, a.servicetag, a.monitormodel, a.phonext
FROM assets a WHERE a.username LIKE '%$name%' ";
$data = array();
if($type == 1){
$result = dbQuery($hsql);
if(dbNumRows($result) == 0) {
header('Location: ../view.php?v=search&error=' . urlencode('No Hardware Found. Please try Again.'));
}else {
while($row = dbFetchAssoc($result)){
extract($row);
$data[] = array('hname' = $hname, 'uname' => $uname, 'cmodel' => $cmodel, 'stag' => $stag, 'mmodel' => $mmodel, 'pext' => $pext);
}
$_SESSION [result_data] = $data;
header('Location: ../search');
}//else
}
else {
$result = dbQuery($ssql);
if(dbNumRows($result) == 0) {
header('Location: ../view.php?v=search&error=' . urlencode('No Software Found. Please try Again.'));
}else {
while($row = dbFetchAssoc($result)){
extract($row);
$data[] = array('hname' => $hname,
'uname' => $uname,
'cmodel' => $cmodel,
'stag' => $stag,
'mmodel' => $mmodel
'pext' => $pext);
}
$_SESSION[result_data] = $data;
header('Location: ../search');
}
}endif;
}
?>
```<issue_comment>username_1: Your comment is not closed.
Put closing `*/` just before last curly bracket `}`
Or
If you do not want to have all the code commented then remove opening `/*` just after the
`function search() {`
Upvotes: 0 <issue_comment>username_1: The problem is with curly brackets in your variable name:
```
$type = (int)${_POST['type']}
```
Correct way is without curly brackets:
```
$type = (int)$_POST['type'];
```
Upvotes: 0 <issue_comment>username_2: The problem is after your comment. You open a backtick (most likely unintentionally) but dont close it. Just remove it and it should work again.
You even can see it in the highlighting.
```
/*
search() function used to search hadrware, software with user given criteria.
*/`
/* ^ there it is */
```
---
Also I´d like to point out, that your code is probably sql injection vulnerable. This for example:
```
$type = $_POST['type'];
$name = $_POST['name'];
$hsql = "SELECT a.hostname, a.username, a.cpumodel, a.servicetag, a.monitormodel, a.phonext
FROM assets a WHERE a.username LIKE '%$name%' ";
$ssql = "SELECT a.hostname, a.username, a.cpumodel, a.servicetag, a.monitormodel, a.phonext
FROM assets a WHERE a.username LIKE '%$name%' ";
```
Upvotes: 1 <issue_comment>username_3: Your comment above the function has a backtick character immediately after the closing comment marker. This is the cause of your issue.
If you remove this backtick, then you will resolve the problem. It still won't work as there is one other compile error in the code you've given, which is due to a missing comma at the end of line 64. If you fix that as well then program will run, you'll find that there are additional logic errors as well as security issues (but I'll leave those for you to find for yourself).
Upvotes: 1 [selected_answer] |
2018/03/19 | 859 | 2,827 | <issue_start>username_0: I am using Adonis 4.1.0 and `Adonis-websocket` is only been available for `v3`. Can anyone tell me workaround for using `socket.io` with Adonis 4.1.0?<issue_comment>username_1: apparently they have been working on this not long ago, it was based on `socket.io` but because of some issues like memory leaks and others, they decided to use `websockets` directly instead, check these discussions :
<https://github.com/adonisjs/discussion/issues/51>
have you tried using `socket.io` without relying on `Adonis` ? ,
something like :
```
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
```
But you should be able to do this with `Adonis` by now according to : <https://github.com/adonisjs/adonis-websocket-protocol>
Example :
```
const filereader = require('simple-filereader')
const msgpack = require('msgpack-lite')
const packets = require('@adonisjs/websocket-packets')
const client = new WebSocket('ws://localhost:3000/adonis-ws')
client.onopen = function () {
// TCP connection created
}
client.onerror = function () {
// TCP connection error
}
client.onmessage = function (message) {
filereader(message, function (error, payload) {
const packet = msgpack.decode(payload)
handlePacket(packet)
})
}
function handlePacket (packet) {
if (packets.isOpenPacket(packet)) {
console.log('Server ack connection. Make channel subscriptions now')
}
if (packets.isJoinAck(packet)) {
console.log('subscription created for %s', packet.d.topic)
}
}
```
check this for broadcast examples using `WS` : <https://github.com/websockets/ws#broadcast-example>
Upvotes: 2 <issue_comment>username_2: Create start/socket.js file and paste following code inside it.
```
const Server = use('Server')
const io = use('socket.io')(Server.getInstance())
io.on('connection', function (socket) {
console.log(socket.id)
})
```
From <NAME> in this forum:<https://forum.adonisjs.com/t/integrating-socket-io-with-adonis-4/519>
Upvotes: 1 <issue_comment>username_3: create a standalone socket io configuration file in start/socket.js
```
const io = require('socket.io')();
io.listen(3000);
io.on('connection', function (socket) {
console.log(socket.id)
})
```
to start your socket io server you can configure your server.js as below
```
new Ignitor(require('@adonisjs/fold'))
.appRoot(__dirname)
.preLoad('start/socket') //path of socket.js
.fireHttpServer()
.catch(console.error)
```
now when you start your server then it will start along with socket io
Upvotes: 0 |
2018/03/19 | 805 | 2,780 | <issue_start>username_0: Hi my knowledge on javascript and I have been getting help on here which was quite helpful (thanks everybody!) but it is still very limited and basic. Basically below is I will prompt a pop-up that displays the answer to the value. The thing is from the coding I found below if I had to insert an array lets say `12,8,3,2` the output would be `8`. For some reason the code below is only taking into consideration 1 digits. Is there a way to edit this code so that the answer to the input above would be `12`.
Thanks once again!
I have done my fair share of research:
**Code:**
```
test
function evaluate() {
const input = prompt("Please enter the array of integers in the form: 1,2,3,1")
.split(',')
.map(nums => nums.trim());
function max(numArray)
{
var nums = numArray.slice();
if (nums.length == 1) { return nums[0]; }
if (nums[0] < nums[1]) { nums.splice(0,1); }
else { nums.splice(1,1); }
return max(nums);
}
if (input == "" || input == null) {
document.writeln("Sorry, there is nothing that can be calculated.");
} else {
document.writeln("The largest number is: ");
document.writeln(max(input) + " with a starting input string of: " + input);
}
}
evaluate();
```<issue_comment>username_1: You can use `Math.max(...array)` function
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max>
```
const returnMax = (str='') => { // pass string
const numbersArr = str.trim().split(',').map(num => parseInt(num.trim()));
return Math.max(...numbersArr); // rest-spread operator from es6 syntax
}
```
More about rest operator: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters>
Upvotes: 2 <issue_comment>username_2: The problem is that you are comparing string not integers. Therefore it only compares the first character of the 'digits' which in your case 12 vs 8 will result to 8 being greater than 1 (the first character of 12). Before doing the comparison make sure to change the string to an integer. All you need to change is one line:
`if (nums[0] < nums[1])` to
`if (parseInt(nums[0]) < parseInt(nums[1]))`
JSFiddle: <https://jsfiddle.net/omartanti/ahbtg2z2/1/>
**Please Note: parseInt returns NaN if the first character cannot be converted to a number**
Upvotes: 2 [selected_answer]<issue_comment>username_3: You can use `Math.max` and spread operator `(...)` to get the max value.In the snippet `+num.trim()` will convert string to number
```js
function evaluate() {
const input = prompt("Please enter the array of integers in the form: 1,2,3,1")
.split(',')
.map(nums => +nums.trim());
console.log(input)
var getLargest = Math.max(...input);
console.log(getLargest)
}
evaluate();
```
Upvotes: 0 |
2018/03/19 | 756 | 2,854 | <issue_start>username_0: In my component, there are 3-4 methods along with `constructor(){...}` and `ngOnInit(){...}`. In class, I've declared one variable `values:any=[]` which is initialized with some json data in one method named as `getData()` in the same class.
```
getData(){
this.service.getData().subscribe(res=>{
this.values = res.json();
})
}
```
now I called this method in `ngOnInit(){...}`. From this I can say that `values` is initialized with some data but if I call `values` in other method for the purpose of displaying data. It says empty array.
```
export class AccountComponent implements OnInit {
values:any=[];
constructor(private service: AccountService) {
}
getData(){
this.service.getData().subscribe(res=>{
this.values = res.json();
})
}
callData(){
console.log(this.values)
}
ngOnInit() {
this.getData();
this.callData();
}
```
In the `callData()` , I have `console.log()` but this says that `values` is empty. Why???<issue_comment>username_1: yes, you cannot get data there as you call to service i.e. http call to get data is not completed yet.
if you want to get data in callData method then make use of `async/await` like this
```
async getData(){
const res = await this.service.getData().toPromise();
this.values = res.json();
}
async ngOnInit() {
await this.getData();
this.callData();
}
callData(){
console.log(this.values)
}
```
Basically you have to wait for serverside call to finish, right now you are not waiting for serverside call to finish and thats the reason why you are not getting data in your `this.calllData()` method.
**or**
if you don't want to go for async/await then you can do this
```
getData(){
this.service.getData().subscribe(res=>{
this.values = res.json();
this.callData();
})
}
callData(){
console.log(this.values)
}
ngOnInit() {
this.getData();
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Adding one more solution which I used to handle similar case:- using 'setTimeout' function.
```
getData(){
this.service.getData().subscribe(res=>{
this.values = res.json();
})
}
callData(){
console.log(this.values)
}
ngOnInit() {
this.getData();
setTimeout(() => {
this.callData();
}, 10);
}
```
This way you can add a minimal wait time to code block which depends on values returned in response. I used it with value 1 millisecond and it had never failed for me.
Also on json traversal point, you could return the json directly from the service method. In order to traverse that object, instead of using 'foreach' you could try below code:
```
for(let key in json){
let value = json[key];
//rest of the code
}
```
Hope it helps!
Upvotes: 0 |
2018/03/19 | 632 | 2,178 | <issue_start>username_0: I have a form, which has two fields: "product\_name" and "product\_q" and in my form i have an option to increase the number of fields in `product_name` and `product_q`
```
demo1
demo2
1
2
```
and an action page like
```
public function order(){
$Product_q = $this->input->post('quantity');
$sponserid = $this->session->userdata('number');
$pname['product_name'] = $this->input->post('product_name');
foreach($Product_q as $key => $value){
$data['Product_q'] = $value;
$data['Product_Name'] = $pname['product_name'][$key];
$this->mymodel->insert_items($data);
}
```
and my model
```
function insert_items($data){
$this->db->insert("lucky_order", $data);
return;
}
```
Please help to insert data database my form look like this:
**FORM with one field**
[](https://i.stack.imgur.com/CaBOh.png)
**Form with two field**
[](https://i.stack.imgur.com/SZtL8.png)<issue_comment>username_1: We cannot insert array directly into database so before inserting it to database we need to encode array into json. You can do it by following `php json_encode($data); ?`
and then later where you want fetch this data then you can simply decode that data back to array by using following method `php json_decode($data); ?`
Upvotes: 0 <issue_comment>username_2: you can try this :
```
demo1
demo2
1
2
You have to increment /decrement the product_count value on addition
or removal or product
```
for controller :
```
loop your function in model for inserting into database
```
for times of product\_count
and the values for each using $key
something like this :
```
for ($i=0; $i<$_POST['product_count']; $i++){
```
call the function of insert by passing the each value using above $i variable.
like
```
$_POST['product_name'][$i];
this will get you your first product name similarly for all
and you can call the model function and pass the above values each
time with incremented value of $i
```
Upvotes: -1 [selected_answer] |
2018/03/19 | 222 | 729 | <issue_start>username_0: I was designing a website. I am having some issue on the Faculties Page. The Issue is as Follows.
[![enter image description here][1]][1]
I want the Div a to reach position b. without changing the responsivity.
(Bootstrap if Possible)
```html
```<issue_comment>username_1: Not possible with your current markup which is like below...
```css
.item {
margin-bottom: 10px;
border: 5px solid #fff;
}
```
```html
```
You will need to wrap the left and right divs in different div like below...
```css
.item {
margin-bottom: 10px;
}
```
```html
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can try multi classes of row and cols as given below..
```html
```
Upvotes: 0 |
2018/03/19 | 249 | 883 | <issue_start>username_0: I'm trying to use Cloud 9 but keep getting the following message during the deployment of the IDE:
```
"Your web browser does not have third-party cookies enabled"
```
I'm using Safari 11.0.3 and in the preferences-privacy the block all cookies box is unchecked. I can use Chrome but would prefer to use Safari.<issue_comment>username_1: I had to uncheck "Prevent cross-site tracking" to get it to work. Maybe it has something to do with authenticity and AWS passing off to cloud9. I don't remember this being a problem in the past, and I've never had problems logging on to cloud9 directly.
Safari -- Version 11.0.3 (13604.5.100.6)
Upvotes: 4 [selected_answer]<issue_comment>username_2: AWS Cloud9 has been updated so that you no longer need to enable third-party cookies to open the IDE.
<https://forums.aws.amazon.com/ann.jspa?annID=7207>
Upvotes: 1 |
2018/03/19 | 410 | 1,384 | <issue_start>username_0: I am trying to run coded UI test in my local machine but everytime I run the test case I get the below message in my output window.
And it is not running any test case.
```
------ Run test started ------
UTA001: TestClass attribute defined on non-public class
Raet.Testing.TestScripts.FlexBenefits.Initialization
There is no test with specified Id {ac3b157c-2594-5317-f826-52e0927cee39}.
```
Also there is no error message in error list window.
I am using visual studio professional 2015.
I have also installed Visual studio professional 2017 in my machine.
In test assembly, I am using
Microsoft.VisualStudio.QualityTools.CodedUITestFramework version 14.0
OS - Windows 10.
Test Solution was created using visual studio enterprise 2015
Let me know if any more details are required.
Can anyone please help?<issue_comment>username_1: I had to uncheck "Prevent cross-site tracking" to get it to work. Maybe it has something to do with authenticity and AWS passing off to cloud9. I don't remember this being a problem in the past, and I've never had problems logging on to cloud9 directly.
Safari -- Version 11.0.3 (13604.5.100.6)
Upvotes: 4 [selected_answer]<issue_comment>username_2: AWS Cloud9 has been updated so that you no longer need to enable third-party cookies to open the IDE.
<https://forums.aws.amazon.com/ann.jspa?annID=7207>
Upvotes: 1 |
2018/03/19 | 1,087 | 4,857 | <issue_start>username_0: I'm using an Azure function like a scheduled job, using the cron timer. At a specific time each morning it calls a stored procedure.
The function is now taking 4 mins to run a stored procedure that takes a few seconds to run in SSMS. This time is increasing despite efforts to successfully improve the speed of the stored procedure.
The function is not doing anything intensive.
```
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
using (var cmd = new SqlCommand("Stored Proc Here", conn) { CommandType = CommandType.StoredProcedure, CommandTimeout = 600})
{
cmd.Parameters.Add("@Param1", SqlDbType.DateTime2).Value = DateTime.Today.AddDays(-30);
cmd.Parameters.Add("@Param2", SqlDbType.DateTime2).Value = DateTime.Today;
var result = cmd.ExecuteNonQuery();
}
}
```
I've checked and the database is not under load with another process when the stored procedure is running.
Is there anything I can do to speed up the Azure function? Or any approaches to finding out why it's so slow?
**UPDATE.**
I don't believe Azure functions is at fault, the issue seems to be with SQL Server.
I eventually ran the production SP and had a look at the execution plan. I noticed that the statistic were way out, for example a join expected the number of returned rows to be 20, but actual figure was closer to 800k.
The solution for my issue was to update the statistic on a specific table each week.
Regarding why that stats were out so much, well the client does a batch update each night and inserts several hundred thousand rows. I can only assume this affected the stats and it's cumulative, so it seems to get worse with time.<issue_comment>username_1: For a project I worked on we ran into the same thing. Its not a function issue but a sql server issue. For us we were updating sprocs during development and it turns out that per execution plan, sql server will cache certain routes/indexes (layman explanation) and that gets out of sync for the new sproc.
We resolved it by specifying `WITH (RECOMPILE)` at the end of the sproc and the API call and SSMS had the same timings.
Once the system is settled, that statement can and should be removed.
Search on slow sproc fast ssms etc to find others who have run into this situation.
Upvotes: 1 <issue_comment>username_2: Please be careful adding with recompile hints. Often compilation is far more expensive than execution for a given simple query, meaning that you may not get decent perf for all apps with this approach.
There are different possible reasons for your experience. One common reason for this kind of scenario is that you got different query plans in the app vs ssms paths. This can happen for various reasons (I will summarize below). You can determine if you are getting different plans by using the query store (which records summary data about queries, plans, and runtime stats). Please review a summary of it here:
<https://learn.microsoft.com/en-us/sql/relational-databases/performance/monitoring-performance-by-using-the-query-store?view=sql-server-2017>
You need a recent ssms to get the ui, though you can use direct queries from any tds client.
Now for a summary of some possible reasons:
One possible reason for plan differences is set options. These are different environment variables for a query such as enabling ansi nulls on or off. Each different setting could change the plan choice and thus perf. Unfortunately the defaults for different language drivers differ (historical artifacts from when each was built - hard to change now without breaking apps). You can review the query store to see if there are different “context settings” (each unique combination of set options is a unique context settings in query store). Each different set implies different possible plans and thus potential perf changes.
The second major reason for plan changes like you explain in your post is parameter sniffing. Depending on the scope of compilation (example: inside a sproc vs as hoc query text) sql will sometimes look at the current parameter value during compilation to infer the frequency of the common value in future executions. Instead of ignoring the value and just using a default frequency, using a specific value can generate a plan that is optimal for a single value (or set of values) but potentially slower for values outside that set. You can see this in the query plan choice in the query store as well btw.
There are other possible reasons for performance differences beyond what I mentioned. Sometimes there are perf differences when running in mars mode vs not in the client. There may be differences in how you call the client drivers that impact perf beyond this.
I hope this gives you a few tools to debug possible reasons for the difference. Good luck!
Upvotes: 2 |
2018/03/19 | 586 | 1,552 | <issue_start>username_0: Can you help me?
I'm trying to make a PHP Regex to accept only: **A-Z**, **a-z**, **0-9**, **(**, **)**, **!** and accented words(**á**,**é**,**í**,**ó**,**ú** and **Á**,**É**,**Í**,**Ó**,**Ú**) to filter a list.
I tried everyting and searched so much, and I'm not getting succcess...
What should I do?
@edit:
```
if (!preg_match("/^[\p{L}-]*$/u", $line)){
```
I already tried using this from this [thread](https://stackoverflow.com/questions/2133758/how-do-i-match-accented-characters-with-php-preg) but didn't worked.
What I'm trying to do? Accept only words that I want to filter this list:
[List](https://i.stack.imgur.com/8mKVU.png)
@edit2: Already tried convertind to UTF8, using iconv, mb\_convert\_encoding, etc...<issue_comment>username_1: Something like
```
php
$strings = ['hash#', 'percent%', '!exc', 'ó','-',',','num1'];
foreach($strings as $v) {
if (preg_match("/^[\p{L}A-Za-z0-9,!]*$/u", $v)) {
print $v . '<br/';
}
}
```
Upvotes: 0 <issue_comment>username_2: Use this...
```html
php
$strings = ['test(yes)h#', 'test2%', '!test3', 'ó','-',',...','test'];
foreach($strings as $v) {
if (preg_match("/^[\p{L}A-Za-z0-9! | #\((.*?)\)#]*$/u", $v)) {
print $v . '<br/';
}
}
?>
```
I think this will solve your issue.
Upvotes: 0 <issue_comment>username_3: It think this is what you are looking for:
```
if (preg_match("/[a-zA-Z0-9áéíóúÁÉÍÓÚ\s]*/", $line)){
// line is ok
}
```
You can test here: <https://regex101.com/r/4Ozxw2/1>
Upvotes: 3 [selected_answer] |
2018/03/19 | 938 | 2,893 | <issue_start>username_0: I have a Hash-map of type `String`, `ArrayList`. Two different `keys` are stored in the hash-map with list of values.
Now i have to compare the values of different keys and extract the common value. How can achieve this functionality ?
Following is the type of `Hashmap` that i am using:
**Example List:**
```
{Size=[43, 53, 63, 48, 58], Color=[66, 62, 65, 64, 63]}
```
>
> Here is code...
>
>
>
```
private HashMap> mapMatchvalues = new HashMap<>();
for (Map.Entry> map3 : mapMatchvalues.entrySet()) {
List getList1 = new ArrayList<>();
getList1 = map3.getValue();
for (int i = 0; i < getList1.size(); i++) {
if (getList.contains(getList1.get(i))) {
//Print values
} else {
// Print if not matched....
}
}
}
```<issue_comment>username_1: Just iterate your `hashmap` and see if a value matches a value from `ArrayList`.
```
HashMap hashmap=new HashMap();
hashmap.put("Key ABC","ABC");
hashmap.put("Key BCD","BCD");
hashmap.put("Key CDE","CDE");
hashmap.put("Key DEF","DEF");
for(Map.Entry map : hashmap.entrySet()){
if (list.contains(map.getValue()))
System.out.println("VALUE: " + map.getKey());
}
```
Upvotes: 0 <issue_comment>username_2: Please try this
```
HashMap> mapMatchvalues = new HashMap<>();
ArrayList list = new ArrayList<>();
ArrayList list1 = new ArrayList<>();
ArrayList list2 = new ArrayList<>();
list.add("43");
list.add("53");
list.add("63");
list.add("48");
list.add("58");
list1.add("66");
list1.add("62");
list1.add("65");
list1.add("64");
list1.add("63");
list2.add("21");
list2.add("22");
list2.add("23");
list2.add("25");
list2.add("63");
mapMatchvalues.put("Size", list);
mapMatchvalues.put("Color", list1);
mapMatchvalues.put("Color1", list2);
for (Map.Entry map : mapMatchvalues.entrySet()) {
if (list.contains(map.getValue()))
Log.e("VALUE: ", map.getKey() + "");
}
ArrayList commonItem = new ArrayList<>();
for (String item : mapMatchvalues.get("Size")) {
if (mapMatchvalues.get("Color").contains(item) && mapMatchvalues.get("Color1").contains(item)) {
commonItem.add(item);
} else {
//uniqueList.add(item);
}
}
Log.e("tag", commonItem + "");
```
Upvotes: 0 <issue_comment>username_3: You can use [retainAll](https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#retainAll%28java.util.Collection%29). Use new `ArrayList` if you don't want to effect the values in the existing lists.
```
List common = new ArrayList<>(mapMatchvalues.get("key1"));
common.retainAll(mapMatchvalues.get("key2"));
```
`common` will contain the matching elements from the lists.
If you have multiple entries in the map you can loop over it
```
// initialize the common list with List
List common = new ArrayList<>(mapMatchvalues.entrySet().iterator().next().getValue());
for (List list : mapMatchvalues.values()) {
common.retainAll(list);
}
```
Upvotes: 3 |
2018/03/19 | 726 | 2,650 | <issue_start>username_0: Users only have to fill out one of two fields.
How would I require this? And where would it be?
I'm trying to put it in the save, but I believe it belongs elsewhere since the validationerror pops up as a Django error screen, and not a field validation error. Here's what I've tried:
```
class SignupForm(forms.Form):
learn1 = forms.CharField(max_length=50, label='Learn', required=False)
teach1 = forms.CharField(max_length=50, label='Teach', required=False)
class Meta:
model = Profile
def save(self, user):
if not self.cleaned_data['learn1'] or self.cleaned_data['teach1']:
raise forms.ValidationError("Specify at least one")
user.is_profile_to.learn1 = self.cleaned_data['learn1']
user.is_profile_to.teach1 = self.cleaned_data['teach1']
user.save()
user.is_profile_to.save()
```<issue_comment>username_1: ```
def clean(self):
cleaned_data = super().clean()
if not self.cleaned_data['learn1'] and not self.cleaned_data['teach1']:
raise forms.ValidationError("Specify at least one")
else:
return cleaned_data
def save(self, user):
user.is_profile_to.learn1 = self.cleaned_data['learn1']
user.is_profile_to.teach1 = self.cleaned_data['teach1']
user.save()
user.is_profile_to.save()
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: For completeness, you can also handle this at the view level (especially, class-based). You use `form.add_error()` and return `form_invalid()`:
```
class MyView( FormView): # or UpdateView, etc.
# usual definitions
def form_valid( self, form):
if not form.cleaned_data['learn1'] and not form.cleaned_data['teach1']:
form.add_error('', 'You must specify either "Learn" or "Teach"')
return self.form_invalid( form)
super().form_valid( form) # if you want the standard stuff, or
# process the form
# return a response
```
The first argument of `form.add_error` is the name of the form field to attach the error to. `''` specifies a non-form error. You might want the same error attached to both fields instead, in which case just attach two errors
```
form.add_error('learn1', 'You must specify either "Learn" or "Teach"')
form.add_error('teach1', 'You must specify either "Learn" or "Teach"')
return self.form_invalid( form)
```
Doing it this way allows you to access the view context in deciding whether or not something is an error. You can consult the url args or kwargs, or consider who is the user.
Upvotes: 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.