问:
How to call another intent without prompting to user in Lex?
Is it possible to trigger intent-B from the lambda function of intent-A without prompting to user?

Suppose user typed something and an intent-A is fired, after some processing I want to trigger some other intent i.e intent-B.

User can also directly trigger intent-B through specific utterances.
Any help is appreciated.

答:
I ended up doing below to call intent-B from intent-A without prompting anything to user:

give access to invoke lambda functions to your calling lambda function i.e lambda function of intent-A

get the name of backend lambda function of intent-B

call that lambda function with all the inputs using boto3

response will be in 'Payload' key of response object

get the response using read() method

get actual output in ['dialogAction']['message']['content']

return using default close() method

import boto3

```<code>client = boto3.client('lambda')
data = {'messageVersion': '1.0', 'invocationSource': 'FulfillmentCodeHook', 'userId': '###',
        'sessionAttributes': {}, 'requestAttributes': None,
        'bot': {'name': '###', 'alias': '$LATEST', 'version': '$LATEST'},
        'outputDialogMode': 'Text',
        'currentIntent': {'name': '###', 'slots': {'###': '###'},
        'slotDetails': {'###': {'resolutions': [], 'originalValue': '###'}},
        'confirmationStatus': 'None'},
        'inputTranscript': '###'}
response = client.invoke(
    FunctionName='{intent-B lambda function}',
    InvocationType='RequestResponse',
    Payload=json.dumps(data)
)
output = json.loads(response['Payload'].read())['dialogAction']['message']['content']
</code>```

Body:
I ended up doing below to call intent-B from intent-A without prompting anything to user:

give access to invoke lambda functions to your calling lambda function i.e lambda function of intent-A

get the name of backend lambda function of intent-B

call that lambda function with all the inputs using boto3

response will be in 'Payload' key of response object

get the response using read() method

get actual output in ['dialogAction']['message']['content']

return using default close() method

import boto3

client = boto3.client('lambda')
data = {'messageVersion': '1.0', 'invocationSource': 'FulfillmentCodeHook', 'userId': '###',
        'sessionAttributes': {}, 'requestAttributes': None,
        'bot': {'name': '###', 'alias': '$LATEST', 'version': '$LATEST'},
        'outputDialogMode': 'Text',
        'currentIntent': {'name': '###', 'slots': {'###': '###'},
        'slotDetails': {'###': {'resolutions': [], 'originalValue': '###'}},
        'confirmationStatus': 'None'},
        'inputTranscript': '###'}
response = client.invoke(
    FunctionName='{intent-B lambda function}',
    InvocationType='RequestResponse',
    Payload=json.dumps(data)
)
output = json.loads(response['Payload'].read())['dialogAction']['message']['content']


来源: stackexchange

问:
Qt Creator Error
Launching debugging for a project and then,

```<code>Running build steps for project Text_Editor...
Starting: "c:/qt/2010.05/qt/bin/qmake.exe" C:/Qt/2010.05/Text_Editor/Text_Editor.pro -r -spec win32-g++
The process "c:/qt/2010.05/qt/bin/qmake.exe" exited normally.
Starting: "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" -w
mingw32-make: Entering directory `C:/Qt/2010.05/Text_Editor-build-desktop'

C:/Qt/2010.05/mingw/bin/mingw32-make -f Makefile.Debug

mingw32-make[1]: Entering directory `C:/Qt/2010.05/Text_Editor-build-desktop'

g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_GUI_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN -I"..\qt\include\QtCore" -I"..\qt\include\QtGui" -I"..\qt\include" -I"..\qt\include\ActiveQt" -I"debug" -I"..\Text_Editor" -I"." -I"..\qt\mkspecs\win32-g++" -o debug\main.o ..\Text_Editor\main.cpp

mingw32-make[1]: Leaving directory `C:/Qt/2010.05/Text_Editor-build-desktop'

mingw32-make: Leaving directory `C:/Qt/2010.05/Text_Editor-build-desktop'

g++: ..\Text_Editor\main.cpp: No such file or directory

g++: no input files

mingw32-make[1]: *** [debug/main.o] Error 1

mingw32-make: *** [debug] Error 2

The process "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" exited with code %2.
Error while building project Text_Editor (target: Desktop)
When executing build step 'Make'
</code>```

I have no clue on that. I just installed it, created a new project and got that error instantly.

答:
For reason or another it is not able to find your main.cpp (g++: ..\Text_Editor\main.cpp: No such file or directory). Basically that path should be ok if you have shadow build toggled on.

Location where the main.cpp is tried to find is:

C:/Qt/2010.05/Text_Editor/main.cpp

Double check that this is proper location (notice also case sensitivity to be sure)

you can try toggling off the shadow build from project -> check off shadow build. And also you should check that Text_Editor.pro contains properly the main.cpp.

Edit: It might be also wise to create that project outside the Qt binary folder, to some other more logical folder.

ContentLicense: CC BY-SA 2.5

Title: Qt Creator Error

Body:
Launching debugging for a project and then,

Running build steps for project Text_Editor...
Starting: "c:/qt/2010.05/qt/bin/qmake.exe" C:/Qt/2010.05/Text_Editor/Text_Editor.pro -r -spec win32-g++
The process "c:/qt/2010.05/qt/bin/qmake.exe" exited normally.
Starting: "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" -w
mingw32-make: Entering directory `C:/Qt/2010.05/Text_Editor-build-desktop'

C:/Qt/2010.05/mingw/bin/mingw32-make -f Makefile.Debug

mingw32-make[1]: Entering directory `C:/Qt/2010.05/Text_Editor-build-desktop'

g++ -c -g -frtti -fexceptions -mthreads -Wall -DUNICODE -DQT_LARGEFILE_SUPPORT -DQT_DLL -DQT_GUI_LIB -DQT_CORE_LIB -DQT_THREAD_SUPPORT -DQT_NEEDS_QMAIN -I"..\qt\include\QtCore" -I"..\qt\include\QtGui" -I"..\qt\include" -I"..\qt\include\ActiveQt" -I"debug" -I"..\Text_Editor" -I"." -I"..\qt\mkspecs\win32-g++" -o debug\main.o ..\Text_Editor\main.cpp

mingw32-make[1]: Leaving directory `C:/Qt/2010.05/Text_Editor-build-desktop'

mingw32-make: Leaving directory `C:/Qt/2010.05/Text_Editor-build-desktop'

g++: ..\Text_Editor\main.cpp: No such file or directory

g++: no input files

mingw32-make[1]: *** [debug/main.o] Error 1

mingw32-make: *** [debug] Error 2

The process "C:/Qt/2010.05/mingw/bin/mingw32-make.exe" exited with code %2.
Error while building project Text_Editor (target: Desktop)
When executing build step 'Make'

I have no clue on that. I just installed it, created a new project and got that error instantly.


问:
How to add data to a Arraylist from a diffrent class
I have seen all the other questions to his topic but I didnt realy get much from it.Just started learning java so pls try to make  the explanation for me as simple as you can.

How do I add to my Arraylist "Fish" anything at all? I coudlnt even add something to it in the same class(line3 class question)... but I need to know how to add it in different a class.(I tried it in the end of class question 2 but it didnt work too)

```<code>import java.util.ArrayList;

public class question {

    private String name;

    public ArrayList<String> Fish = new ArrayList<>();

    Fish.add(name); // <--- this for some reason doesnt work the point is red underlined as well as the ")"

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getFish() {
        return Fish;
    }
}
</code>```

second class

```<code>public class question2 {

    public String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    // First try : question.getFish().add(nam1);
    // Second try   question.Fish.add(name1);
    //how do I add the name1 into my ArrayList "Fish".How can I transport my ArrayList from question1 to question2?
}
</code>```

Any help will be appreciated, Thank you.

答:
With a little bit of research i found this:
http://www.guj.com.br/t/chamar-instancia-em-outra-classe/349765/6

Check the awnser and run the code by debugging it, this way you can see step by step of what is going right or wrong.

Hope it helps you, if don't, later i can make a example for you.

PS: If your first class has just a constructor, you don't need to create the array there, you can just call the constructor on your second class and create the array there.

ContentLicense: CC BY-SA 3.0

Body:
I have seen all the other questions to his topic but I didnt realy get much from it.Just started learning java so pls try to make  the explanation for me as simple as you can.

How do I add to my Arraylist "Fish" anything at all? I coudlnt even add something to it in the same class(line3 class question)... but I need to know how to add it in different a class.(I tried it in the end of class question 2 but it didnt work too)

import java.util.ArrayList;

public class question {

    private String name;

    public ArrayList<String> Fish = new ArrayList<>();

    Fish.add(name); // <--- this for some reason doesnt work the point is red underlined as well as the ")"

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getFish() {
        return Fish;
    }
}

second class

public class question2 {

    public String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    // First try : question.getFish().add(nam1);
    // Second try   question.Fish.add(name1);
    //how do I add the name1 into my ArrayList "Fish".How can I transport my ArrayList from question1 to question2?
}

Any help will be appreciated, Thank you.


问:
Split All Files In a Folder Based On Row Structure

What I Am Trying to Accomplish

I have a folder with several hundred files, each has the same structure, Here's a sample:

```<code>Start Date  End Date    Code1   Code2   Vendor Identifier   Quantity    V1_1    V1_2    Currency    V1_3    ID  V1_4    V2  V3  V4  TypeID  OtherID Country_of_Sale V5  V6  V7  V8
11/27/16    12/31/16        character_value character_value 2           USD     numeric_value   character_value character_value character_value     character_value     AU
11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
row count   3558
Country_of_Sale TotalA  TotalB  TotalC  TotalD  spu TotalE  V2_1    V2_2    TotalF  V2_3    V2_4
AR  0   2782223 2782223 7763.1  0.002790251 22  0.05        0.05    4626.17 5023
US  0   2497603034  2497603034  2958948.67  0.001184715 111374  109.33      109.33  1763291.86  1897441
DO  0   529132  529132  632.54  0.001195429 5   0.01        0.01    376.94  403
EC  0   794440  794440  1669.63 0.002101644 14  0.02        0.02    994.96  1087
BR  0   24397952    24397952    57932.77    0.002374493 217 0.43        0.43    34523.2 37225
Ctotal  109.84
Stotal  5680.38
Total   5790.22
</code>```

As you can see, each file should really be two separate files; one with header row

```<code>Start Date  End Date    Code1   Code2   Vendor Identifier   Quantity    V1_1    V1_2    Currency    V1_3    ID  V1_4    V2  V3  V4  TypeID  OtherID Country_of_Sale V5  V6  V7  V8
</code>```

and one with header row

```<code>Country_of_Sale TotalA  TotalB  TotalC  TotalD  spu TotalE  V2_1    V2_2    TotalF  V2_3    V2_4
</code>```

The line that separates these two always has $1 == row count (/^row count/?)

I want two outcome files, one for each header row described above. But there are, again, several hundred files -- all of them in a single directory --to pull those from:

The Problem

I know my solution lies in awk. I don't know awk. I've researched for several hours, and I have figured out how to solve different parts of this, but just can't figure out how to pull it all together.

What I ultimately need is two tables that I can join (in SQL) on Country_of_Sale.

Expected Result

Simple:

file1:

```<code>Start Date  End Date    UPC ISRC/ISBN   Vendor Identifier   Quantity    V1_1    V1_2    Currency    V1_3    ID  V1_4    V2  V3  V4  TypeID  OtherID Country_of_Sale V5  V6  V7  V8
    11/27/16    12/31/16        character_value character_value 2           USD     numeric_value   character_value character_value character_value     character_value     AU
    11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
    11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
</code>```

file2

```<code>Country_of_Sale TotalA  TotalB  TotalC  TotalD  spu TotalE  V2_1    V2_2    TotalF  V2_3    V2_4
    AR  0   2782223 2782223 7763.1  0.002790251 22  0.05        0.05    4626.17 5023
    US  0   2497603034  2497603034  2958948.67  0.001184715 111374  109.33      109.33  1763291.86  1897441
    DO  0   529132  529132  632.54  0.001195429 5   0.01        0.01    376.94  403
    EC  0   794440  794440  1669.63 0.002101644 14  0.02        0.02    994.96  1087
    BR  0   24397952    24397952    57932.77    0.002374493 217 0.43        0.43    34523.2 37225
</code>```

What I've Tried (By Request :))

I started with this:

```<code>gawk '
  /^row count/ {nextfile}
  NR == 1 {$0 = "Filename" OFS $0; print}
  FNR > 1 {$0 =  FILENAME OFS $0; print}
' OFS='\t' dir/to/raw/files/*.txt > dir/to/munged/file/file1.txt
</code>```

and

```<code>gawk 'FNR==1,/^Country_Of_Sale/{next} /^CTotal/ {nextfile}
{ $0 =  FILENAME OFS $0; print }' OFS='\t' dir/to/raw/files/*.txt > dir/to/munged/file/file2.tsv
</code>```

Which kinda works, but I want to do it in one line.

So I messed around with various permutations of this:

```<code>awk -F, '{print > $1}' file1
</code>```

But to be perfectly honest, I don't really get it. I'm more comfy with already-wrangled data.

I hope I've given enough here. I certainly don't want to exploit the resource.

答:
Assuming your files have the .txt extension and you want to name the generated files with the .txt.1 or .txt.2 extension, you could try something like:

```<code>awk 'BEGINFILE{f=FILENAME".1"} /^row count/{f=FILENAME".2";next} /^Ctotal/{nextfile} {print>f}' *.txt
</code>```

Explanations:

At the beginning of the processing of each input file, variable f is set to FILENAME.1 where FILENAME (awk buit-in variable) is the name of the currently processes file.

When the current line of the current input file starts with row count, variable f is set to FILENAME.2 and the line is skipped.

When the current line of the current input file starts with Ctotal the rest of the file is skipped.

Variable f is used as the output file name for all non-skipped lines.

Body:
What I Am Trying to Accomplish

I have a folder with several hundred files, each has the same structure, Here's a sample:

Start Date  End Date    Code1   Code2   Vendor Identifier   Quantity    V1_1    V1_2    Currency    V1_3    ID  V1_4    V2  V3  V4  TypeID  OtherID Country_of_Sale V5  V6  V7  V8
11/27/16    12/31/16        character_value character_value 2           USD     numeric_value   character_value character_value character_value     character_value     AU
11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
row count   3558
Country_of_Sale TotalA  TotalB  TotalC  TotalD  spu TotalE  V2_1    V2_2    TotalF  V2_3    V2_4
AR  0   2782223 2782223 7763.1  0.002790251 22  0.05        0.05    4626.17 5023
US  0   2497603034  2497603034  2958948.67  0.001184715 111374  109.33      109.33  1763291.86  1897441
DO  0   529132  529132  632.54  0.001195429 5   0.01        0.01    376.94  403
EC  0   794440  794440  1669.63 0.002101644 14  0.02        0.02    994.96  1087
BR  0   24397952    24397952    57932.77    0.002374493 217 0.43        0.43    34523.2 37225
Ctotal  109.84
Stotal  5680.38
Total   5790.22

As you can see, each file should really be two separate files; one with header row

Start Date  End Date    Code1   Code2   Vendor Identifier   Quantity    V1_1    V1_2    Currency    V1_3    ID  V1_4    V2  V3  V4  TypeID  OtherID Country_of_Sale V5  V6  V7  V8

and one with header row

Country_of_Sale TotalA  TotalB  TotalC  TotalD  spu TotalE  V2_1    V2_2    TotalF  V2_3    V2_4

The line that separates these two always has $1 == row count (/^row count/?)

I want two outcome files, one for each header row described above. But there are, again, several hundred files -- all of them in a single directory --to pull those from:

The Problem

I know my solution lies in awk. I don't know awk. I've researched for several hours, and I have figured out how to solve different parts of this, but just can't figure out how to pull it all together.

What I ultimately need is two tables that I can join (in SQL) on Country_of_Sale.

Expected Result

Simple:

file1:

Start Date  End Date    UPC ISRC/ISBN   Vendor Identifier   Quantity    V1_1    V1_2    Currency    V1_3    ID  V1_4    V2  V3  V4  TypeID  OtherID Country_of_Sale V5  V6  V7  V8
    11/27/16    12/31/16        character_value character_value 2           USD     numeric_value   character_value character_value character_value     character_value     AU
    11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU
    11/27/16    12/31/16        character_value character_value 1           USD     numeric_value   character_value character_value character_value     character_value     AU

file2

Country_of_Sale TotalA  TotalB  TotalC  TotalD  spu TotalE  V2_1    V2_2    TotalF  V2_3    V2_4
    AR  0   2782223 2782223 7763.1  0.002790251 22  0.05        0.05    4626.17 5023
    US  0   2497603034  2497603034  2958948.67  0.001184715 111374  109.33      109.33  1763291.86  1897441
    DO  0   529132  529132  632.54  0.001195429 5   0.01        0.01    376.94  403
    EC  0   794440  794440  1669.63 0.002101644 14  0.02        0.02    994.96  1087
    BR  0   24397952    24397952    57932.77    0.002374493 217 0.43        0.43    34523.2 37225

What I've Tried (By Request :))

I started with this:

gawk '
  /^row count/ {nextfile}
  NR == 1 {$0 = "Filename" OFS $0; print}
  FNR > 1 {$0 =  FILENAME OFS $0; print}
' OFS='\t' dir/to/raw/files/*.txt > dir/to/munged/file/file1.txt

and

gawk 'FNR==1,/^Country_Of_Sale/{next} /^CTotal/ {nextfile}
{ $0 =  FILENAME OFS $0; print }' OFS='\t' dir/to/raw/files/*.txt > dir/to/munged/file/file2.tsv

Which kinda works, but I want to do it in one line.

So I messed around with various permutations of this:

awk -F, '{print > $1}' file1

But to be perfectly honest, I don't really get it. I'm more comfy with already-wrangled data.

I hope I've given enough here. I certainly don't want to exploit the resource.

Body:
Assuming your files have the .txt extension and you want to name the generated files with the .txt.1 or .txt.2 extension, you could try something like:

awk 'BEGINFILE{f=FILENAME".1"} /^row count/{f=FILENAME".2";next} /^Ctotal/{nextfile} {print>f}' *.txt

Explanations:

At the beginning of the processing of each input file, variable f is set to FILENAME.1 where FILENAME (awk buit-in variable) is the name of the currently processes file.

When the current line of the current input file starts with row count, variable f is set to FILENAME.2 and the line is skipped.

When the current line of the current input file starts with Ctotal the rest of the file is skipped.

Variable f is used as the output file name for all non-skipped lines.


问:
How things looks a like behind Ajax calls
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:

```<code>$.ajax({
         method: "GET",
         url: "Customers/GetCustomerById",
         data: { customerId: Id }
        })
.done(function (response) {
//Do something here
});
</code>```

I red behind Ajax is XMLHttpRequest object, so does that means when code above is used, something like this is happening "behind the scene" :

```<code>httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
    // Process the server response here.
};
http.open("GET", url+"?"+customerId, true);
</code>```

Is this true?

And is this second approach avoided today? Or it's still being used?
I'm just learning web and I don't know so that's reason why I'm asking..

And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...

Thanks a lot guys and cheers!

答:
I will describe the answer simply in two sections

1. Behind the Scenes of $.ajax()

Yeah basically JQuery uses the native browser API for Ajax Requests. It creates XHR object same as your second code but they used some additional lines of code because JQuery handles not only plain text. (ie. additional JSON and XML Support)

You may see the JQuery source code portion for XHR here to watch more behind the scenes ;)

2. Use of Native browser API

The second example code type is nowadays also using. People use $.ajax() since it makes coding fast and easy also very easy to capture XML and JSON responses.

Hope it helps

Body:
I just started learning Ajax, and most people as I saw working with Ajax (making Get and Post requests) like this:

$.ajax({
         method: "GET",
         url: "Customers/GetCustomerById",
         data: { customerId: Id }
        })
.done(function (response) {
//Do something here
});

I red behind Ajax is XMLHttpRequest object, so does that means when code above is used, something like this is happening "behind the scene" :

httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function someMyFunction(){
    // Process the server response here.
};
http.open("GET", url+"?"+customerId, true);

Is this true?

And is this second approach avoided today? Or it's still being used?
I'm just learning web and I don't know so that's reason why I'm asking..

And I'm wondering also why people are using this "first" approach, maybe they are not but I acctually saw it on many places...

Thanks a lot guys and cheers!


问:
order of gridview itmes to open Activity1 and Activity2
I am working on a project,where i have 4 activities, main activity have Griview I want to open Activity 1  by clicking item 1 and open Activity 2 by clicking item 2
I want to help complete this work.

CustomAdapter.java:

```<code>@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;

    rowView = inflater.inflate(R.layout.sample_gridlayout, null);
    holder.os_text =(TextView) rowView.findViewById(R.id.os_texts);
    holder.os_img =(ImageView) rowView.findViewById(R.id.os_images);

    holder.os_text.setText(result[position]);
    holder.os_img.setImageResource(imageId[position]);

    rowView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_SHORT).show();
        }
    });

    return rowView;
}
</code>```

MainActivity.java:

```<code>public class MainActivity extends Activity {

GridView gridview;

public static String[] osNameList = {
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
};
public static int[] osImages = {
        R.mipmap.android,
        R.mipmap.ios,
        R.mipmap.linux,
        R.mipmap.macos,
        R.mipmap.msdos,
        R.mipmap.symbian,
        R.mipmap.windows10,
        R.mipmap.winxp,};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gridview = (GridView) findViewById(R.id.customgrid);
    gridview.setAdapter(new CustomAdapter(this, osNameList, osImages));
}
</code>```

}

答:
// Implement On Item click listener</p>

```<code>     gridView.setOnItemClickListener(new OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {

            switch(position)
            {
            case 1:
    //Intent to open Avtivity 2
Intent in2 = new Intent(YourActivity.this, Activity2);
startActivity(in2);
            break;

            case 2:
    //Intent to open Avtivity 1
Intent in1 = new Intent(YourActivity.this, Activity1);
startActivity(in1);
                break;
                default:
                    Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
                    }
            }
        });
</code>```

Body:
I am working on a project,where i have 4 activities, main activity have Griview I want to open Activity 1  by clicking item 1 and open Activity 2 by clicking item 2
I want to help complete this work.

CustomAdapter.java:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    Holder holder=new Holder();
    View rowView;

    rowView = inflater.inflate(R.layout.sample_gridlayout, null);
    holder.os_text =(TextView) rowView.findViewById(R.id.os_texts);
    holder.os_img =(ImageView) rowView.findViewById(R.id.os_images);

    holder.os_text.setText(result[position]);
    holder.os_img.setImageResource(imageId[position]);

    rowView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_SHORT).show();
        }
    });

    return rowView;
}

MainActivity.java:

public class MainActivity extends Activity {

GridView gridview;

public static String[] osNameList = {
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
        "Android",
};
public static int[] osImages = {
        R.mipmap.android,
        R.mipmap.ios,
        R.mipmap.linux,
        R.mipmap.macos,
        R.mipmap.msdos,
        R.mipmap.symbian,
        R.mipmap.windows10,
        R.mipmap.winxp,};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gridview = (GridView) findViewById(R.id.customgrid);
    gridview.setAdapter(new CustomAdapter(this, osNameList, osImages));
}

}

Body:
// Implement On Item click listener

     gridView.setOnItemClickListener(new OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> a, View v, int position, long id) {

            switch(position)
            {
            case 1:
    //Intent to open Avtivity 2
Intent in2 = new Intent(YourActivity.this, Activity2);
startActivity(in2);
            break;

            case 2:
    //Intent to open Avtivity 1
Intent in1 = new Intent(YourActivity.this, Activity1);
startActivity(in1);
                break;
                default:
                    Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
                    }
            }
        });


问:
VueJS method json response to selectbox?
I have a VueJS component, now I'm getting from JSON response which I want to export into a html select box.

My VueJS method:

```<code>getTaskList() {
    axios.get('/api/v1/tasklist').then(response => {
        this.taskList = this.data.taskList;
    });
}
</code>```

I found example in VueJS documentation but there is still the problem with method...

How can I export this response into a selectbox, I know how to work with v-for, but I don't know exactly how to initialize this data in HTML (with v-bind, or something like that)?

答:
I don't know what's in the taskList items but you can simply bind those data in option tags :

```<code><select v-model="selectedTask">
  <option v-for="task in taskList" :key="task.id" :value="task.value">{{ task.label }}</option>
</select>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a VueJS component, now I'm getting from JSON response which I want to export into a html select box.

My VueJS method:

getTaskList() {
    axios.get('/api/v1/tasklist').then(response => {
        this.taskList = this.data.taskList;
    });
}

I found example in VueJS documentation but there is still the problem with method...

How can I export this response into a selectbox, I know how to work with v-for, but I don't know exactly how to initialize this data in HTML (with v-bind, or something like that)?

Body:
I don't know what's in the taskList items but you can simply bind those data in option tags :

<select v-model="selectedTask">
  <option v-for="task in taskList" :key="task.id" :value="task.value">{{ task.label }}</option>
</select>


问:
Deprecated node in MULE 3.6.4, 3.5.0 and 3.7.2?
I well know JDBC was deprecated in MULE 3.5.0 & HTTP connector was deprecated from MULE 3.6.4.

But i want known, is it any other nodes are involved in this deprecated list?

As well as i want the deprecated node's list for MULE 3.7.2.

答:
Take a look at the Mule release notes for each version.

For example, the 3.7.0 release notes mentions the following deprecations:

MULE-8260 As ASM 3.3.1 is not fully compliant with Java 8, the class
  in the packages org.mule.util.scan and org.mule.util.scan.annotations
  have been deprecated, however you can use them under Java 7.

MULE-7588      Lifecycle has been fixed:
  - TransientRegistry is deprecated and no longer used by the runtime. SpringRegistry is now the only registry the runtime uses by default.
  AbstractMuleContextTestCase uses the new SimpleRegistry instead.
  - addRegistry() and removeRegistry() methods from the MuleContext have been deprecated. Manually added registries cannot participate of
  dependency injection
  - The org.mule.api.registry.Registry.registerObject(key, Object, metadata) method has been deprecated. The metadata is no longer used.
  - RegistryBroker and RegistryBrokerLifecycleManager classes have been deprecated
  - SimpleRegistryBootstrap is deprecated and is no longer used by the runtime. SpringRegistryBootstrap is used instead
  - PreInjectProcessor, InjectProcessor, ObjectProcessor and all their implementation have been deprecated and are no longer used by the
  runtime. Use a Spring BeanPostProcessor instead

MULE-8411 @deprecated As of 3.7.0, use {@link#toXMLStreamReader(javax.xml.stream.XMLInputFactory, org.mule.api.MuleEvent, Object)} instead.

MULE-8469 NoActionTransformer class inside TCK test folder

MULE-7742 class AsyncMessageProcessorWorker


问:
Matching images from file with Sikuli
I just found about Sikuli when I was looking for a library to find matches of a given image within a larger image (both loaded from files).
By default, Sikuli only supports loading the searched image from file, but relies on a proprietary class Screen to take screenshots to use as base for the search... And I'd like to have the ability to use a image file instead.

Looking for a solution has led me to this question, but the answer is a bit vague when you consider that I have no prior experience with Sikuli and the available documentation is not particularly helpful for my needs.

Does anyone have any examples on how to make a customized implementation of Screen, ScreenRegion, ImageScreen and ImageScreenLocation? Even a link to a more detailed documentation on these classes would be a big help.

All I want is to obtain the coordinates of an image match within another image file, so if there's another library that could help with this task I'd more than happy to learn about it!

答:
With Sikuli, you can check for the presence of an image inside another one.
In this example code, the pictures are loaded from files.
This code tell us if the second picture is a part of the first picture.

```<code>public static void main(String[] argv){
    String img1Path = "/test/img1.png";
    String img2Path = "/test/img2.png";
    if ( findPictureRegion(img1Path, img2Path) == null )
        System.out.println("Picture 2 was not found in picture 1");
    else
        System.out.println("Picture 2 is in picture 1");
}

public static ScreenRegion findPictureRegion(String refPictureName, String targetPictureName2){
    Target target = new ImageTarget(new File(targetPictureName2));
    target.setMinScore(0.5); // Precision of recognization from 0 to 1.
    BufferedImage refPicture = loadPicture(refPictureName);
    ScreenRegion screenRegion = new StaticImageScreenRegion(refPicture);
    return screenRegion.find(target);
}

public static BufferedImage loadPicture(String pictureFullPath){
    try {
        return ImageIO.read(new File(pictureFullPath));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

To use Sikuli package, I added this dependency with Maven :

```<code>    <!-- SIKULI libraries -->
    <dependency>
        <groupId>org.sikuli</groupId>
        <artifactId>sikuli-api</artifactId>
        <version>1.1.0</version>
    </dependency>
</code>```

Title: Matching images from file with Sikuli

Body:
With Sikuli, you can check for the presence of an image inside another one.
In this example code, the pictures are loaded from files.
This code tell us if the second picture is a part of the first picture.

public static void main(String[] argv){
    String img1Path = "/test/img1.png";
    String img2Path = "/test/img2.png";
    if ( findPictureRegion(img1Path, img2Path) == null )
        System.out.println("Picture 2 was not found in picture 1");
    else
        System.out.println("Picture 2 is in picture 1");
}

public static ScreenRegion findPictureRegion(String refPictureName, String targetPictureName2){
    Target target = new ImageTarget(new File(targetPictureName2));
    target.setMinScore(0.5); // Precision of recognization from 0 to 1.
    BufferedImage refPicture = loadPicture(refPictureName);
    ScreenRegion screenRegion = new StaticImageScreenRegion(refPicture);
    return screenRegion.find(target);
}

public static BufferedImage loadPicture(String pictureFullPath){
    try {
        return ImageIO.read(new File(pictureFullPath));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

To use Sikuli package, I added this dependency with Maven :

    <!-- SIKULI libraries -->
    <dependency>
        <groupId>org.sikuli</groupId>
        <artifactId>sikuli-api</artifactId>
        <version>1.1.0</version>
    </dependency>


问:
Speed up split and write out to file in python
I'm curious if there is a faster way to deal with big text files...
I need to read quite a huge TXT file ( around 40MB :-/ ) which contains data separated by ";", remove the first 10 line as they are informative and not the main data, and then output just the first instance from each line so line[0] after split...

My current code does what it needs to, but it takes forever...

```<code>def remove_lines(input, output):
    lines = open(input).readlines()
    # clean the file before use
    open('output', 'w').close()
    # remove first lines and split by ; then output
    for l in lines[10:]:
        l = l.split(';')
        open(output, 'a').write(l[0] + "\n")
</code>```

Its not like I need to do it often, maybe once a week so I can let it crunch as long as I want, but I'm curious if it can be speed up somehow...

答:
If you think 40MB is huge, you haven't seen huge ;) Either way, you don't need to read the whole file in memory, nor you need to split the whole line - it's sufficient just to skip the first n lines while reading and then get the line content up until the first semi-column, something like:

```<code>def remove_lines(input_file, output_file):
    with open(input_file, "r") as f_in, open(output_file, "a") as f_out:
        for i, line in enumerate(f_in):  # read the input line by line and enumerate it
            if i > 9:  # we're not interested in the first 10 lines
                sc_index = line.find(";")  # find the position of the first ; in line
                if sc_index != -1:  # found the first semi-column, get the content up to it
                    f_out.write(line[:sc_index] + "\n")  # write it to the output file
                else:
                    f_out.write(line)  # write the whole line as we couldn't find a ;
</code>```

UPDATE: For the folks who think that str.split("delim", 1) is faster than finding the actual position and manually slicing, here's a simple test:

```<code>import timeit

def func_split(data):
    return data.split(";", 1)[0]

def func_find(data):
    index = data.find(";")
    if index != -1:
        return data[:index]
    return data

test1 = "A quick; brown; fox; with; semi; columns."
test2 = "A quick brown fox without semi columns."

assert func_split(test1) == func_find(test1)
assert func_split(test2) == func_find(test2)

if __name__ == "__main__":
    print("func_split:", timeit.timeit("func_split(test1); func_split(test2)",
                                       "from __main__ import func_split, test1, test2",
                                       number=1000000))
    print("func_find: ", timeit.timeit("func_find(test1); func_find(test2)",
                                       "from __main__ import func_find, test1, test2",
                                      number=1000000))
</code>```

And the results

```CPython 2.7.11 x64 (1000000 loops):
('func_split:', 6.877725868989936)
('func_find: ', 6.228281754820999)

CPython 3.5.1 x64 (100000 loops):
func_split: 0.8343849130147841
func_find:  0.8080772353660183```

YMMV, of course, but in general the latter will always be faster on CPython, and the speed difference will increase with each character added to the string as the str.find() doesn't need to pick up the whole string 'til the end nor needs to create a list to store it.

Body:
I'm curious if there is a faster way to deal with big text files...
I need to read quite a huge TXT file ( around 40MB :-/ ) which contains data separated by ";", remove the first 10 line as they are informative and not the main data, and then output just the first instance from each line so line[0] after split...

My current code does what it needs to, but it takes forever...

def remove_lines(input, output):
    lines = open(input).readlines()
    # clean the file before use
    open('output', 'w').close()
    # remove first lines and split by ; then output
    for l in lines[10:]:
        l = l.split(';')
        open(output, 'a').write(l[0] + "\n")

Its not like I need to do it often, maybe once a week so I can let it crunch as long as I want, but I'm curious if it can be speed up somehow...

Body:
If you think 40MB is huge, you haven't seen huge ;) Either way, you don't need to read the whole file in memory, nor you need to split the whole line - it's sufficient just to skip the first n lines while reading and then get the line content up until the first semi-column, something like:

def remove_lines(input_file, output_file):
    with open(input_file, "r") as f_in, open(output_file, "a") as f_out:
        for i, line in enumerate(f_in):  # read the input line by line and enumerate it
            if i > 9:  # we're not interested in the first 10 lines
                sc_index = line.find(";")  # find the position of the first ; in line
                if sc_index != -1:  # found the first semi-column, get the content up to it
                    f_out.write(line[:sc_index] + "\n")  # write it to the output file
                else:
                    f_out.write(line)  # write the whole line as we couldn't find a ;

UPDATE: For the folks who think that str.split("delim", 1) is faster than finding the actual position and manually slicing, here's a simple test:

import timeit

def func_split(data):
    return data.split(";", 1)[0]

def func_find(data):
    index = data.find(";")
    if index != -1:
        return data[:index]
    return data

test1 = "A quick; brown; fox; with; semi; columns."
test2 = "A quick brown fox without semi columns."

assert func_split(test1) == func_find(test1)
assert func_split(test2) == func_find(test2)

if __name__ == "__main__":
    print("func_split:", timeit.timeit("func_split(test1); func_split(test2)",
                                       "from __main__ import func_split, test1, test2",
                                       number=1000000))
    print("func_find: ", timeit.timeit("func_find(test1); func_find(test2)",
                                       "from __main__ import func_find, test1, test2",
                                      number=1000000))

And the results

CPython 2.7.11 x64 (1000000 loops):
('func_split:', 6.877725868989936)
('func_find: ', 6.228281754820999)

CPython 3.5.1 x64 (100000 loops):
func_split: 0.8343849130147841
func_find:  0.8080772353660183

YMMV, of course, but in general the latter will always be faster on CPython, and the speed difference will increase with each character added to the string as the str.find() doesn't need to pick up the whole string 'til the end nor needs to create a list to store it.


问:
C: How to add a try again function to this asterisk square printing program

I need a program that asks for an integer &prints out an emtpy asterisk square based on the input number. And if the input was invalid then i need it to try and ask again
.
THIS is what i have so far (it already can make a square based on a variable number) i just need to enhence it so it asks again if the user is too dumb to input an integer

```<code>#include <stdio.h>
int Loops() {
    int s, e, z;
    printf("Input number \n");
    scanf("%d", &s);
    for(e = 0; e < s; e++) {
        for(z = 0; z < s; z++) {
            if(e==0 || e==s-1 || z==0 || z==s-1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
}

int main() {
   Loops();
}
</code>```

 i think the teacher mentioned something of adding a switch case...?

答:
You can simply use an infinite loop i.e. while(1) loop with a condition to break. Let's say you want a user to input positive integer and discard negative numbers and alphabets as well, you can do that in the following manner:

```<code>int Loops() {
int s, e, z;

while(1)
{
    printf("Input number \n");
    e = scanf("%d", &s);
    if((s <= 0) || (e != 1))
    {
        printf("Please Enter Non-negaitve Number\n");
        getchar(); //This is to consume the '\n'
    }
    else
    {
        break;
    }
}

for(e = 0; e < s; e++) {
    for(z = 0; z < s; z++) {
        if(e==0 || e==s-1 || z==0 || z==s-1)
            printf("*");
        else
            printf(" ");
    }
    printf("\n");
  }
}
</code>```

Body:
I need a program that asks for an integer &prints out an emtpy asterisk square based on the input number. And if the input was invalid then i need it to try and ask again
.
THIS is what i have so far (it already can make a square based on a variable number) i just need to enhence it so it asks again if the user is too dumb to input an integer

#include <stdio.h>
int Loops() {
    int s, e, z;
    printf("Input number \n");
    scanf("%d", &s);
    for(e = 0; e < s; e++) {
        for(z = 0; z < s; z++) {
            if(e==0 || e==s-1 || z==0 || z==s-1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
}

int main() {
   Loops();
}

 i think the teacher mentioned something of adding a switch case...?

Body:
You can simply use an infinite loop i.e. while(1) loop with a condition to break. Let's say you want a user to input positive integer and discard negative numbers and alphabets as well, you can do that in the following manner:

int Loops() {
int s, e, z;

while(1)
{
    printf("Input number \n");
    e = scanf("%d", &s);
    if((s <= 0) || (e != 1))
    {
        printf("Please Enter Non-negaitve Number\n");
        getchar(); //This is to consume the '\n'
    }
    else
    {
        break;
    }
}

for(e = 0; e < s; e++) {
    for(z = 0; z < s; z++) {
        if(e==0 || e==s-1 || z==0 || z==s-1)
            printf("*");
        else
            printf(" ");
    }
    printf("\n");
  }
}


问:
How does google make make those awesome PDF reports in Analytics and when you print a Google Doc etc?
When you print from Google Docs (using the "print" link, not File/Print) you end up printing a nicely formated PDF file instead of relying on the print engine of the browser.  Same is true for some of the reports in Google Analytics . . . the printed reports as PDF's are beautiful.  How do they do that?  I can't imagine they use something like Adobe Acrobat to facilitate it but maybe they do.  I've seen some expensive HTML to PDF converters online from time to time but have never tired it.  Any thoughts?</p>

答:
iTextSharp and iText are opensource and free PDF generation libraries for .NET and Java respectively.

I've used them to generate report PDF's before and was quite happy with the results.

http://itextsharp.sourceforge.net/

http://www.lowagie.com/iText/

OwnerDisplayName: Sheldon McGee

OwnerDisplayName: Jonathan Holland


问:
How can I make silent exceptions louder in tkinter?
If I run the following code from a terminal, I get a helpful error message in the terminal:

```<code>import Tkinter as tk

master = tk.Tk()

def callback():
    raise UserWarning("Exception!")

b = tk.Button(master, text="This will raise an exception", command=callback)
b.pack()

tk.mainloop()
</code>```

However, if I run it without a terminal (say, by double-clicking an icon), the error message is suppressed.

In my real, more complicated Tkinter application, I like that the GUI is a little crash-resistant. I don't like that my users have a hard time giving me useful feedback to fix the resulting unexpected behavior.

How should I handle this? Is there a standard way to expose tracebacks or stderror or whatnot in a Tkinter application? I'm looking for something more elegant than putting try/except everywhere.

EDIT: Jochen Ritzel gave an excellent answer below that pops up a warning box, and mentioned attaching it to a class. Just to make this explicit:

```<code>import Tkinter as tk
import traceback, tkMessageBox

class App:
    def __init__(self, master):
        master.report_callback_exception = self.report_callback_exception
        self.frame = tk.Frame(master)
        self.frame.pack()
        b = tk.Button(
            self.frame, text="This will cause an exception",
            command=self.cause_exception)
        b.pack()

    def cause_exception(self):
        a = []
        a.a = 0 #A traceback makes this easy to catch and fix

    def report_callback_exception(self, *args):
        err = traceback.format_exception(*args)
        tkMessageBox.showerror('Exception', err)

root = tk.Tk()
app = App(root)
root.mainloop()
</code>```

My remaining confusion: Jochen mentions the possibility of having different exception reporting functions in different frames. I don't yet see how to do that. Is this obvious?

答:
There is report_callback_exception to do this:

```<code>import traceback
import tkMessageBox

# You would normally put that on the App class
def show_error(self, *args):
    err = traceback.format_exception(*args)
    tkMessageBox.showerror('Exception',err)
# but this works too
tk.Tk.report_callback_exception = show_error
</code>```

If you didn't import Tkinter as tk, then do

```<code>Tkinter.Tk.report_callback_exception = show_error
</code>```

Body:
If I run the following code from a terminal, I get a helpful error message in the terminal:

import Tkinter as tk

master = tk.Tk()

def callback():
    raise UserWarning("Exception!")

b = tk.Button(master, text="This will raise an exception", command=callback)
b.pack()

tk.mainloop()

However, if I run it without a terminal (say, by double-clicking an icon), the error message is suppressed.

In my real, more complicated Tkinter application, I like that the GUI is a little crash-resistant. I don't like that my users have a hard time giving me useful feedback to fix the resulting unexpected behavior.

How should I handle this? Is there a standard way to expose tracebacks or stderror or whatnot in a Tkinter application? I'm looking for something more elegant than putting try/except everywhere.

EDIT: Jochen Ritzel gave an excellent answer below that pops up a warning box, and mentioned attaching it to a class. Just to make this explicit:

import Tkinter as tk
import traceback, tkMessageBox

class App:
    def __init__(self, master):
        master.report_callback_exception = self.report_callback_exception
        self.frame = tk.Frame(master)
        self.frame.pack()
        b = tk.Button(
            self.frame, text="This will cause an exception",
            command=self.cause_exception)
        b.pack()

    def cause_exception(self):
        a = []
        a.a = 0 #A traceback makes this easy to catch and fix

    def report_callback_exception(self, *args):
        err = traceback.format_exception(*args)
        tkMessageBox.showerror('Exception', err)

root = tk.Tk()
app = App(root)
root.mainloop()

My remaining confusion: Jochen mentions the possibility of having different exception reporting functions in different frames. I don't yet see how to do that. Is this obvious?

Body:
There is report_callback_exception to do this:

import traceback
import tkMessageBox

# You would normally put that on the App class
def show_error(self, *args):
    err = traceback.format_exception(*args)
    tkMessageBox.showerror('Exception',err)
# but this works too
tk.Tk.report_callback_exception = show_error

If you didn't import Tkinter as tk, then do

Tkinter.Tk.report_callback_exception = show_error


问:
Why can Android Studio not connect to physical devices?
Up until very recently Android Studio had no problems sending APKs to Android devices over USB. But now, although it works fine with the emulator, I cannot send APKs to either of the two physical devices I have tried.

"adb devices" shows no devices connected, even when the phone is connected over a USB cable (I tried other cables too) and when USB debugging IS enabled on the device.

I have tried revoking USB debugging authorisation on the devices, but on restarting adb and reconnecting the device am not asked to authorise the new access.

I've tried rebooting the phones, rebooting the dev machine (a MacBook) and killing and restarting adb, but with no success. I wonder if a recent Android tools update has reset the USB device auth, but how do I re-auth?

It's a problem as the app I'm working on scans barcodes so I really do need a physical device for testing.

UPDATE 1
Ah, so it seems if a USB device is not authorised, it still shows in the list but marked as such. The devices do not show in the list at all so it seems it is not an authorisation issue.

On a Samsung J5, when it is connected to the MacBook, no notification shows. When a Pixel 2 XL is connected to USB, the phone shows the "USB debugging connected" notification, but adb devices does not list it.

UPDATE 2
On making sure adb is running, then connecting both devices to the MacBook with USB and then running "adb devices", I am seeing this:

List of devices attached
* daemon not running; starting now at tcp:5037
ADB server didn't ACK
Full server startup log: /var/folders/_3/zzf_y_vx2rnc685ysjf1hqr40000gn/T//adb.501.log
Server had pid: 13977
--- adb starting (pid 13977) ---
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Version 27.0.0-4455170
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Installed as /Users/admin/android-sdk/platform-tools/adb
adb I 12-08 10:10:52 13977 807310 main.cpp:57]
adb I 12-08 10:10:52 13977 807310 adb_auth_host.cpp:416] adb_auth_init...
adb I 12-08 10:10:52 13977 807310 adb_auth_host.cpp:174] read_key_file '/Users/admin/.android/adbkey'...
adb F 12-08 10:10:52 13977 807320 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)

failed to start daemon
error: cannot connect to daemon

If I then use kill-server and start-server, adb fails to start, showing the same output.

答:
Many phones have options like "Only charging" vs "Device access / Memory access (or something like that)"

Check this option on devices.

For Samsung, for example, you usually need to choose "Give access to images"
For Nexus'es - "Connect as MTP device"


问:
How to make datatables export to xls asking for password first before exporting
I was wondering if it is possible to make datatables ask for password first before it is exporting data from datatables to xls file. I tried javascript but apparently datatables uses flash player to export the data to file. So there's no on click event captured in javascript or jquery. Do anyone have the answer? I'll give my code snippet but I don't think it would help. Thanks.</p>

```<code>    var table = $('.example').DataTable( {
    // dom: '<"col_10 pt_5 pb_5"B><"clear">lf',
    dom: 'B<"pt_5"l>f',
    processing: true,
    serverSide: true,
    ajax:{
      url:'<?php echo site_url().'/student/leads/ajax'; ?>',
      cache: false,
      data: function(d){
        d.startdate = $('#date_from').val(),
        d.enddate = $('#date_to').val()
      }
    },
    iDisplayLength: 20,
    order: [ [ 0, "desc" ] ],
    aLengthMenu: [[20, 50, 100, -1], [20, 50, 100, "All"]],
    aoColumns: [
        {"sTitle": "id", "sWidth": "8%"},
        {"sTitle": "Name", "sWidth": "8%"},
        {"sTitle": "E-mail", "sWidth": "12%"},
        {"sTitle": "Telp", "sWidth": "8%"},
        {"sTitle": "Placement Date", "sWidth": "8%"},
        {"sTitle": "Register", "sWidth": "9%"},
        {"sTitle": "Teacher State", "sWidth": "11%"},
        {"sTitle": "Trial", "sWidth": "7%"},
        {"sTitle": "Study", "sWidth": "13%"}
    ],
    buttons: [
        {
          extend: 'excel',
          text: 'Export to Excel'
        }
    ],
    bAutoWidth: false
  });
</code>```

答: You can make two button first which will ask to login to database (create form with input users and password) and then if the users is correct you show an other button which gonna let the user download the xls file. </p>

Body:
I was wondering if it is possible to make datatables ask for password first before it is exporting data from datatables to xls file. I tried javascript but apparently datatables uses flash player to export the data to file. So there's no on click event captured in javascript or jquery. Do anyone have the answer? I'll give my code snippet but I don't think it would help. Thanks.

    var table = $('.example').DataTable( {
    // dom: '<"col_10 pt_5 pb_5"B><"clear">lf',
    dom: 'B<"pt_5"l>f',
    processing: true,
    serverSide: true,
    ajax:{
      url:'<?php echo site_url().'/student/leads/ajax'; ?>',
      cache: false,
      data: function(d){
        d.startdate = $('#date_from').val(),
        d.enddate = $('#date_to').val()
      }
    },
    iDisplayLength: 20,
    order: [ [ 0, "desc" ] ],
    aLengthMenu: [[20, 50, 100, -1], [20, 50, 100, "All"]],
    aoColumns: [
        {"sTitle": "id", "sWidth": "8%"},
        {"sTitle": "Name", "sWidth": "8%"},
        {"sTitle": "E-mail", "sWidth": "12%"},
        {"sTitle": "Telp", "sWidth": "8%"},
        {"sTitle": "Placement Date", "sWidth": "8%"},
        {"sTitle": "Register", "sWidth": "9%"},
        {"sTitle": "Teacher State", "sWidth": "11%"},
        {"sTitle": "Trial", "sWidth": "7%"},
        {"sTitle": "Study", "sWidth": "13%"}
    ],
    buttons: [
        {
          extend: 'excel',
          text: 'Export to Excel'
        }
    ],
    bAutoWidth: false
  });


问:
Can we use @Autowired in a Tasklet in Spring Batch?
I have a Spring Batch tasklet as follows in my application.

```<code>@Service
public class SampleTasklet implements Tasklet {

    @Autowired
    private UserService userService;

    @Override
    public RepeatStatus execute(StepContribution contribution,
                                ChunkContext chunkContext) throws Exception {

        System.err.println(userService.getUsers().size());
        return RepeatStatus.FINISHED;
    }

}
</code>```

and I have a Service Class as follows.

```<code>@Service
@Slf4j
public class UserService {
    public Map<String, String> getUsers(){
        return null
    }

}
</code>```

Spring Boot class :

```<code>@SpringBootApplication
@Slf4j
public class SampleBatchApp {

    public static void main(String[] args) {
        log.info("Custom DAM Batch Application starting");
        SpringApplication.run(SampleBatchApp.class, args);
    }

}
</code>```

Spring Batch File: -- EDITED as per comments.

```<code>@Configuration
@EnableBatchProcessing
public class SampleBatch {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    public SampleTasklet sampleTasklet;

    @Bean
    public Job importUserJob() {
        return jobBuilderFactory.get("importUserJob")
                .start(step1())
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .tasklet(sampleTasklet)
                .build();
    }

}
</code>```

When I start my application I get an error as follows.

Field userService in SampleTasklet required a bean of type 'UserService' that could not be found.

Can you please explain this weird behavior? I have tried looking for this in multiple places and I think we can't @autowire a service class inside a tasklet. Am I correct?

答:
OK I found the error.

In your SampleBatch you declare your Bean SampleTasklet in Java Config. That means you have to make sure all dependencies get injected. That is why you do not get the UserService autowired.

Make sure that the UserService gets set in

```<code>@Bean
public SampleTasklet sampleTasklet(UserService userService){
    return new SampleTasklet(userService);
}
</code>```

and do not forget to add this constructor in your SampleTasklet and assign the UserService there.

```<code>public class SampleTasklet implements Tasklet {

private UserService userService;

    public SampleTasklet (UserService userService){
        this.userService=userService;
    }
</code>```

Body:
I have a Spring Batch tasklet as follows in my application.

@Service
public class SampleTasklet implements Tasklet {

    @Autowired
    private UserService userService;

    @Override
    public RepeatStatus execute(StepContribution contribution,
                                ChunkContext chunkContext) throws Exception {

        System.err.println(userService.getUsers().size());
        return RepeatStatus.FINISHED;
    }

}

and I have a Service Class as follows.

@Service
@Slf4j
public class UserService {
    public Map<String, String> getUsers(){
        return null
    }

}

Spring Boot class :

@SpringBootApplication
@Slf4j
public class SampleBatchApp {

    public static void main(String[] args) {
        log.info("Custom DAM Batch Application starting");
        SpringApplication.run(SampleBatchApp.class, args);
    }

}

Spring Batch File: -- EDITED as per comments.

@Configuration
@EnableBatchProcessing
public class SampleBatch {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    public SampleTasklet sampleTasklet;

    @Bean
    public Job importUserJob() {
        return jobBuilderFactory.get("importUserJob")
                .start(step1())
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .tasklet(sampleTasklet)
                .build();
    }

}

When I start my application I get an error as follows.

Field userService in SampleTasklet required a bean of type 'UserService' that could not be found.

Can you please explain this weird behavior? I have tried looking for this in multiple places and I think we can't @autowire a service class inside a tasklet. Am I correct?

Body:
OK I found the error.

In your SampleBatch you declare your Bean SampleTasklet in Java Config. That means you have to make sure all dependencies get injected. That is why you do not get the UserService autowired.

Make sure that the UserService gets set in

@Bean
public SampleTasklet sampleTasklet(UserService userService){
    return new SampleTasklet(userService);
}

and do not forget to add this constructor in your SampleTasklet and assign the UserService there.

public class SampleTasklet implements Tasklet {

private UserService userService;

    public SampleTasklet (UserService userService){
        this.userService=userService;
    }


问:
Chrome alert pop up not detected in Selenium
I am having issues with handling Authentication pop up in Chrome via Selenium.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get('URL')
time.sleep(5)
alert = driver.switch_to_alert()
alert.send_keys('Username')
alert.send_keys(Keys.TAB)
alert.send_keys('Password')
</code>```

This returns an error--

"selenium.common.exceptions.NoAlertPresentException: Message: no alert open"

Alternatively, I also tried the following code:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get('https://Username:Password@URL')
</code>```

The second code works partially-

In Chrome the user is logged in but the page does not load. Only a blank page is displayed. Once the blank page is loaded, i passed only the URL(without user credentials) and it works fine.

In Firefox, the webpage loads perfectly.

Basically, the issue is with Chrome.

Any help is appreciated.

Thanks!

答:
First try to wait for alert present.

```<code>wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())
</code>```

if alert is present then only move forword to next step.
And also can you please check the screenshot if alert is actually present when testcase is failing.

Body:
I am having issues with handling Authentication pop up in Chrome via Selenium.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get('URL')
time.sleep(5)
alert = driver.switch_to_alert()
alert.send_keys('Username')
alert.send_keys(Keys.TAB)
alert.send_keys('Password')

This returns an error--

"selenium.common.exceptions.NoAlertPresentException: Message: no alert open"

Alternatively, I also tried the following code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get('https://Username:Password@URL')

The second code works partially-

In Chrome the user is logged in but the page does not load. Only a blank page is displayed. Once the blank page is loaded, i passed only the URL(without user credentials) and it works fine.

In Firefox, the webpage loads perfectly.

Basically, the issue is with Chrome.

Any help is appreciated.

Thanks!

Body:
First try to wait for alert present.

wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())

if alert is present then only move forword to next step.
And also can you please check the screenshot if alert is actually present when testcase is failing.


问:
Rewrite foreach loops into linq query?
I tried to rewrite the following loops in one "elegant" linq query but no success!

```<code>foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }
</code>```

Could anyone suggest a query (if even possible)?

Thanks in advance

答:
Here is the snippet that produced exactly the same result as using loops:

```<code>result = List1.FirstOrDefault(om => om.List2.Any(ol => ol.prop == value))?.prop;
</code>```

Thanks to everyone and especially to @Nekeniehl

Title: Rewrite foreach loops into linq query?

Body:
I tried to rewrite the following loops in one "elegant" linq query but no success!

foreach (Obj1 om in List1)
            {
                foreach (Obj2 ol in List2)
                {
                    if (ol.prop == value)
                    {
                       return om.prop
                    }
                }
            }

Could anyone suggest a query (if even possible)?

Thanks in advance

Body:
Here is the snippet that produced exactly the same result as using loops:

result = List1.FirstOrDefault(om => om.List2.Any(ol => ol.prop == value))?.prop;

Thanks to everyone and especially to @Nekeniehl


问:
SQL Server 2012 - using select * into along with dynamic SQL

Hi I have the the following code:

```<code>use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'
</code>```

print @dsql

--exec sp_executesql @dsql

```<code>select * into Sales.FreightTotals from @dsql;
</code>```

I am trying to use select * into with dynamic pivot as shown above.If I use

```<code>exec sp_executesql @dsql
</code>```

I get the following result the result i am looking for

```<code>empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)
</code>```

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

```<code>Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".
</code>```

any suggestion as to why this is the case?

答:
You can't use a string instead of a table in the from clause.

If you really need dynamic SQL you can use the insert ... exec workaround.

Insert into Sales.FreightTotals
Exec sp_executesql @dsql;

Body:
Hi I have the the following code:

use TSQL2012;
go

if OBJECT_ID('Sales.FreightTotals') is not null drop table
Sales.FreightTotals
go

declare @shipperid as nvarchar(max) ='';
declare @dsql as nvarchar(max);
select @shipperid += quotename(shipperid,'')+',' from sales.Orders group by
shipperid;
set @shipperid = LEFT(@shipperid, LEN(@shipperid)-1)

print @shipperid;

set @dsql='
select empid,'+@shipperid+' from
(select empid, shipperid, freight from Sales.Orders )as d
pivot(sum(freight) for shipperid in('+@shipperid+')) as pvt
order by pvt.empid
'

print @dsql

--exec sp_executesql @dsql

select * into Sales.FreightTotals from @dsql;

I am trying to use select * into with dynamic pivot as shown above.If I use

exec sp_executesql @dsql

I get the following result the result i am looking for

empid       1                     2                     3
----------- --------------------- --------------------- --------------------
1           2194.73               3259.99               3381.92
2           2281.09               4350.20               2065.12
3           2491.74               4258.90               4134.10
4           3129.39               4926.73               3290.02
5           1218.27               1991.84               708.60
6           1049.83               1270.42               1460.22
7           1204.60               3155.18               2305.66
8           1889.27               3297.40               2301.21
9           726.41                1734.19               865.66

(9 rows affected)

but if I do
    select * into Sales.FreightTotals from @dsql;

i get:

Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@dsql".

any suggestion as to why this is the case?


问:
how to match statement that combine word,/,digits like /dev/home/hello-world
i want to match following statement in regex:

```<code>/
/dev/shm
/var/lib/snap/hello-world/27
</code>```

any idea?
and this is my last try:

```<code>\/((\w+)|(\/\w+-\w+))+
</code>```

but it seems that, dash-statements treat like a seperate part.

答:
If you are a positive person and don't want to use negative classes (as proposed by @anubhava), you can check this fully positive regex:

```<code>^(?:(?:\/)|(?:\/\w+)|(?:\/\w+-\w+))+$
</code>```

RegEx Demo

Body:
i want to match following statement in regex:

/
/dev/shm
/var/lib/snap/hello-world/27

any idea?
and this is my last try:

\/((\w+)|(\/\w+-\w+))+

but it seems that, dash-statements treat like a seperate part.

Body:
If you are a positive person and don't want to use negative classes (as proposed by @anubhava), you can check this fully positive regex:

^(?:(?:\/)|(?:\/\w+)|(?:\/\w+-\w+))+$

RegEx Demo


问:
How to add data to a Arraylist from a diffrent class
I have seen all the other questions to his topic but I didnt realy get much from it.Just started learning java so pls try to make  the explanation for me as simple as you can.

How do I add to my Arraylist "Fish" anything at all? I coudlnt even add something to it in the same class(line3 class question)... but I need to know how to add it in different a class.(I tried it in the end of class question 2 but it didnt work too)

```<code>import java.util.ArrayList;

public class question {

    private String name;

    public ArrayList<String> Fish = new ArrayList<>();

    Fish.add(name); // <--- this for some reason doesnt work the point is red underlined as well as the ")"

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getFish() {
        return Fish;
    }
}
</code>```

second class

```<code>public class question2 {

    public String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    // First try : question.getFish().add(nam1);
    // Second try   question.Fish.add(name1);
    //how do I add the name1 into my ArrayList "Fish".How can I transport my ArrayList from question1 to question2?
}
</code>```

Any help will be appreciated, Thank you.

答:
Fish.add(name);

does not make any sense here. Such a statement must be inside a method. To get access to the field "Fish" (btw: please obey the Java naming conventions that strictly recommend fields to start with a lower case letter), you first need an instance of "question" (here again: classes start with an upper case letter).

private String name;

what is that name for? It's a sibling of your ArrayList.

To add a fish to your ArrayList I would go with the following:

```<code>public void addFish(String name) {
    Fish.add(name);
}
</code>```

Put that method inside your question class.

Regarding your second class: Both tries would work if they were inside a method and you had an instance of question in question2. I don't see the use of the question2 class here - but one possibility to add fish inside question2 would be:

```<code>public void addFish(question q, String name) {
    q.getFish().add(name);
}
</code>```

I suggest you work through some nice java tutorials. It seems that you lack some basic understanding of OOP. I would start here: https://docs.oracle.com/javase/tutorial/java/concepts/object.html
https://docs.oracle.com/javase/tutorial/java/concepts/class.html

Body:
I have seen all the other questions to his topic but I didnt realy get much from it.Just started learning java so pls try to make  the explanation for me as simple as you can.

How do I add to my Arraylist "Fish" anything at all? I coudlnt even add something to it in the same class(line3 class question)... but I need to know how to add it in different a class.(I tried it in the end of class question 2 but it didnt work too)

import java.util.ArrayList;

public class question {

    private String name;

    public ArrayList<String> Fish = new ArrayList<>();

    Fish.add(name); // <--- this for some reason doesnt work the point is red underlined as well as the ")"

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getFish() {
        return Fish;
    }
}

second class

public class question2 {

    public String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    // First try : question.getFish().add(nam1);
    // Second try   question.Fish.add(name1);
    //how do I add the name1 into my ArrayList "Fish".How can I transport my ArrayList from question1 to question2?
}

Any help will be appreciated, Thank you.

Body:
Fish.add(name);

does not make any sense here. Such a statement must be inside a method. To get access to the field "Fish" (btw: please obey the Java naming conventions that strictly recommend fields to start with a lower case letter), you first need an instance of "question" (here again: classes start with an upper case letter).

private String name;

what is that name for? It's a sibling of your ArrayList.

To add a fish to your ArrayList I would go with the following:

public void addFish(String name) {
    Fish.add(name);
}

Put that method inside your question class.

Regarding your second class: Both tries would work if they were inside a method and you had an instance of question in question2. I don't see the use of the question2 class here - but one possibility to add fish inside question2 would be:

public void addFish(question q, String name) {
    q.getFish().add(name);
}

I suggest you work through some nice java tutorials. It seems that you lack some basic understanding of OOP. I would start here: https://docs.oracle.com/javase/tutorial/java/concepts/object.html
https://docs.oracle.com/javase/tutorial/java/concepts/class.html


问:
Can static_cast work for bit fields?
Hi does static cast work for bit fields?. Because here i have created a bit field of 32 bit Long data and i am trying to cast it to u32.

```<code>void CO2_SpiDriver::CreateBuffer() {
    //#[ operation CreateBuffer()
    typedef struct scr_t
     {
         union {
            u32 data;
             struct {
                 u8 CRC : 4;
                 u16 Datatosend : 16;
                 u8 DataLengthCode : 2;
                 u8 AddressReg : 4;
                 u8 ReadandWrite : 1;
                 u8 InstrucCode : 3;
                 u8 ExtChipId : 2;
             };
         };
     } scr_t;

     //set of data bits
     scr_t se;
     se.CRC = 0x00;   //CRC BITS 0 to 3
     se.Datatosend = 0x0000000000000000;  //Data bits 19 to 4
     se.DataLengthCode = 0x00; //DLC bits 21 and 20
     se.AddressReg = 0x00;     // SMP580 registers to access 25-22
     se.ReadandWrite = 0x01;  //Read|Write Reg 26
     se.InstrucCode = 0x5;    //InstrCode 29-27
     se.ExtChipId = 0x2;      //ExtChipId 31-30

     static_cast<u32>(se)
</code>```

But here i am getting an error that scr_t cannot be casted to u32. Can anyone give some suggestions

答:
In C++, only one of the fields of an union is active at any time. The only portable way to reinterpret a memory layout is to use std::memcpy:

```<code>struct bf {
    u8 CRC : 4;
    u16 Datatosend : 16;
    u8 DataLengthCode : 2;
    u8 AddressReg : 4;
    u8 ReadandWrite : 1;
    u8 InstrucCode : 3;
    u8 ExtChipId : 2;
};

bf se;
se.CRC = 0x00;   //CRC BITS 0 to 3
se.Datatosend = 0x0000000000000000;  //Data bits 19 to 4
se.DataLengthCode = 0x00; //DLC bits 21 and 20
se.AddressReg = 0x00;     // SMP580 registers to access 25-22
se.ReadandWrite = 0x01;  //Read|Write Reg 26
se.InstrucCode = 0x5;    //InstrCode 29-27
se.ExtChipId = 0x2;      //ExtChipId 31-30

u32 se_as_u32;
static_assert(sizeof(se_as_u32) <= sizeof(se), "UB detector"); // avoid reading buffer overflow (see explanation below)
std::memcpy(&se_as_u32, &se, sizeof(se_as_u32));
</code>```

Note: I've added the line

```<code>static_assert(sizeof(se_as_u32) <= sizeof(se), "UB detector");
</code>```

in order to protect se to be read outside of its "bounds":

```<code>std::memcpy(&se_as_u32, &se, sizeof(se_as_u32));
</code>```

This reads sizeof(u32) (probably 4) bytes from se. In the eventuality that se was smaller than 4 bytes long, memcpy would read "outside of it", this is a kind of buffer overflow and result in undefined behaviour (this is bad).
In the case where the inequality was not respected (sizeof(se_as_u32) > sizeof(se)), a merciful abort() would be called and the program would promptly crash instead of maybe working for a time and destroy the production one day.

Title: Can static_cast work for bit fields?

Body:
Hi does static cast work for bit fields?. Because here i have created a bit field of 32 bit Long data and i am trying to cast it to u32.

void CO2_SpiDriver::CreateBuffer() {
    //#[ operation CreateBuffer()
    typedef struct scr_t
     {
         union {
            u32 data;
             struct {
                 u8 CRC : 4;
                 u16 Datatosend : 16;
                 u8 DataLengthCode : 2;
                 u8 AddressReg : 4;
                 u8 ReadandWrite : 1;
                 u8 InstrucCode : 3;
                 u8 ExtChipId : 2;
             };
         };
     } scr_t;

     //set of data bits
     scr_t se;
     se.CRC = 0x00;   //CRC BITS 0 to 3
     se.Datatosend = 0x0000000000000000;  //Data bits 19 to 4
     se.DataLengthCode = 0x00; //DLC bits 21 and 20
     se.AddressReg = 0x00;     // SMP580 registers to access 25-22
     se.ReadandWrite = 0x01;  //Read|Write Reg 26
     se.InstrucCode = 0x5;    //InstrCode 29-27
     se.ExtChipId = 0x2;      //ExtChipId 31-30

     static_cast<u32>(se)

But here i am getting an error that scr_t cannot be casted to u32. Can anyone give some suggestions

Body:
In C++, only one of the fields of an union is active at any time. The only portable way to reinterpret a memory layout is to use std::memcpy:

struct bf {
    u8 CRC : 4;
    u16 Datatosend : 16;
    u8 DataLengthCode : 2;
    u8 AddressReg : 4;
    u8 ReadandWrite : 1;
    u8 InstrucCode : 3;
    u8 ExtChipId : 2;
};

bf se;
se.CRC = 0x00;   //CRC BITS 0 to 3
se.Datatosend = 0x0000000000000000;  //Data bits 19 to 4
se.DataLengthCode = 0x00; //DLC bits 21 and 20
se.AddressReg = 0x00;     // SMP580 registers to access 25-22
se.ReadandWrite = 0x01;  //Read|Write Reg 26
se.InstrucCode = 0x5;    //InstrCode 29-27
se.ExtChipId = 0x2;      //ExtChipId 31-30

u32 se_as_u32;
static_assert(sizeof(se_as_u32) <= sizeof(se), "UB detector"); // avoid reading buffer overflow (see explanation below)
std::memcpy(&se_as_u32, &se, sizeof(se_as_u32));

Note: I've added the line

static_assert(sizeof(se_as_u32) <= sizeof(se), "UB detector");

in order to protect se to be read outside of its "bounds":

std::memcpy(&se_as_u32, &se, sizeof(se_as_u32));

This reads sizeof(u32) (probably 4) bytes from se. In the eventuality that se was smaller than 4 bytes long, memcpy would read "outside of it", this is a kind of buffer overflow and result in undefined behaviour (this is bad).
In the case where the inequality was not respected (sizeof(se_as_u32) > sizeof(se)), a merciful abort() would be called and the program would promptly crash instead of maybe working for a time and destroy the production one day.


问:
dplyr tidyeval equivalent of underscore function versions
Rencent versions of dplyr deprecate underscore versions of functions, such as filter_, in favour of tidy evaluation.

What is expected new form of the underscore forms with the new way? How do I write avoiding undefined symbols with R CMD check?

```<code>library(dplyr)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")

# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )

# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )
</code>```

Is there a preferred or more conside form? Option C is shortest but is slower on some of my real-world larger datasets and more complex dplyr constructs:

```<code>microbenchmark(
sym = dsPClosest %>%
  group_by(!!sym(dateVarName), !!sym("depth")) %>%
  summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
            , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
  ungroup()
,data = dsPClosest %>%
    group_by(!!sym(dateVarName), .data$depth ) %>%
    summarise(temperature = mean(.data$temperature , na.rm = TRUE)
              , moisture = mean(.data$moisture , na.rm = TRUE)) %>%
    ungroup()
,times=10
)
#Unit: milliseconds
# expr        min         lq      mean     median        uq       max neval
#  sym   80.05512   84.97267  122.7513   94.79805  100.9679  392.1375    10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648    10
</code>```

There is another answer for mutate_ using even more complex syntax.

答:
```<code># option F: using the dot .
df %>% filter( .$id == "a" )

# slow in progtw's real-world problem:
microbenchmark(
  sym = dsPClosest %>%
    group_by(!!sym(dateVarName), !!sym("depth")) %>%
    summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
              , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
    ungroup()
  ,dot = dsPClosest %>%
    group_by(!!sym(dateVarName), .$depth ) %>%
    summarise(temperature = mean(.$temperature , na.rm = TRUE)
              , moisture = mean(.$moisture , na.rm = TRUE)) %>%
    ungroup()
  ,times=10
)
#Unit: milliseconds
# expr          min           lq         mean       median           uq         max neval
#  sym     75.37921     78.86365     90.72871     81.22674     90.77943    163.2081    10
#  dot 115452.88945 116260.32703 128314.44451 125162.46876 136578.09888 149193.9751    10
</code>```

Similar to option c (.data$) but shorter. However, showed poor performance on my real-world application.

Moreover, I did not find documentation on when this can be used.

Body:
Rencent versions of dplyr deprecate underscore versions of functions, such as filter_, in favour of tidy evaluation.

What is expected new form of the underscore forms with the new way? How do I write avoiding undefined symbols with R CMD check?

library(dplyr)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")

# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )

# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )

Is there a preferred or more conside form? Option C is shortest but is slower on some of my real-world larger datasets and more complex dplyr constructs:

microbenchmark(
sym = dsPClosest %>%
  group_by(!!sym(dateVarName), !!sym("depth")) %>%
  summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
            , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
  ungroup()
,data = dsPClosest %>%
    group_by(!!sym(dateVarName), .data$depth ) %>%
    summarise(temperature = mean(.data$temperature , na.rm = TRUE)
              , moisture = mean(.data$moisture , na.rm = TRUE)) %>%
    ungroup()
,times=10
)
#Unit: milliseconds
# expr        min         lq      mean     median        uq       max neval
#  sym   80.05512   84.97267  122.7513   94.79805  100.9679  392.1375    10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648    10

There is another answer for mutate_ using even more complex syntax.

Body:
# option F: using the dot .
df %>% filter( .$id == "a" )

# slow in progtw's real-world problem:
microbenchmark(
  sym = dsPClosest %>%
    group_by(!!sym(dateVarName), !!sym("depth")) %>%
    summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
              , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
    ungroup()
  ,dot = dsPClosest %>%
    group_by(!!sym(dateVarName), .$depth ) %>%
    summarise(temperature = mean(.$temperature , na.rm = TRUE)
              , moisture = mean(.$moisture , na.rm = TRUE)) %>%
    ungroup()
  ,times=10
)
#Unit: milliseconds
# expr          min           lq         mean       median           uq         max neval
#  sym     75.37921     78.86365     90.72871     81.22674     90.77943    163.2081    10
#  dot 115452.88945 116260.32703 128314.44451 125162.46876 136578.09888 149193.9751    10

Similar to option c (.data$) but shorter. However, showed poor performance on my real-world application.

Moreover, I did not find documentation on when this can be used.


问:
Create new row to data set based existing ones SAS
I have a dataset looking something like this:

```<code>var1 var2   count
cat1    no     1
cat1    yes    4
cat1    unkown 3
cat2    no     7
cat2    yes    3
cat2    unkown 5
cat3    no     2
cat3    yes    9
cat3    unkown 0
</code>```

What I want to do is combine var1 & var2 into new variable where first row is from var1 and the others from var2. So it supposed to look like:

```<code>comb   count
cat1
no     1
yes    4
unkown 3
cat2
no     7
yes    3
unkown 5
cat3
no     2
yes    9
unkown 0
</code>```

Any help would be highly appreciated!

答:
It's quite simple.

Here the solution :

1) create the dataset source:

```<code>data testa;
 infile datalines dsd dlm=',';
   input var1 : $200. var2 : $200. count : 8. ;
   datalines;
cat1,no,1,
cat1,yes,4,
cat1,unkown,3,
cat2,no,7,
cat2,yes,3,
cat2,unkown,5,
cat3,no,2,
cat3,yes,9,
cat3,unkown,0,
;
run;
</code>```

2) Selection of var list : cat1|cat2|cat3

```<code>proc sql;
    select distinct(var1) into: list_var separated by '|' from testa;
run;
</code>```

3) Process the var list one by one

```<code>%macro processListVar(list_var);

    data want;
    run;

    %let k=1;
    %do %while (%qscan(&list_var, &k,|) ne );
        %let var = %scan(&list_var, &k,|);

        data testb(drop=var1 rename=(var2=comb));
            set testa;
            N=_N_+1+&k;
            where var1="&var";
        run;

        data testc;
            N=1+&k;
            comb="&var";
            count=.;
        run;

        data tmp;
            set testb testc;
        run;

        proc sort data=tmp out=teste;
        by N;
        run;

        data want;
            set want teste;
        run;

        %put var=&var;
        %let k = %eval(&k + 1);
    %end;

%mend processListVar;

%processListVar(&list_var);
</code>```

4) At the end you get the result in dataset want.

You have to exclude finaly the N column like that :

```<code>data want_cleaned (drop=N);
set want;
run;
</code>```

5) More explanation on the code.

a. The key problem was to keep the order between cat1,cat2,cat3.

b. So I divided the problem by each dataset cat1, cat2, .. and created a %do %while to loop through categories.

c. We use the column N, to count the number of line (like an index), and then we can sort on this column, to keep the order.

d. For example : the first var cat1 : We select the column var2, we rename it like the comb column. We drop the var1 column. It create the testb dataset.
The testb dataset is used to create an index (column N) and we create the first line of our subdataset (N=1+&k) in testc. &k is used through all subdatasets. Like that the index is continuing between subdatasets. (without interfering each others). We make a merge between testb and testc. The dataset tmp contains all info needed for cat1. Then we merge all subdatasets in dataset want.

So to summary, we create a loop, and we merge the datasets together at the end. We make a sort on the column N, to display lines in the order you wanted.

Regards,

Body:
I have a dataset looking something like this:

var1 var2   count
cat1    no     1
cat1    yes    4
cat1    unkown 3
cat2    no     7
cat2    yes    3
cat2    unkown 5
cat3    no     2
cat3    yes    9
cat3    unkown 0

What I want to do is combine var1 & var2 into new variable where first row is from var1 and the others from var2. So it supposed to look like:

comb   count
cat1
no     1
yes    4
unkown 3
cat2
no     7
yes    3
unkown 5
cat3
no     2
yes    9
unkown 0

Any help would be highly appreciated!

Body:
It's quite simple.

Here the solution :

1) create the dataset source:

data testa;
 infile datalines dsd dlm=',';
   input var1 : $200. var2 : $200. count : 8. ;
   datalines;
cat1,no,1,
cat1,yes,4,
cat1,unkown,3,
cat2,no,7,
cat2,yes,3,
cat2,unkown,5,
cat3,no,2,
cat3,yes,9,
cat3,unkown,0,
;
run;

2) Selection of var list : cat1|cat2|cat3

proc sql;
    select distinct(var1) into: list_var separated by '|' from testa;
run;

3) Process the var list one by one

%macro processListVar(list_var);

    data want;
    run;

    %let k=1;
    %do %while (%qscan(&list_var, &k,|) ne );
        %let var = %scan(&list_var, &k,|);

        data testb(drop=var1 rename=(var2=comb));
            set testa;
            N=_N_+1+&k;
            where var1="&var";
        run;

        data testc;
            N=1+&k;
            comb="&var";
            count=.;
        run;

        data tmp;
            set testb testc;
        run;

        proc sort data=tmp out=teste;
        by N;
        run;

        data want;
            set want teste;
        run;

        %put var=&var;
        %let k = %eval(&k + 1);
    %end;

%mend processListVar;

%processListVar(&list_var);

4) At the end you get the result in dataset want.

You have to exclude finaly the N column like that :

data want_cleaned (drop=N);
set want;
run;

5) More explanation on the code.

a. The key problem was to keep the order between cat1,cat2,cat3.

b. So I divided the problem by each dataset cat1, cat2, .. and created a %do %while to loop through categories.

c. We use the column N, to count the number of line (like an index), and then we can sort on this column, to keep the order.

d. For example : the first var cat1 : We select the column var2, we rename it like the comb column. We drop the var1 column. It create the testb dataset.
The testb dataset is used to create an index (column N) and we create the first line of our subdataset (N=1+&k) in testc. &k is used through all subdatasets. Like that the index is continuing between subdatasets. (without interfering each others). We make a merge between testb and testc. The dataset tmp contains all info needed for cat1. Then we merge all subdatasets in dataset want.

So to summary, we create a loop, and we merge the datasets together at the end. We make a sort on the column N, to display lines in the order you wanted.

Regards,


问:
Blog error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:
I'm building the view post page for my blog and I have the following error in the browser:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near 'FROM blog_posts
  WHERE postID = '15'' at line 1' in
  /home/ct5006kwolczak/public_html/viewpost.php:7 Stack trace: #0
  /home/ct5006kwolczak/public_html/viewpost.php(7):
  PDOStatement->execute(Array) #1 {main} thrown in
  /home/ct5006kwolczak/public_html/viewpost.php on line 7

I expect the page to view the post description page

Screenshot of code

答:
Problem in query string syntax:</p>

```<code>Remove comma after `postDate` field.
</code>```

Body:
Problem in query string syntax:

Remove comma after `postDate` field.


问:
REST API calling from Angular application
I am trying to develop my web application using microservice architecture. Back-end I am using Spring, Spring Cloud and Spring Boot for microservice. And my front-end application is a Angular 2 application. My front-end application will work according to the back end rest end-point which is calling from Angular 2 application.

I am trying to create a login for this web app. I planning to use an API key for authentication to back-end service. And my login checking functionality is also a microservice. So here When I calling my back-end service , How I can achieve this API key functionality? Is it need to set constantly as unique variable?

Here API key can not be dynamically manageable,since login functionality itself is a microservice, So I need to use API key for calling login check service which is to be already deployed in the cloud?

How can I understand this scenario?

答:
You can't really use API key in this scenario as its a web app. The API key would be publicly visible in the web app.
The correct way to implement authentication is quite complex and involves

Angular Route Guards

Angular Http interceptors.

JWT Token management in both server and client side.

A high -level overview of the whole process may be summarised as below:

User tries to login with his credentials. This is sent to a server for authentication.

The credentials are validated against a DB record. If validated, A JWT token is sent back to client.

The client should store this JWT token somewhere, either in memory or local storage, depending upon the use-case.A valid JWT indicates the user is authenticated.

For every subsequent request, this JWT should be appended to request header. The server will look for this JWT token to authenticate.

Access to client-side routes are protected to authenticated users using route guards.

Again, this JWT token has an expiry time and must be continuously checked for expiry.

If the expiry of JWT token of authenticated user is close, the server should return a refresh-token and the client should request a new authenticated JWT token using this refresh token.

Please refer to this article for a start.


问:
SFML graphics Draw Texture in Window- Black Screen
I just tried to write a chess engine, and what is important to me is that I get a nice visual representation of the game. I tried to implement the Code in a Visual Studio project - the problem is that the program only shows me a black screen instead of the texture I loaded.

My Code is the following:

```<code>#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int main(){

    RenderWindow window(VideoMode(1000, 1000), "MattseChess!");

    Texture t1;
    t1.loadFromFile("images/board.png");
    Sprite s(t1);

    while (window.isOpen())
    {
        Event e;

        while (window.pollEvent(e)) {

            if (e.type == Event::Closed)
                window.close();
    //Draw
            window.clear();
            window.draw(s);
            window.display();
        }
    }

    return 0;
}
</code>```

Do you have any idea of what I did wrong?

答:
That code works. I am pretty sure you did not put your board.png into the images directory in your execution path.

Make sure this image is available:

```<code>t1.loadFromFile("images/board.png");
</code>```

Body:
I just tried to write a chess engine, and what is important to me is that I get a nice visual representation of the game. I tried to implement the Code in a Visual Studio project - the problem is that the program only shows me a black screen instead of the texture I loaded.

My Code is the following:

#include <SFML/Graphics.hpp>
#include <time.h>
using namespace sf;

int main(){

    RenderWindow window(VideoMode(1000, 1000), "MattseChess!");

    Texture t1;
    t1.loadFromFile("images/board.png");
    Sprite s(t1);

    while (window.isOpen())
    {
        Event e;

        while (window.pollEvent(e)) {

            if (e.type == Event::Closed)
                window.close();
    //Draw
            window.clear();
            window.draw(s);
            window.display();
        }
    }

    return 0;
}

Do you have any idea of what I did wrong?

Body:
That code works. I am pretty sure you did not put your board.png into the images directory in your execution path.

Make sure this image is available:

t1.loadFromFile("images/board.png");