问:
Bash - Append to Array Issue
I'm pretty new to bash.

I have the following code:

```<code>while read line
do
    foundproduct=`echo $line | awk -F "\"*,\"*" '{print $2}'`
    if [ "$foundproduct" == "$product" ]; then
        productid=`echo $line | awk -F "\"*,\"*" '{print $19}'`
        newid=1
        for i in ${productids[@]}
        do
            if [ "${productids[i]}" == "$productid" ] ; then
                newid=0
                break
            fi
        done
        if (( newid == 1 )) ; then
            declare -p productids
            echo "$productid"
            echo "1. $productids[${#productids[@]}]"
            productids+=("$productid")
            echo "2. $productids[${#productids[@]}]"
            declare -p productids
        fi
        loadid=`echo $line | awk -F "\"*,\"*" '{print $39}'`
    fi
done < hddtable1.csv
</code>```

Which produces the following result:

```<code>declare -a productids='()'
ST900MM0006
1. [0]
2. ST900MM0006 [1]
declare -a productids='([0]="ST900MM0006 ")'
declare -a productids='([0]="ST900MM0006 ")'
ST600MM0006
1. ST900MM0006 [1]
2. ST900MM0006 [2]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [2]
2. ST900MM0006 [3]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [3]
2. ST900MM0006 [4]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [4]
2. ST900MM0006 [5]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [5]
2. ST900MM0006 [6]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [6]
2. ST900MM0006 [7]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [7]
2. ST900MM0006 [8]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 ")'
ST300MM0006
1. ST900MM0006 [8]
2. ST900MM0006 [9]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [9]
2. ST900MM0006 [10]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [10]
2. ST900MM0006 [11]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [11]
2. ST900MM0006 [12]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [12]
2. ST900MM0006 [13]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 " [12]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 " [12]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [13]
2. ST900MM0006 [14]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 " [12]="ST300MM0006 " [13]="ST300MM0006 ")'
</code>```

The column from the CSV looks like this: column

I've used this method of appending to arrays in bash in this same script and it worked fine, can someone help me figure out why this isn't working? I tried doing productids+="$productid" and that, for some reason, just appends everything to the end of the first entry in the array.

Iterating through the array:

```<code>for i in ${productids[@]}
do
    echo "${productids[i]}"
done
</code>```

Full output of this:

```<code>ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
</code>```

答: I was accessing the array incorrectly when iterating through it. Should have used "$i" instead of "${productids[i]}".</p>

Title: Bash - Append to Array Issue

Body:
I'm pretty new to bash.

I have the following code:

while read line
do
    foundproduct=`echo $line | awk -F "\"*,\"*" '{print $2}'`
    if [ "$foundproduct" == "$product" ]; then
        productid=`echo $line | awk -F "\"*,\"*" '{print $19}'`
        newid=1
        for i in ${productids[@]}
        do
            if [ "${productids[i]}" == "$productid" ] ; then
                newid=0
                break
            fi
        done
        if (( newid == 1 )) ; then
            declare -p productids
            echo "$productid"
            echo "1. $productids[${#productids[@]}]"
            productids+=("$productid")
            echo "2. $productids[${#productids[@]}]"
            declare -p productids
        fi
        loadid=`echo $line | awk -F "\"*,\"*" '{print $39}'`
    fi
done < hddtable1.csv

Which produces the following result:

declare -a productids='()'
ST900MM0006
1. [0]
2. ST900MM0006 [1]
declare -a productids='([0]="ST900MM0006 ")'
declare -a productids='([0]="ST900MM0006 ")'
ST600MM0006
1. ST900MM0006 [1]
2. ST900MM0006 [2]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [2]
2. ST900MM0006 [3]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [3]
2. ST900MM0006 [4]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [4]
2. ST900MM0006 [5]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [5]
2. ST900MM0006 [6]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [6]
2. ST900MM0006 [7]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 ")'
ST600MM0006
1. ST900MM0006 [7]
2. ST900MM0006 [8]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 ")'
ST300MM0006
1. ST900MM0006 [8]
2. ST900MM0006 [9]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [9]
2. ST900MM0006 [10]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [10]
2. ST900MM0006 [11]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [11]
2. ST900MM0006 [12]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [12]
2. ST900MM0006 [13]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 " [12]="ST300MM0006 ")'
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 " [12]="ST300MM0006 ")'
ST300MM0006
1. ST900MM0006 [13]
2. ST900MM0006 [14]
declare -a productids='([0]="ST900MM0006 " [1]="ST600MM0006 " [2]="ST600MM0006 " [3]="ST600MM0006 " [4]="ST600MM0006 " [5]="ST600MM0006 " [6]="ST600MM0006 " [7]="ST600MM0006 " [8]="ST300MM0006 " [9]="ST300MM0006 " [10]="ST300MM0006 " [11]="ST300MM0006 " [12]="ST300MM0006 " [13]="ST300MM0006 ")'

The column from the CSV looks like this: column

I've used this method of appending to arrays in bash in this same script and it worked fine, can someone help me figure out why this isn't working? I tried doing productids+="$productid" and that, for some reason, just appends everything to the end of the first entry in the array.

Iterating through the array:

for i in ${productids[@]}
do
    echo "${productids[i]}"
done

Full output of this:

ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006
ST900MM0006


来源: stackexchange

问:
C++ list with array of strings
I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful

My input must be something like:

Peter Evens 4.86

*other people**

*average result of the group**

*the one with the heighest grade**

*the one with lowest grade**

This is what I have done for now:

```<code>#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            for (int p = 0; p < n; p++)
                cin >> list[i][j][p];
        }
}
int main() {
    char list[31][MAXN][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}
</code>```

答:
As mentioned in above comments, it's good time to learn vector. It's very easy. Below is a very simple and neat solution:

```<code>#include <iostream>
#include <string>
#include <vector>

using namespace std;

typedef vector<pair<string, string> > Container;

int main()
{
  Container container;
  container.push_back(make_pair("Peter Evens", "4.86"));
  container.push_back(make_pair("Other name", "his score"));
  return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++ list with array of strings

Body:
I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful

My input must be something like:

Peter Evens 4.86

*other people**

*average result of the group**

*the one with the heighest grade**

*the one with lowest grade**

This is what I have done for now:

#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) {
            for (int p = 0; p < n; p++)
                cin >> list[i][j][p];
        }
}
int main() {
    char list[31][MAXN][MAXM];
    int n;
    cin >> n;
    input(list, n);
    return 0;
}

Body:
As mentioned in above comments, it's good time to learn vector. It's very easy. Below is a very simple and neat solution:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

typedef vector<pair<string, string> > Container;

int main()
{
  Container container;
  container.push_back(make_pair("Peter Evens", "4.86"));
  container.push_back(make_pair("Other name", "his score"));
  return 0;
}

ContentLicense: CC BY-SA 4.0


问:
Spark installation in windows
I followed all the steps by Frank kane on his Youtube video to install spark on my windows pc. But i get the following error-

I tweaked Environment variables and paths with no luck. My windows version is windows 10.

答:
The Problem is solved. The problem was with the java installation folder. I installed JDK to its default path which was c:\program files\java\jdk1.8.0_131 , because of that underscore/space spark was not working. Now when i installed jdk on C:\java it worked without a problem. So thanks a lot to those who answered and yes it was a duplicate of the other post which i did not see. the other post was

Why does spark-shell fail with "'""C:\Program' is not recognized as an internal or external command" on Windows?

You can hv a look there too. Same problem , same solution.. thanks..

Title: Spark installation in windows


问:
Detecting extra mouse button click in batch
I'm very new to batch programing, and I was wondering if there is a way to detect when the extra mouse buttons have been clicked in batch.</p>

答:
If you are used to c# you may build a program to detect mouse input and pipe input to the batch itself , i.e getinput.exe | mybatch.cmd. It's not a trivial thing, but you may see how can be achieved (here with powershell) Tetris game in a pure Batch file by Aacini.

You can download a full working mouse batch menu test here. input and output is handled (and written) in c, but main processing is pure batch.

The following code, is a batch hibryd that creates a c# executable if it doesn't exist. You can build c# code  as complex as you may need, the issue is two grab cmd's window input and process it on the batch file.

```<code>//>nul 2>nul||@goto :batch_code
/*
:batch_code
@echo off
setlocal

if not exist "%~n0.exe" call :build_the_exe || exit/B

%~n0.exe
endlocal
exit /b 0

:build_the_exe
:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set "csc=%frm%%netver%\csc.exe"
:: csc not found
if "%csc%" == "\csc.exe" echo/&echo/Warning: Net Framework Not Found&exit/B 1
::csc found
call %csc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
exit/B 0
*/

//begin c# code
public class HelloWorld
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, C# World!");
   }
}
</code>```

Another example

```<code>//>nul 2>nul||@goto :batch_code
/*
:batch_code
@echo off
setlocal

if not exist "keyTime.exe" call :build_the_exe || exit/B

:: use the newly created exe
<NUL set/p="Press a key (wait 5 seconds) "

keyTime.exe /W 5000
endlocal

exit /b 0

:build_the_exe
:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set "csc=%frm%%netver%\csc.exe"
:: csc not found
if "%csc%" == "\csc.exe" echo/&echo/Warning: Net Framework Not Found&exit/B 1
::csc found
call %csc% /nologo /out:"keyTime.exe" "%~dpsfnx0"
exit/B 0
*/

//begin c# code
using System;

namespace ElZooilogico
{
  public static class choice
  {
// readkey with timeout
    private static void ReadKeyTimeout(int msecs, char theChar)
    {
      theChar = '\0';
      ConsoleKeyInfo cfi;
      ReadKeyDelegate d = Console.ReadKey;
      IAsyncResult result = d.BeginInvoke(null, null);
      result.AsyncWaitHandle.WaitOne(msecs);
      if ( result.IsCompleted )
      {
        cfi = d.EndInvoke(result);
        theChar = cfi.KeyChar;
      }
    }
    delegate ConsoleKeyInfo ReadKeyDelegate();
// readkey with timeout

    [STAThread]
    public static int Main(string[] args)
    {
      char myChar='\0'; int wait = 10000;

      for ( int i = 0; i < args.Length; i++ )
      {
        if ( args[i].Equals("/W", StringComparison.OrdinalIgnoreCase) ) { wait = Int32.Parse(args[i + 1]); }
      }

      ReadKeyTimeout(wait, myChar);
      Console.Write(myChar);

      return 0;
    }
  } // class miClass
} // namespace ElZooilogico
</code>```

Body:
If you are used to c# you may build a program to detect mouse input and pipe input to the batch itself , i.e getinput.exe | mybatch.cmd. It's not a trivial thing, but you may see how can be achieved (here with powershell) Tetris game in a pure Batch file by Aacini.

You can download a full working mouse batch menu test here. input and output is handled (and written) in c, but main processing is pure batch.

The following code, is a batch hibryd that creates a c# executable if it doesn't exist. You can build c# code  as complex as you may need, the issue is two grab cmd's window input and process it on the batch file.

//>nul 2>nul||@goto :batch_code
/*
:batch_code
@echo off
setlocal

if not exist "%~n0.exe" call :build_the_exe || exit/B

%~n0.exe
endlocal
exit /b 0

:build_the_exe
:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set "csc=%frm%%netver%\csc.exe"
:: csc not found
if "%csc%" == "\csc.exe" echo/&echo/Warning: Net Framework Not Found&exit/B 1
::csc found
call %csc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
exit/B 0
*/

//begin c# code
public class HelloWorld
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, C# World!");
   }
}

Another example

//>nul 2>nul||@goto :batch_code
/*
:batch_code
@echo off
setlocal

if not exist "keyTime.exe" call :build_the_exe || exit/B

:: use the newly created exe
<NUL set/p="Press a key (wait 5 seconds) "

keyTime.exe /W 5000
endlocal

exit /b 0

:build_the_exe
:: find csc.exe
set "frm=%SystemRoot%\Microsoft.NET\Framework\"
for /f "tokens=* delims=" %%v in ('dir /b /a:d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
   set netver=%%v
   goto :break_loop
)
:break_loop
set "csc=%frm%%netver%\csc.exe"
:: csc not found
if "%csc%" == "\csc.exe" echo/&echo/Warning: Net Framework Not Found&exit/B 1
::csc found
call %csc% /nologo /out:"keyTime.exe" "%~dpsfnx0"
exit/B 0
*/

//begin c# code
using System;

namespace ElZooilogico
{
  public static class choice
  {
// readkey with timeout
    private static void ReadKeyTimeout(int msecs, char theChar)
    {
      theChar = '\0';
      ConsoleKeyInfo cfi;
      ReadKeyDelegate d = Console.ReadKey;
      IAsyncResult result = d.BeginInvoke(null, null);
      result.AsyncWaitHandle.WaitOne(msecs);
      if ( result.IsCompleted )
      {
        cfi = d.EndInvoke(result);
        theChar = cfi.KeyChar;
      }
    }
    delegate ConsoleKeyInfo ReadKeyDelegate();
// readkey with timeout

    [STAThread]
    public static int Main(string[] args)
    {
      char myChar='\0'; int wait = 10000;

      for ( int i = 0; i < args.Length; i++ )
      {
        if ( args[i].Equals("/W", StringComparison.OrdinalIgnoreCase) ) { wait = Int32.Parse(args[i + 1]); }
      }

      ReadKeyTimeout(wait, myChar);
      Console.Write(myChar);

      return 0;
    }
  } // class miClass
} // namespace ElZooilogico


问:
How to determine if a function was called with `.call` or `.apply`?
I created this function so that I could chain methods together:

```<code>export default function bindable(fn) {
    return function boundFn(...args) {
        return this === undefined ? fn(...args) : fn(this, ...args);
    }
}
</code>```

It works with the bind operator. For example, you can define a new function like,

```<code> export const flatten = bindable(arrayOfArrays => Array.prototype.concat(...arrayOfArrays));
</code>```

And then use it like this:

```<code>[[1,2,3],[4,5,6]]::flatten()
</code>```

Or like this:

```<code>flatten([[1,2,3],[4,5,6]])
</code>```

Babel REPL

This worked great at first until I realized that if I use it like in the second scenario, but import the helper method as a module, it breaks the context!

```<code> import * as Arr from './array-helper-methods';
 Arr.flatten([1,2,3]); // `this` is now `Arr`
</code>```

So my question is: is there any way that I can reliably detect if a function is called with the bind operator?

答:
This is rather a workaround than a real solution, but you can check if this contains a flatten property:

```<code>export default function bindable(fn) {
    return function boundFn(...args) {
        return (this === undefined || 'flatten' in this) ? fn(...args) : fn(this, ...args);
    }
}
</code>```

Body:
I created this function so that I could chain methods together:

export default function bindable(fn) {
    return function boundFn(...args) {
        return this === undefined ? fn(...args) : fn(this, ...args);
    }
}

It works with the bind operator. For example, you can define a new function like,

 export const flatten = bindable(arrayOfArrays => Array.prototype.concat(...arrayOfArrays));

And then use it like this:

[[1,2,3],[4,5,6]]::flatten()

Or like this:

flatten([[1,2,3],[4,5,6]])

<a href="https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=env%2Cstage-0&targets=Node-8&browsers=&builtIns=false&debug=true&experimental=true&loose=true&spec=false&code=function%20bindable(fn)%20%7B%0A%20%20%20%20return%20function%20boundFn(...args)%20%7B%0A%20%20%20%20%20%20%20%20return%20this%20!%3D%3D%20undefined%20%26%26%20args.length%20%3C%20fn.length%20%3F%20this%3A%3Afn(this%2C%20...args)%20%3A%20this%3A%3Afn(...args)%3B%0A%20%20%20%20%7D%0A%7D%0A%0Aconst%20flatten%20%3D%20bindable(arrayOfArrays%20%3D%3E%20Array.prototype.concat(...arrayOfArrays))%3B%0A%0Aconsole.log(%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D%3A%3Aflatten())%3B%0Aconsole.log(flatten(%5B%5B1%2C2%2C3%5D%2C%5B4%2C5%2C6%5D%5D))%3B" rel="nofollow noreferrer">Babel REPL

This worked great at first until I realized that if I use it like in the second scenario, but import the helper method as a module, it breaks the context!

 import * as Arr from './array-helper-methods';
 Arr.flatten([1,2,3]); // `this` is now `Arr`

So my question is: is there any way that I can reliably detect if a function is called with the bind operator?

Body:
This is rather a workaround than a real solution, but you can check if this contains a flatten property:

export default function bindable(fn) {
    return function boundFn(...args) {
        return (this === undefined || 'flatten' in this) ? fn(...args) : fn(this, ...args);
    }
}


答:
You'll need to remove the factor levels from your data frame see similar posts on the subject (Convert data.frame columns from factors to characters, How to change factor labels into string in a data frame). Here's a short example based on the supplied data for answering the question.</p>

```<code>dat = data.frame(ID=c('0200','02003','020034','id','020039'),
           X1=c(-9,-9,-9,'G1',-9),
           X2=c(1,0,1,'G2',0), stringsAsFactors = FALSE)
names(dat) <- dat[dat$ID=='id',])
dat <- dat[which(dat$id!='id'),]  # remove the 'id' row
</code>```

Title: How i can shift one row dataframe to be header?

Body:
Whats wrong in the input codes, where and why the numbers 5109 2 5 5.1 5.2 come to header, i want to id row at 4509 be the header.

data[1:3,1:5]

         ID   X1  X2 X3 X4
1    02003KH1 -9  1  2  1
2 02003KH1005 -9  0  1  2
3 02003KH1021 -9  1  1  1

> data[4507:4509,1:5]
           ID    X1 X2 X3 X4
4507 2010XX2178  -9 0 2 2
4508 2010XX2228  -9 0 2 2
4509 id        G_r8 G_r9 G_r5 G_r80

> names(data) <- data[data$ID=='id',]

> data[1:3,1:5]
    5109       2 5 5.1 5.2
1 02003KH1    -9 1   2   1
2 02003KH1005 -9 0   1   2
3 02003KH1021 -9 1   1   1

Body:
You'll need to remove the factor levels from your data frame see similar posts on the subject (Convert data.frame columns from factors to characters, How to change factor labels into string in a data frame). Here's a short example based on the supplied data for answering the question.

dat = data.frame(ID=c('0200','02003','020034','id','020039'),
           X1=c(-9,-9,-9,'G1',-9),
           X2=c(1,0,1,'G2',0), stringsAsFactors = FALSE)
names(dat) <- dat[dat$ID=='id',])
dat <- dat[which(dat$id!='id'),]  # remove the 'id' row


问:
JavaFX controller isnt getting content
Im new to using controllers in JavaFX and im having trouble. My first scene loads fine but when I click the button to move to the second scene nothing comes up just a blank box. Any clues on how to load my 2nd scene?

Here is my starter scene:

```<code>public class ControllerConnect implements Controller{
    private final FlowPane root;
    public ControllerConnect() {
        //Connection page objects
        TextField username = new TextField();
        TextField password = new TextField();
        username.setAlignment(Pos.CENTER);
        password.setAlignment(Pos.CENTER);
        Button connect = new Button("Connect");
        connect.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent e) {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                } catch (ClassNotFoundException ex) {
                    System.out.println("Error: unable to load driver class!");
                    System.exit(1);
                }
                String URL = "jdbc:mysql://localhost:3306/world";
                String name = username.getText();
                String pass = password.getText();

                try {
                    Connection conn = DriverManager.getConnection(URL, name, pass);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                ControllerCity controller2 = new ControllerCity();
                connect.getScene().setRoot(controller2.getContent());

            }
        });
        root = new FlowPane(connect);
        Label user = new Label("Username:");
        Label pass = new Label("Password:");
        user.setAlignment(Pos.CENTER);
        pass.setAlignment(Pos.CENTER);
        username.setAlignment(Pos.CENTER);
        password.setAlignment(Pos.CENTER);
        connect.setAlignment(Pos.CENTER);
        VBox connectionBox = new VBox(10, user, username, pass, password, connect);
        connectionBox.setAlignment(Pos.CENTER);
        root.getChildren().addAll(connectionBox);
        root.setMinSize(640, 480);
        root.setAlignment(Pos.CENTER);

    }
    @Override
    public Parent getContent() {
        return root;
    }
}
</code>```

Here is my 2nd scene only half finished but the buttons should show:

```<code>public class ControllerCity implements Controller {
    private final BorderPane root = new BorderPane();
    public ControllerCity() {
        //Layout for city pane
        //HBox for buttons

        Button populate = new Button("Populate/Update");
        Button delete = new Button("Delete");
        Button create = new Button("Create");
        HBox cityButtons = new HBox(populate, delete, create);
        root.setBottom(cityButtons);
        //HBox for TableView
        HBox cityTable = new HBox();
        root.setCenter(cityTable);
        root.setMinSize(1024, 768);

    }
    @Override
    public Parent getContent() {
        return root;
    }
}
</code>```

Application class:

```<code>public void start(Stage primaryStage) throws Exception {
    ControllerConnect controllerconnect = new ControllerConnect();
    Scene scene = new Scene(
            controllerconnect.getContent()
    );

    primaryStage.setScene(scene);
    primaryStage.show();
}
</code>```

答:
The buttons are present: you just can't see them.

The issue is that your first "controller" (which is surely a view, not a controller) sets a minimum size of 640 x 480 pixels. The scene will size to the preferred size of the root, which in this case will be 640 x 480 (because the controls in the first scene do not need more space than that).

Your second scene sets a minimum size of 1024 x 768. So the second view is now bigger than the stage containing it, and the buttons are out of view.

If you expand the window after pressing the "Connect" button, you will see the buttons.

If you replace

```<code>ControllerCity controller2 = new ControllerCity();
connect.getScene().setRoot(controller2.getContent());
</code>```

in the button's event handler with

```<code>ControllerCity controller2 = new ControllerCity();
Scene scene = connect.getScene();
scene.setRoot(controller2.getContent());
scene.getWindow().sizeToScene();
</code>```

then the window will resize so you can see the buttons.

Title: JavaFX controller isnt getting content

Body:
Im new to using controllers in JavaFX and im having trouble. My first scene loads fine but when I click the button to move to the second scene nothing comes up just a blank box. Any clues on how to load my 2nd scene?

Here is my starter scene:

public class ControllerConnect implements Controller{
    private final FlowPane root;
    public ControllerConnect() {
        //Connection page objects
        TextField username = new TextField();
        TextField password = new TextField();
        username.setAlignment(Pos.CENTER);
        password.setAlignment(Pos.CENTER);
        Button connect = new Button("Connect");
        connect.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent e) {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                } catch (ClassNotFoundException ex) {
                    System.out.println("Error: unable to load driver class!");
                    System.exit(1);
                }
                String URL = "jdbc:mysql://localhost:3306/world";
                String name = username.getText();
                String pass = password.getText();

                try {
                    Connection conn = DriverManager.getConnection(URL, name, pass);
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
                ControllerCity controller2 = new ControllerCity();
                connect.getScene().setRoot(controller2.getContent());

            }
        });
        root = new FlowPane(connect);
        Label user = new Label("Username:");
        Label pass = new Label("Password:");
        user.setAlignment(Pos.CENTER);
        pass.setAlignment(Pos.CENTER);
        username.setAlignment(Pos.CENTER);
        password.setAlignment(Pos.CENTER);
        connect.setAlignment(Pos.CENTER);
        VBox connectionBox = new VBox(10, user, username, pass, password, connect);
        connectionBox.setAlignment(Pos.CENTER);
        root.getChildren().addAll(connectionBox);
        root.setMinSize(640, 480);
        root.setAlignment(Pos.CENTER);

    }
    @Override
    public Parent getContent() {
        return root;
    }
}

Here is my 2nd scene only half finished but the buttons should show:

public class ControllerCity implements Controller {
    private final BorderPane root = new BorderPane();
    public ControllerCity() {
        //Layout for city pane
        //HBox for buttons

        Button populate = new Button("Populate/Update");
        Button delete = new Button("Delete");
        Button create = new Button("Create");
        HBox cityButtons = new HBox(populate, delete, create);
        root.setBottom(cityButtons);
        //HBox for TableView
        HBox cityTable = new HBox();
        root.setCenter(cityTable);
        root.setMinSize(1024, 768);

    }
    @Override
    public Parent getContent() {
        return root;
    }
}

Application class:

public void start(Stage primaryStage) throws Exception {
    ControllerConnect controllerconnect = new ControllerConnect();
    Scene scene = new Scene(
            controllerconnect.getContent()
    );

    primaryStage.setScene(scene);
    primaryStage.show();
}

Body:
The buttons are present: you just can't see them.

The issue is that your first "controller" (which is surely a view, not a controller) sets a minimum size of 640 x 480 pixels. The scene will size to the preferred size of the root, which in this case will be 640 x 480 (because the controls in the first scene do not need more space than that).

Your second scene sets a minimum size of 1024 x 768. So the second view is now bigger than the stage containing it, and the buttons are out of view.

If you expand the window after pressing the "Connect" button, you will see the buttons.

If you replace

ControllerCity controller2 = new ControllerCity();
connect.getScene().setRoot(controller2.getContent());

in the button's event handler with

ControllerCity controller2 = new ControllerCity();
Scene scene = connect.getScene();
scene.setRoot(controller2.getContent());
scene.getWindow().sizeToScene();

then the window will resize so you can see the buttons.


问:
Changing background-image onscroll
I'm trying to change the background image of an element after a certain position has been scrolled past. Here's a snippet of my code:

```<code><body>
 <script>
  window.onscroll = function() {scrollBG()};

  function scrollBG() {
   if (document.body.scrollTop > document.getElementById("one").getBoundingClientRect().top ||
       document.documentElement.scrollTop > document.getElementById("one").getBoundingClientRect().top) {
     document.getElementById("outer").style.backgroundImage = "url('imgs/pic1.jng')";
   } else {
     document.getElementById("outer").style.backgroundImage = "url('imgs/pic2.jpg')";
   }
  }
 </script>
 <table id="outer">
</code>```

I'm using a similar coding style to show/hide a "back to top" button after a certain scroll position that functions just fine. I don't think there's a conflict between the two (though inline scripting isn't my preferred style) because even when I remove everything related to the "back to top" button, my code still fails to function.

Is this a stupid syntactical error, or is there a more fundamental error to my approach?

答:
I've tweaked your code a little and it's working:

jsFiddle 1

var divOuter = document.getElementById("outer"),
 divOne = document.getElementById("one");

window.onscroll = function() {scrollBG()};

  function scrollBG() {
   var oneTop = divOne.getBoundingClientRect().top;
   if(document.body.scrollTop > oneTop ||
       document.documentElement.scrollTop > oneTop){
         divOuter.style.backgroundImage = "url('//www.planwallpaper.com/static/images/518071-background-hd_xO1TwRc.jpg')";
       } else {
          divOuter.style.backgroundImage = "url('//www.planwallpaper.com/static/images/maxresdefault_YodSsVN.jpg')";
       }
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; padding: 0; height: 1500px; }
#outer {
  position: fixed;
  background: url('//www.planwallpaper.com/static/images/maxresdefault_YodSsVN.jpg') no-repeat;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
#one {
  width: 100%;
  height: 150px;
  background-color: orange;
  color: white;
  position: relative;
  top: 400px;
}</code>```

This is One

```
</div>
</div>
</p>

<p>However, following the above method will be inefficient as IMHO it makes an extra HTTP request for the images every time the scroll goes up and down the threshold and thus you'll see flickering every time the background images get changed. </p>

<p>So it'd be better if we make use of an external CSS class, i.e <code>#outer.bg2</code>, and just add/remove it depending on the position of the scroll and this will fetch a cached version of the image which makes it smooth [<em>except for the first time when the image is being requested for the first time</em>]. Like below:</p>

<p><strong>jsFiddle 2</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var divOuter = document.getElementById("outer"),
  divOne = document.getElementById("one");

window.onscroll = function() { scrollBG() };

function scrollBG() {
  var oneTop = divOne.offsetTop;
  if (document.body.scrollTop > oneTop ||
    document.documentElement.scrollTop > oneTop) {
    divOuter.classList.add('bg2');
  } else {
    divOuter.classList.remove('bg2');
  }
}</code>```

body{ margin:0; padding:0; height: 1500px; }
#outer{
  position:fixed;
  background: url('//www.planwallpaper.com/static/images/maxresdefault_YodSsVN.jpg') no-repeat;
  top:0;
  left:0;
  right:0;
  bottom:0;
}
#outer.bg2{
  background: url('//www.planwallpaper.com/static/images/518071-background-hd_xO1TwRc.jpg');
}
#one{
  width:100%;
  height:150px;
  background-color:orange;
  color:white;
  position:relative;
  top:400px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="outer"></div>
<div id="one"><h1>This is One</h1></div></code>```

In the above code the triggering will happen when the scroll meets the bottom of the element #one, if you want the triggering to happen according to the top edge then replace this:

```<code>var oneTop = divOne.offsetTop;
</code>```

With this:

```<code>var oneTop = divOne.offsetTop - divOne.offsetHeight;
</code>```

jsFiddle 3

Title: Changing background-image onscroll

Body:
I'm trying to change the background image of an element after a certain position has been scrolled past. Here's a snippet of my code:

I'm using a similar coding style to show/hide a "back to top" button after a certain scroll position that functions just fine. I don't think there's a conflict between the two (though inline scripting isn't my preferred style) because even when I remove everything related to the "back to top" button, my code still fails to function.

Is this a stupid syntactical error, or is there a more fundamental error to my approach?

Body:
I've tweaked your code a little and it's working:

jsFiddle 1

var divOuter = document.getElementById("outer"),
 divOne = document.getElementById("one");

window.onscroll = function() {scrollBG()};

  function scrollBG() {
   var oneTop = divOne.getBoundingClientRect().top;
   if(document.body.scrollTop > oneTop ||
       document.documentElement.scrollTop > oneTop){
         divOuter.style.backgroundImage = "url('//www.planwallpaper.com/static/images/518071-background-hd_xO1TwRc.jpg')";
       } else {
          divOuter.style.backgroundImage = "url('//www.planwallpaper.com/static/images/maxresdefault_YodSsVN.jpg')";
       }
  }

body { margin: 0; padding: 0; height: 1500px; }
#outer {
  position: fixed;
  background: url('//www.planwallpaper.com/static/images/maxresdefault_YodSsVN.jpg') no-repeat;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
#one {
  width: 100%;
  height: 150px;
  background-color: orange;
  color: white;
  position: relative;
  top: 400px;
}

<div id="outer"></div>
<div id="one"><h1>This is One</h1></div>

However, following the above method will be inefficient as IMHO it makes an extra HTTP request for the images every time the scroll goes up and down the threshold and thus you'll see flickering every time the background images get changed.

So it'd be better if we make use of an external CSS class, i.e #outer.bg2, and just add/remove it depending on the position of the scroll and this will fetch a cached version of the image which makes it smooth [except for the first time when the image is being requested for the first time]. Like below:

jsFiddle 2

var divOuter = document.getElementById("outer"),
  divOne = document.getElementById("one");

window.onscroll = function() { scrollBG() };

function scrollBG() {
  var oneTop = divOne.offsetTop;
  if (document.body.scrollTop > oneTop ||
    document.documentElement.scrollTop > oneTop) {
    divOuter.classList.add('bg2');
  } else {
    divOuter.classList.remove('bg2');
  }
}

body{ margin:0; padding:0; height: 1500px; }
#outer{
  position:fixed;
  background: url('//www.planwallpaper.com/static/images/maxresdefault_YodSsVN.jpg') no-repeat;
  top:0;
  left:0;
  right:0;
  bottom:0;
}
#outer.bg2{
  background: url('//www.planwallpaper.com/static/images/518071-background-hd_xO1TwRc.jpg');
}
#one{
  width:100%;
  height:150px;
  background-color:orange;
  color:white;
  position:relative;
  top:400px;
}

<div id="outer"></div>
<div id="one"><h1>This is One</h1></div>

In the above code the triggering will happen when the scroll meets the bottom of the element #one, if you want the triggering to happen according to the top edge then replace this:

var oneTop = divOne.offsetTop;

With this:

var oneTop = divOne.offsetTop - divOne.offsetHeight;

jsFiddle 3


问:
WARNING: Module ini file doesn't exist under /etc/php/7.0/mods-available
I have uninstalled php7 and all its modules from ubuntu, and when I try to reinstall the modules, I get the following error for each php module, and although the module is installed, because of this error, it is not activated and I cannot use them.
Is the any way to solve this issue ?
the error for each module(when installing):</p>

```<code>Not replacing deleted config file /etc/php/7.0/mods-available/intl.ini
WARNING: Module [module name] ini file doesn't exist under /etc/php/7.0/mods-available
WARNING: Module [module name] ini file doesn't exist under /etc/php/7.0/mods-available
WARNING: Module [module name] ini file doesn't exist under /etc/php/7.0/mods-available
</code>```

答:
I came here because I had trouble installing Phpmyadmin on Ubuntu after upgrading from php 7.0 to 7.1

Here is the trick

remove php version (7.0 for instance - adapt the command line)

sudo apt-get purge php7.0-common

Note --> You should check the list of packages that will be removed.

Install php modules

sudo apt-get install php7.1-mbstring
sudo apt-get install php7.1-mcrypt
...

activate the modules

sudo phpenmod mbstring
sudo phpenmod mcrypt

(option for apache) activate php7.1

```<code>sudo a2enmod php7.1
</code>```

And of course restart your server (apache in this case)

```<code>sudo systemctl restart apache2
</code>```

Body:
I have uninstalled php7 and all its modules from ubuntu, and when I try to reinstall the modules, I get the following error for each php module, and although the module is installed, because of this error, it is not activated and I cannot use them.
Is the any way to solve this issue ?
the error for each module(when installing):

Not replacing deleted config file /etc/php/7.0/mods-available/intl.ini
WARNING: Module [module name] ini file doesn't exist under /etc/php/7.0/mods-available
WARNING: Module [module name] ini file doesn't exist under /etc/php/7.0/mods-available
WARNING: Module [module name] ini file doesn't exist under /etc/php/7.0/mods-available

Body:
I came here because I had trouble installing Phpmyadmin on Ubuntu after upgrading from php 7.0 to 7.1

Here is the trick

remove php version (7.0 for instance - adapt the command line)

sudo apt-get purge php7.0-common

Note --> You should check the list of packages that will be removed.

Install php modules

sudo apt-get install php7.1-mbstring
sudo apt-get install php7.1-mcrypt
...

activate the modules

sudo phpenmod mbstring
sudo phpenmod mcrypt

(option for apache) activate php7.1

sudo a2enmod php7.1

And of course restart your server (apache in this case)

sudo systemctl restart apache2


问:
Java: Strange result after decompiling
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

```<code>public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}
</code>```

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?

答:
As @Joachim Sauer correctly points out: The JVM specification poses less constraints on method overloading in the bytecode than the JLS does on Java programs.

From the JVM Specification (Section 4.6, Methods):

No two methods in one class file may have the same name and descriptor (§4.3.3).

And a method descriptor includes the return type: (4.3.3 Method Descriptors)

MethodDescriptor:

      ( ParameterDescriptor* ) ReturnDescriptor

The methods you mentioned in your question all have distinct descriptors, so they are okay:

```<code>public final void a(ak aa)     ->     (Lsomepkg1/ak;)V
public final void a(cn ccn)    ->     (Lsomepkg2/ccn;)V
public final cN a()            ->     ()Lsomepkg3/cN;
public final void a()          ->     ()V
public final boolean a()       ->     ()Z
</code>```

This is cleverly exploited by obfuscators. A valid bytecode-program no longer has a "directly corresponding" Java program. ProGuard does this for instance. Here is a snippet from their manual:

-overloadaggressively

  Specifies to apply aggressive overloading while obfuscating. Multiple fields and methods can then get the same names, as long as their arguments and return types are different (not just their arguments).

There are other similar techniques using for instance the jsr bytecode instruction or using variable identifiers that are reserved words in the Java language. Here is a webpage listing a few techniques.

To answer the obvious follow-up question: How does the JVM know which method to call at the call-site?

The invoke-instructions require you to specify a reference to a complete method signature, (including the return type of the method) that is to be called.

Title: Java: Strange result after decompiling

Body:
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?

Body:
As @Joachim Sauer correctly points out: The JVM specification poses less constraints on method overloading in the bytecode than the JLS does on Java programs.

From the JVM Specification (Section 4.6, Methods):

No two methods in one class file may have the same name and descriptor (§4.3.3).

And a method descriptor includes the return type: (4.3.3 Method Descriptors)

MethodDescriptor:

      ( ParameterDescriptor* ) ReturnDescriptor

The methods you mentioned in your question all have distinct descriptors, so they are okay:

public final void a(ak aa)     ->     (Lsomepkg1/ak;)V
public final void a(cn ccn)    ->     (Lsomepkg2/ccn;)V
public final cN a()            ->     ()Lsomepkg3/cN;
public final void a()          ->     ()V
public final boolean a()       ->     ()Z

This is cleverly exploited by obfuscators. A valid bytecode-program no longer has a "directly corresponding" Java program. ProGuard does this for instance. Here is a snippet from their manual:

-overloadaggressively

  Specifies to apply aggressive overloading while obfuscating. Multiple fields and methods can then get the same names, as long as their arguments and return types are different (not just their arguments).

There are other similar techniques using for instance the jsr bytecode instruction or using variable identifiers that are reserved words in the Java language. Here is a webpage listing a few techniques.

To answer the obvious follow-up question: How does the JVM know which method to call at the call-site?

The invoke-instructions require you to specify a reference to a complete method signature, (including the return type of the method) that is to be called.


问:
Join two tables with same ID and merge ID columns
This is probably a pretty simple question, but most of the searches I do have to do with merging rows (not merging columns) or concatenating them.

I want to join two tables on an ID column, but I only want it to return a single ID column.

Example:

Table 1:

```<code>ID|Data1|Data2
</code>```

Table2:

```<code>ID|Data3|Data4
</code>```

I want it to return:

```<code>ID|Data1|Data2|Data3|Data4
</code>```

EDIT:

I realize I can specify every column, but there are actually closer to 50 columns that I'm bringing over and I would prefer not to have to specify every single one. Is there a way to do this without specifying each column to bring over from the query?

I believe natural join is what I need, but see this error I'm getting:

```<code>SELECT *
FROM allqachecklists t1
WHERE t1.IsIncorrect=1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2
</code>```

1 errors were found during analysis.

Unrecognized keyword. (near "NATURAL" at position 59)

答:
This is waht you need</p>

```<code>SELECT table1.ID,table1.Data1,table1.Data2,table2.Data3,table2.Data4
FROM table1
JOIN table2 ON table1.id=table2.id
</code>```

Body:
This is probably a pretty simple question, but most of the searches I do have to do with merging rows (not merging columns) or concatenating them.

I want to join two tables on an ID column, but I only want it to return a single ID column.

Example:

Table 1:

ID|Data1|Data2

Table2:

ID|Data3|Data4

I want it to return:

ID|Data1|Data2|Data3|Data4

EDIT:

I realize I can specify every column, but there are actually closer to 50 columns that I'm bringing over and I would prefer not to have to specify every single one. Is there a way to do this without specifying each column to bring over from the query?

I believe natural join is what I need, but see this error I'm getting:

SELECT *
FROM allqachecklists t1
WHERE t1.IsIncorrect=1
NATURAL JOIN (SELECT QAID, PMC, SiteName, Submitter, QAer FROM qabin.allqas) t2

1 errors were found during analysis.

Unrecognized keyword. (near "NATURAL" at position 59)

Body:
This is waht you need

SELECT table1.ID,table1.Data1,table1.Data2,table2.Data3,table2.Data4
FROM table1
JOIN table2 ON table1.id=table2.id


问:
How can rename a folder which is in another path?
I need to rename folders in my code.

My current code:

```<code>target_file = input("Input folder that you want to rename >>>")
rename = input("Please write a new name for it >>> ")
try :
  os.rename(target_file, rename)
  print("Successfull")
except :
  print("!!! You didn't write file name right. Try again !!!")
</code>```

This code renaming folders in current working path. But I need to rename files in other paths, like this:

```<code>os.rename(C:\\user\\oldname, newname)
</code>```

Is it possible?

答:
You can, but you have to be careful that you use the absolute path for the first argument, whereas the second is the relative path.

In two words, it means that you will find the file you are looking for, but that it will be saved in the folder your script is running in.

As the comment suggest, if you want to only rename while keeping it in the same place, you would have to write the absolute path every time or find a clever way to transpose the relative path you enter as a second argument into a relative path...

One idea would be to split your first argument in a way to get the absolute path minus the folder you want to rename :

target_file_path = '/'.join(target_file.split('/')[:-1])

Body:
I need to rename folders in my code.

My current code:

target_file = input("Input folder that you want to rename >>>")
rename = input("Please write a new name for it >>> ")
try :
  os.rename(target_file, rename)
  print("Successfull")
except :
  print("!!! You didn't write file name right. Try again !!!")

This code renaming folders in current working path. But I need to rename files in other paths, like this:

os.rename(C:\\user\\oldname, newname)

Is it possible?


问:
Optimizing code for calculating the best move for Animal Java
```<code>/**
 *
 * @param listOfEntities - The list to be checked
 * @param entity - The entity to base the searching off of.
 * @return - the Point of the highest scoring goal
 *
 * TODO: Make this code better, it relies too much on instanceof and is not OOP.
 *
 */
protected Point getBestMove(List<Point> listOfEntities,Entity entity) {
    //Store the position of the highest valued prey.
    Point highestScore = null;

    // Check if the entity passed in is a Sheep, if it is
    // then loop through the map within the line of sight
    // of this animal and then score individually.
    // Based on the result move in a direction that is benifitial.
    if (entity instanceof Sheep) {
        // The scoring map using a Point, Double system.
        Map<Point, Double> bestMoveMap = new HashMap<>();

        //Loop through for every entity position in listOfEntities
        for(Point currentEntity : listOfEntities) {
            //Put this current entity with a basevalue of 2400.
            bestMoveMap.put(currentEntity, 2400.0);

            // Loop X and Y within line of sight (- since we want both directions)
            for (int xPos = - lineOfSight; xPos <= lineOfSight; xPos++) {
                for (int yPos = - lineOfSight; yPos <= lineOfSight; yPos++) {
                    // Get the starting point of this entity
                    double points = bestMoveMap.get(currentEntity);

                    // Get the distance between this entity and the goal entity.
                    Point goalPoint = new Point(currentEntity.x + xPos,currentEntity.y + yPos);

                    // Store all entities in a list within range.
                    List<Entity> entities = pasture.getGrid().get(goalPoint);

                    //If list is not empty or null
                    if(entities != null && entities.isEmpty() == false) {
                        //Loop through all the entities
                        for(Entity e : entities) {
                            //If it is a wolf.
                            if(e instanceof Wolf) {
                                //Score depending on distance using a formula.
                                double distanceToWolf = goalPoint.distance(currentEntity);

                                // Calculate using a formula where we factor in the distance to the wolf.
                                points = points + (1000 / (1 + distanceToWolf));

                                // Put this entity with the position.
                                bestMoveMap.put(currentEntity, points);
                            }
                            // If it is a plant.
                            if(e instanceof Plant) {
                                //Score depending on distance using a formula.
                                double distanceToPlant = goalPoint.distance(currentEntity);

                                points = points - (100 / (1 + distanceToPlant));
                                bestMoveMap.put(currentEntity, points);
                            }
                        }
                    }
                }
            }}

        //Minimum score.
        Map.Entry<Point, Double> minScore = null;

        // Get the highest scored value and set minScore aswell as highestScore.
        // Since Java 8 you could do this:
        // Collections.max(bestMoveMap.entrySet(), Map.Entry.comparingByValue()).getKey();
        for (Map.Entry<Point, Double> entry : bestMoveMap.entrySet()){
            if (minScore == null || minScore.getValue() > entry.getValue()){
                // Set highestScore to that and minScore to that entry.
                minScore = entry;
                highestScore= minScore.getKey();
            }
        }
    }
    // If the entity is a Wolf
    if(entity instanceof Wolf){
        Map<Point, Double> bestMoveMap = new HashMap<>();
        for(Point thisPoint : listOfEntities){
            bestMoveMap.put(thisPoint, 2000.0);

            for (int x = -lineOfSight; x <= lineOfSight; x++) {
                for (int y = -lineOfSight; y <= lineOfSight; y++) {
                    Point p = new Point(thisPoint.x + x,thisPoint.y + y);
                    List<Entity> l =pasture.getGrid().get(p);
                    if(l!=null){
                        for(Entity e:l){

                            //Only interested in Sheeps
                            if(e instanceof Sheep){
                                double distanceToSheep=p.distance(thisPoint);
                                double points=bestMoveMap.get(thisPoint);
                                points = points -(10000/(0.1+distanceToSheep));
                                bestMoveMap.put(thisPoint, points);
                            }
                        }
                    }
                }
            }
        }
        // Set highestScore to the best Point.
        Map.Entry<Point, Double> min = null;
        for(Map.Entry<Point, Double> entry : bestMoveMap.entrySet()) {
            if (min == null || min.getValue() > entry.getValue()) {
                min = entry;
                highestScore= min.getKey();
            }
        }
    }

    // Return the highest score, the Point that scored the highest
    return highestScore;
}
</code>```

I got this code above which finds the best new Point for an Animal. The basic idea is:

Sheeps eats grass and avoids Wolves
Wolves hunt Sheeps and has no enemies

It is pretty long and I was wondering if there is any way I could shorten or improve it? I feel as if the "instanceof" is a bad habit but I am not sure how to do it otherwise or what to replace it with. Especially since the code is so similar in many aspects. Maybe I can combine it in some way?

答:
The way to avoid instanceof is to move functionality into classes and make use of inheritance and polymorphism.

So, instead of if( e instanceof Wolf ) { do wolfy stuff... } else if( e instanceof Plant ) { do plant stuff... } you would invoke e.doStuff().

Then, the Wolf entity would have an implementation of doStuff() which does wolfy stuff, while the Plant entity would have its own implementation of doStuff() which does plant stuff.

Of course the base class Entity would declare a public abstract doStuff(); so that Wolf and Plant can override it.

Body:
/**
 *
 * @param listOfEntities - The list to be checked
 * @param entity - The entity to base the searching off of.
 * @return - the Point of the highest scoring goal
 *
 * TODO: Make this code better, it relies too much on instanceof and is not OOP.
 *
 */
protected Point getBestMove(List<Point> listOfEntities,Entity entity) {
    //Store the position of the highest valued prey.
    Point highestScore = null;

    // Check if the entity passed in is a Sheep, if it is
    // then loop through the map within the line of sight
    // of this animal and then score individually.
    // Based on the result move in a direction that is benifitial.
    if (entity instanceof Sheep) {
        // The scoring map using a Point, Double system.
        Map<Point, Double> bestMoveMap = new HashMap<>();

        //Loop through for every entity position in listOfEntities
        for(Point currentEntity : listOfEntities) {
            //Put this current entity with a basevalue of 2400.
            bestMoveMap.put(currentEntity, 2400.0);

            // Loop X and Y within line of sight (- since we want both directions)
            for (int xPos = - lineOfSight; xPos <= lineOfSight; xPos++) {
                for (int yPos = - lineOfSight; yPos <= lineOfSight; yPos++) {
                    // Get the starting point of this entity
                    double points = bestMoveMap.get(currentEntity);

                    // Get the distance between this entity and the goal entity.
                    Point goalPoint = new Point(currentEntity.x + xPos,currentEntity.y + yPos);

                    // Store all entities in a list within range.
                    List<Entity> entities = pasture.getGrid().get(goalPoint);

                    //If list is not empty or null
                    if(entities != null && entities.isEmpty() == false) {
                        //Loop through all the entities
                        for(Entity e : entities) {
                            //If it is a wolf.
                            if(e instanceof Wolf) {
                                //Score depending on distance using a formula.
                                double distanceToWolf = goalPoint.distance(currentEntity);

                                // Calculate using a formula where we factor in the distance to the wolf.
                                points = points + (1000 / (1 + distanceToWolf));

                                // Put this entity with the position.
                                bestMoveMap.put(currentEntity, points);
                            }
                            // If it is a plant.
                            if(e instanceof Plant) {
                                //Score depending on distance using a formula.
                                double distanceToPlant = goalPoint.distance(currentEntity);

                                points = points - (100 / (1 + distanceToPlant));
                                bestMoveMap.put(currentEntity, points);
                            }
                        }
                    }
                }
            }}

        //Minimum score.
        Map.Entry<Point, Double> minScore = null;

        // Get the highest scored value and set minScore aswell as highestScore.
        // Since Java 8 you could do this:
        // Collections.max(bestMoveMap.entrySet(), Map.Entry.comparingByValue()).getKey();
        for (Map.Entry<Point, Double> entry : bestMoveMap.entrySet()){
            if (minScore == null || minScore.getValue() > entry.getValue()){
                // Set highestScore to that and minScore to that entry.
                minScore = entry;
                highestScore= minScore.getKey();
            }
        }
    }
    // If the entity is a Wolf
    if(entity instanceof Wolf){
        Map<Point, Double> bestMoveMap = new HashMap<>();
        for(Point thisPoint : listOfEntities){
            bestMoveMap.put(thisPoint, 2000.0);

            for (int x = -lineOfSight; x <= lineOfSight; x++) {
                for (int y = -lineOfSight; y <= lineOfSight; y++) {
                    Point p = new Point(thisPoint.x + x,thisPoint.y + y);
                    List<Entity> l =pasture.getGrid().get(p);
                    if(l!=null){
                        for(Entity e:l){

                            //Only interested in Sheeps
                            if(e instanceof Sheep){
                                double distanceToSheep=p.distance(thisPoint);
                                double points=bestMoveMap.get(thisPoint);
                                points = points -(10000/(0.1+distanceToSheep));
                                bestMoveMap.put(thisPoint, points);
                            }
                        }
                    }
                }
            }
        }
        // Set highestScore to the best Point.
        Map.Entry<Point, Double> min = null;
        for(Map.Entry<Point, Double> entry : bestMoveMap.entrySet()) {
            if (min == null || min.getValue() > entry.getValue()) {
                min = entry;
                highestScore= min.getKey();
            }
        }
    }

    // Return the highest score, the Point that scored the highest
    return highestScore;
}

I got this code above which finds the best new Point for an Animal. The basic idea is:

Sheeps eats grass and avoids Wolves
Wolves hunt Sheeps and has no enemies

It is pretty long and I was wondering if there is any way I could shorten or improve it? I feel as if the "instanceof" is a bad habit but I am not sure how to do it otherwise or what to replace it with. Especially since the code is so similar in many aspects. Maybe I can combine it in some way?


问:
How to center the page title in ConstraintLayout
I am using ConstraintLayout to show the page, and I can't find the way to make the title at center of the bar. I didn't use the action bar or tools bar. The solution I found online is all about add a label on active bar which I don't have.

Here is the layout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_centerHorizontal="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    tools:context="com.spydertrap.occexample.MainActivity"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="206dp" />

    <android.support.v7.widget.CardView
        android:id="@+id/cardView2"
        android:layout_height="150dp"
        android:layout_width="0dp"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/cardView"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:layout_marginBottom="50dp"
            app:srcCompat="@drawable/resource" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="116dp"
            android:layout_marginLeft="10dp"
            android:textAppearance="@style/CardSubTitle"
            android:text="Resource Center" />
    </android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
</code>```

and the activity is pretty simple:

```<code>public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("Dashboard");
    }
}
</code>```

This title needs to be centered

any help will be appreciated!!

答:
Override the setTitle(CharSequence title) method of the Activity.

public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setTitle("Dashboard");

}

@Override
public void setTitle(CharSequence title) {
    super.setTitle(title);

    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER_HORIZONTAL);
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
}
</code>```

Body:
I am using ConstraintLayout to show the page, and I can't find the way to make the title at center of the bar. I didn't use the action bar or tools bar. The solution I found online is all about add a label on active bar which I don't have.

Here is the layout:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_centerHorizontal="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="right"
    tools:context="com.spydertrap.occexample.MainActivity"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">

    <android.support.constraint.Guideline
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/guideline2"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="206dp" />

    <android.support.v7.widget.CardView
        android:id="@+id/cardView2"
        android:layout_height="150dp"
        android:layout_width="0dp"
        app:layout_constraintRight_toLeftOf="@+id/guideline2"
        android:layout_marginRight="8dp"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/cardView"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:layout_marginBottom="50dp"
            app:srcCompat="@drawable/resource" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="116dp"
            android:layout_marginLeft="10dp"
            android:textAppearance="@style/CardSubTitle"
            android:text="Resource Center" />
    </android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>

and the activity is pretty simple:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setTitle("Dashboard");
    }
}

This title needs to be centered

any help will be appreciated!!

Body:
Override the setTitle(CharSequence title) method of the Activity.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setTitle("Dashboard");

}

@Override
public void setTitle(CharSequence title) {
    super.setTitle(title);

    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER_HORIZONTAL);
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
}


问:
Java Scanners: How to keep the same line after an input
I have a small code segment that I do not know how to fix.  This is it:

```<code>System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
</code>```

The output is: y=3 on one line, and x+4 on the next.  I would like them to be on the same line.  How do I do this?

答:
I'm not sure what you  want to do there but maybe you just need to use one System.out.print? at the bottom of your code with example:</p>

```<code>System.out.print("y= %d  x+%d", m , b);
</code>```

Body:
I have a small code segment that I do not know how to fix.  This is it:

System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();

The output is: y=3 on one line, and x+4 on the next.  I would like them to be on the same line.  How do I do this?

Body:
I'm not sure what you  want to do there but maybe you just need to use one System.out.print? at the bottom of your code with example:

System.out.print("y= %d  x+%d", m , b);


问:
HttpClient is modifying my original request to change domains
I have some code that is making a Server2Server call using an HttpClient.  Here is some quick code

Code to make a request

```<code>    private HttpRequestMessage GetRequest(Uri uri, NameValueCollection headers)
    {
        var method = HttpMethod.Get;
        var request = new HttpRequestMessage(method, uri);
        foreach (string v in headers)
        {
            var success = request.Headers.TryAddWithoutValidation(v, headers[v]);

            if (!success)
            {
                // log something ( no logs are appearing )
            }
        }
        return request;
    }
</code>```

Code to make the request

```<code>private void AsyncCallUrl(Uri url, NameValueCollection headers)
{
    object result1 = null;
    var handler = new HttpClientHandler() { AllowAutoRedirect = false };
    using (HttpClient client = new HttpClient(handler))
    {
        var request = GetRequest(url, headers);
        using (HttpResponseMessage response = client.SendAsync(request).Result) // when this line is executed the request object's domain is changed to something else
        {
            using (HttpContent content = response.Content)
            {
                result1 = content.ReadAsStringAsync().Result;
            }
        }
    }
</code>```

I've verified that the request object is created appropriately with the proper domain. I've also verified that the network traffic is going to the wrong domain, even the request object shows the new bad domain.  What I don't is why this is happening.  I've even set the AllowAutoRedirect to false

NOTE: As a note I notice that if I use GetAsync instead of SendAsync the domain change doesn't happen.  However this is not an ideal solution as in order to add headers I would need to add them to the HttpClient itself and this code lives on an IIS server and I don't want to make a new client for every request

答:
So, with SendAsync the value of the Host header of the request is determined by the uri parameter... However it is possible to override the Host header through the Headers property of the request.

It's highly likely that the NameValueCollection headers that you are blindly injecting into the request's headers contains an entry for Host which is different to that which you supplied in the Uri.

As an aside, this behaviour can be useful, if (for instance) you were to discover that the DNS performance of HttpWebRequest (the business end of HttpClient on Windows) is sub-standard. I've bypassed .Net/Windows DNS by using a third party library to look up the IP of the host, rewriting the Uri to use the IP address in place of the host name, then setting the Host header on the outgoing request back to the original host name.

Body:
I have some code that is making a Server2Server call using an HttpClient.  Here is some quick code

Code to make a request

    private HttpRequestMessage GetRequest(Uri uri, NameValueCollection headers)
    {
        var method = HttpMethod.Get;
        var request = new HttpRequestMessage(method, uri);
        foreach (string v in headers)
        {
            var success = request.Headers.TryAddWithoutValidation(v, headers[v]);

            if (!success)
            {
                // log something ( no logs are appearing )
            }
        }
        return request;
    }

Code to make the request

private void AsyncCallUrl(Uri url, NameValueCollection headers)
{
    object result1 = null;
    var handler = new HttpClientHandler() { AllowAutoRedirect = false };
    using (HttpClient client = new HttpClient(handler))
    {
        var request = GetRequest(url, headers);
        using (HttpResponseMessage response = client.SendAsync(request).Result) // when this line is executed the request object's domain is changed to something else
        {
            using (HttpContent content = response.Content)
            {
                result1 = content.ReadAsStringAsync().Result;
            }
        }
    }

I've verified that the request object is created appropriately with the proper domain. I've also verified that the network traffic is going to the wrong domain, even the request object shows the new bad domain.  What I don't is why this is happening.  I've even set the AllowAutoRedirect to false

NOTE: As a note I notice that if I use GetAsync instead of SendAsync the domain change doesn't happen.  However this is not an ideal solution as in order to add headers I would need to add them to the HttpClient itself and this code lives on an IIS server and I don't want to make a new client for every request


问:
Laravel 5.4 Trying to get property of non-object
I have a problem with a relationship hasMany. This is my code:

In the model Document, I have:

```<code>public function aliases()
{
    return $this->hasMany('App\Models\Alias');
}
</code>```

In model Alias:

```<code>public function document()
{
    return $this->belongsTo('App\Models\Document');
}
</code>```

In the Controller, I’ve made a foreach to avoid having a collection:

```<code>$data['aliases'] = [];
$aliases = Alias::where('path', $directory)->get();
if(null != $aliases){
    foreach($aliases as $alias){
        $data['aliases'][] = $alias;
    }
}
</code>```

In the view:

```<code>if(isset($data['aliases']))
    @foreach($data['aliases'] as $alias)
        <tr>
            <td>{!! HTML::image('images/panel/icons/alias.svg', '', array('class' => 'icons_type')) !!}</td>
            <td><a href="{{ route('documents.show', '', $alias->doc_id) }}">{!! $alias->document->name !!}</a></td>
            <td>{{--{!! date('d-m-Y', strtotime($alias->document->date)) !!}--}}</td>
            <td>{{--{!! $alias->document->class !!}--}}</td>
        </tr>
    @endforeach
@endif
</code>```

The problem is when I try to get the property name or another property trough of relationship document() in the view:

```<code>$alias->document->name
</code>```

答:
Your data array code in the controller does not solve anything? Why would you want to convert a collection (which implements the ArrayAccess interface) to an array?

And by setting:

```<code>$data['aliases'] = [];
</code>```

This statement will always be true:

```<code>if(isset($data['aliases']))
</code>```

The issue you have is that you are requesting the name from a non-object, there is no document for the alias there.

I see that you use $alias->doc_id in the view, I assume that this is the Document model foreign key on the Alias model, doc_id is not according to the naming convention and will not auto resolve. If not defined, Laravel expects it to be document_id. You use doc_id as the foreign key, which is not according the naming conventions, so you have to define it.

Try this:

```<code>public function aliases()
{
    return $this->hasMany('App\Models\Alias', 'doc_id');
}

public function document()
{
    return $this->belongsTo('App\Models\Document', 'doc_id');
}
</code>```

For more info see: Laravel - One-to-many relationships

Also checkout eager loading (saves queries) and if an alias can exist without a document, you should check if the document exists in your foreach before you try to access properties of the document.

Body:
I have a problem with a relationship hasMany. This is my code:

In the model Document, I have:

public function aliases()
{
    return $this->hasMany('App\Models\Alias');
}

In model Alias:

public function document()
{
    return $this->belongsTo('App\Models\Document');
}

In the Controller, I’ve made a foreach to avoid having a collection:

$data['aliases'] = [];
$aliases = Alias::where('path', $directory)->get();
if(null != $aliases){
    foreach($aliases as $alias){
        $data['aliases'][] = $alias;
    }
}

In the view:

if(isset($data['aliases']))
    @foreach($data['aliases'] as $alias)

            {!! HTML::image('images/panel/icons/alias.svg', '', array('class' => 'icons_type')) !!}
            doc_id) }}">{!! $alias->document->name !!}
            {{--{!! date('d-m-Y', strtotime($alias->document->date)) !!}--}}
            {{--{!! $alias->document->class !!}--}}

    @endforeach
@endif

The problem is when I try to get the property name or another property trough of relationship document() in the view:

$alias->document->name

Body:
Your data array code in the controller does not solve anything? Why would you want to convert a collection (which implements the ArrayAccess interface) to an array?

And by setting:

$data['aliases'] = [];

This statement will always be true:

if(isset($data['aliases']))

The issue you have is that you are requesting the name from a non-object, there is no document for the alias there.

I see that you use $alias->doc_id in the view, I assume that this is the Document model foreign key on the Alias model, doc_id is not according to the naming convention and will not auto resolve. If not defined, Laravel expects it to be document_id. You use doc_id as the foreign key, which is not according the naming conventions, so you have to define it.

Try this:

public function aliases()
{
    return $this->hasMany('App\Models\Alias', 'doc_id');
}

public function document()
{
    return $this->belongsTo('App\Models\Document', 'doc_id');
}

For more info see: Laravel - One-to-many relationships

Also checkout eager loading (saves queries) and if an alias can exist without a document, you should check if the document exists in your foreach before you try to access properties of the document.


问:
Getting the Hash in MD5 Powershell
I am trying to make a script that can get the hash MD5 of Files and Directories that I get with the function ChildItem. My Script at the moment is the following. Why is the part of the Hash not working?</p>

```<code> $UserInput = Read-Host

 Get-ChildItem -Path $UserInput -Recurse

function md5hash($UserInput)
{
    $fullPath = Resolve-Path $UserInput
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
    [System.BitConverter]::ToString($md5.ComputeHash($file))
    $file.Dispose()
}
</code>```

答:
As a one-liner:</p>

```<code>Get-ChildItem -Path C:\Temp -Recurse -File | Get-Filehash -Algorithm MD5
</code>```

Title: Getting the Hash in MD5 Powershell

Body:
I am trying to make a script that can get the hash MD5 of Files and Directories that I get with the function ChildItem. My Script at the moment is the following. Why is the part of the Hash not working?

 $UserInput = Read-Host

 Get-ChildItem -Path $UserInput -Recurse

function md5hash($UserInput)
{
    $fullPath = Resolve-Path $UserInput
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
    [System.BitConverter]::ToString($md5.ComputeHash($file))
    $file.Dispose()
}

Body:
As a one-liner:

Get-ChildItem -Path C:\Temp -Recurse -File | Get-Filehash -Algorithm MD5


问:
Google Cloud App Engine Cron can't execute python script
I need to publish Pub/Sub event in my infrastructure. So, I wrote the background Google Cloud Function that subscribed on topic scan-dead-locks. It will read database and release all crashed not closed locks on documents. This function should be executed periodically every 20 minuets, for example. As I investigated, there is no way to trigger Pub/Sub event directly by App Engine's Cron service. I wrote a python script that should do that (used App Engine's examples), but, the final issue left is that libraries at runtime where not found. So, I've got this error.

And this files.

app.yaml

```<code>runtime: python27
threadsafe: no

handlers:
  - url: /trigger-scan-dead-locks
    script: trigger-scan-dead-locks.py
    login: admin
</code>```

appengine_config.py

```<code>from google.appengine.ext import vendor

vendor.add('lib')
</code>```

cron.yaml

```<code>cron:
- description: scan for dead locks and release locks
  url: /trigger-scan-dead-locks
  schedule: every 20 mins
</code>```

trigger-scan-dead-locks.py

```<code>from apiclient import discovery

pubsub = discovery.build('pubsub', 'v1')

pubsub.projects().topics().publish(topic="scan-dead-locks").execute()
</code>```

Example was taken from here https://github.com/GoogleCloudPlatform/reliable-task-scheduling-compute-engine-sample.
Maybe the general question that might solve the issue, how the libraries managed here (I already read documentation, but it was not really helpful)? And also I found another examples with from google.cloud import pubsub library declaration, but it didn't worked because of absent library as well.

答:
Sounds like you don't have googleapiclient in your lib directory.

Couple of things:

1) try from googleapiclient import discovery <- newer version

2) $ cd to your project directory, then $ pip install -t lib google-api-python-client

Body:
I need to publish Pub/Sub event in my infrastructure. So, I wrote the background Google Cloud Function that subscribed on topic scan-dead-locks. It will read database and release all crashed not closed locks on documents. This function should be executed periodically every 20 minuets, for example. As I investigated, there is no way to trigger Pub/Sub event directly by App Engine's Cron service. I wrote a python script that should do that (used App Engine's examples), but, the final issue left is that libraries at runtime where not found. So, I've got this error.

And this files.

app.yaml

runtime: python27
threadsafe: no

handlers:
  - url: /trigger-scan-dead-locks
    script: trigger-scan-dead-locks.py
    login: admin

appengine_config.py

from google.appengine.ext import vendor

vendor.add('lib')

cron.yaml

cron:
- description: scan for dead locks and release locks
  url: /trigger-scan-dead-locks
  schedule: every 20 mins

trigger-scan-dead-locks.py

from apiclient import discovery

pubsub = discovery.build('pubsub', 'v1')

pubsub.projects().topics().publish(topic="scan-dead-locks").execute()

Example was taken from here https://github.com/GoogleCloudPlatform/reliable-task-scheduling-compute-engine-sample.
Maybe the general question that might solve the issue, how the libraries managed here (I already read documentation, but it was not really helpful)? And also I found another examples with from google.cloud import pubsub library declaration, but it didn't worked because of absent library as well.


问:
Code sniffer for for converting snake_case to camelCase
I need a code sniffer for converting all the variables in all of my PHP file from snake_case to camelCase.

I don't need the functions which do it in php on a string, I want to convert the variables in my PHP files to camelCase.

I appreciate you in advanced.

答:
I found a way to do it.
I integrate the code for cakePHP (There is the file with ctp extension and the variable passed to view by set function).

Save the below code as tocamelcase.php

```<code>php tocamelcase.php the/path/of/your/app
</code>```

file content:

```<code><?php
function snakeToCamel($val) {
    preg_match('#^_*#', $val, $underscores);
    $underscores = current($underscores);
    $camel = str_replace('||||', '', ucwords(str_replace('_', '||||', $val), '||||'));
    $camel = strtolower(substr($camel, 0, 1)).substr($camel, 1);

    return $underscores.$camel;
}

function convert($str) {
    global $j;
    $name = '/(\$[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(->[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(::[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\sfunction\s+[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\$this->set\(\'[a-zA-Z0-9]+_[a-zA-Z0-9_]+\'\,)|'.
            '(\$this->set\(\"[a-zA-Z0-9]+_[a-zA-Z0-9_]+\"\,)'.
            '/i';
    $str = preg_replace_callback($name, function($matches){
        return snakeToCamel($matches[0]);
    },$str);
    return $str;
}

$path = $argv[1];
$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$i=1;
foreach($Iterator as $file){
    if(substr($file,-4) !== '.php' && substr($file,-4) !== '.ctp')
        continue;
    echo($i.": ".$file."\n");
    $i++;
    $out = convert(file_get_contents($file));
    file_put_contents($file, $out);
}
</code>```

Body:
I found a way to do it.
I integrate the code for cakePHP (There is the file with ctp extension and the variable passed to view by set function).

Save the below code as tocamelcase.php

php tocamelcase.php the/path/of/your/app

file content:

<?php
function snakeToCamel($val) {
    preg_match('#^_*#', $val, $underscores);
    $underscores = current($underscores);
    $camel = str_replace('||||', '', ucwords(str_replace('_', '||||', $val), '||||'));
    $camel = strtolower(substr($camel, 0, 1)).substr($camel, 1);

    return $underscores.$camel;
}

function convert($str) {
    global $j;
    $name = '/(\$[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(->[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(::[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\sfunction\s+[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\$this->set\(\'[a-zA-Z0-9]+_[a-zA-Z0-9_]+\'\,)|'.
            '(\$this->set\(\"[a-zA-Z0-9]+_[a-zA-Z0-9_]+\"\,)'.
            '/i';
    $str = preg_replace_callback($name, function($matches){
        return snakeToCamel($matches[0]);
    },$str);
    return $str;
}

$path = $argv[1];
$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$i=1;
foreach($Iterator as $file){
    if(substr($file,-4) !== '.php' && substr($file,-4) !== '.ctp')
        continue;
    echo($i.": ".$file."\n");
    $i++;
    $out = convert(file_get_contents($file));
    file_put_contents($file, $out);
}


问:
Noty.js removing oldest notification on new notification
I am using this script http://ned.im/noty/
for showing notifications

```<code>    var n = noty({
        text: message,
        type: type,
        dismissQueue: true,
        force: true,
        layout : "bottomLeft",
        theme: 'newTheme',
        maxVisible : 5
    });
</code>```

So this is the current config, it has queued 5 items. The problem is that I can't figure out how to remove the first notification on showing new one, when a button is clicked.
Any ideas are welcome.

答:
Was looking for this and ended up here; current version for the time being (3.1.0) allows you to use the killer option:

```<code>noty({
    text: 'I have just killed it',
    type: 'success',
    killer : true
})
</code>```

Looks like it "kills" all previous notifications in the queue, making "this one" the only one displayed.

Body:
I am using this script http://ned.im/noty/
for showing notifications

    var n = noty({
        text: message,
        type: type,
        dismissQueue: true,
        force: true,
        layout : "bottomLeft",
        theme: 'newTheme',
        maxVisible : 5
    });

So this is the current config, it has queued 5 items. The problem is that I can't figure out how to remove the first notification on showing new one, when a button is clicked.
Any ideas are welcome.

Body:
Was looking for this and ended up here; current version for the time being (3.1.0) allows you to use the killer option:

noty({
    text: 'I have just killed it',
    type: 'success',
    killer : true
})

Looks like it "kills" all previous notifications in the queue, making "this one" the only one displayed.


问:
Could not find com.android.support:appcompat-v7:25.3.1 in Android studio?
I am trying to add floating search view library to my android app. After adding the dependencies I got:

```<code>Error:Could not find com.android.support:appcompat-v7:25.3.1.
Required by:
project :app

Please install the Android Support Repository from the Android SDK Manager.
</code>```

So, I have added following dependencies to my module Gradle file:

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:percent:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-v13:25.3.1'
</code>```

After sync Gradle file, I got the same error. Then I clean the project and even https://github.com/arimorty/floatingsearchview the Invalidate cache to the project but the same response.

My Android Studio is updated and API level 25 is installed.

What am I doing wrong here?

Gradle file

(Editing Gradle file after a suggestion)

```<code>android {
  compileSdkVersion 25
  buildToolsVersion '25.0.3'

defaultConfig {
    applicationId "com.app.seeker"
    minSdkVersion 21
    targetSdkVersion 25
    versionCode 1
    multiDexEnabled true
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
</code>```

Any help would be appreciable

答:
In order to use compile 'com.android.support:appcompat-v7:25.3.1' your compileSdkVersion must be 25, so update it.

In the same way, consider to upgrade your buildToolsVersion to version 25.0.3

Body:
I am trying to add floating search view library to my android app. After adding the dependencies I got:

Error:Could not find com.android.support:appcompat-v7:25.3.1.
Required by:
project :app

Please install the Android Support Repository from the Android SDK Manager.

So, I have added following dependencies to my module Gradle file:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:percent:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:support-v13:25.3.1'

After sync Gradle file, I got the same error. Then I clean the project and even https://github.com/arimorty/floatingsearchview the Invalidate cache to the project but the same response.

My Android Studio is updated and API level 25 is installed.

What am I doing wrong here?

Gradle file

(Editing Gradle file after a suggestion)

android {
  compileSdkVersion 25
  buildToolsVersion '25.0.3'

defaultConfig {
    applicationId "com.app.seeker"
    minSdkVersion 21
    targetSdkVersion 25
    versionCode 1
    multiDexEnabled true
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

Any help would be appreciable