问:
Jquery input type hidden value data toggle add/remove
Basically i have two buttons that insert dynamic data to the one input value:

```<code>    <button class="sunday">Sunday</button>
    <button class="monday">Monday</button>

    <input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017">
</code>```

Each button inserts 3 dates, so if you click both on sunday and monday for example you will get

```<code><input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017, 3/18/2017, 3/19/2017, 3/20/2017">
</code>```

What would be the best way to do this with JQuery but to be like a toggle, I want to add them but not to duplicate them.

答:
```<code>$(".sunday, .monday").off("click").on("click",function(){
    var existing = [];
    var duplicates = $('#ElementID').filter(function() {
        var value = $(this).val().split(",");
        //compare the array and insert to existing array
        existing.push(value);
    });
    ("#hidden").value(existing);
});
</code>```

Body:
Basically i have two buttons that insert dynamic data to the one input value:

    <button class="sunday">Sunday</button>
    <button class="monday">Monday</button>

    <input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017">

Each button inserts 3 dates, so if you click both on sunday and monday for example you will get

<input type="hidden" value="3/15/2017, 3/16/2017, 3/17/2017, 3/18/2017, 3/19/2017, 3/20/2017">

What would be the best way to do this with JQuery but to be like a toggle, I want to add them but not to duplicate them.


来源: stackexchange

问:
How to extract all the emojis from text?
Consider the following list:

```<code>a_list = ['  me así, bla es se  ds ']
</code>```

How can I extract in a new list all the emojis inside a_list?:

```<code>new_lis = ['     ']
</code>```

I tried to use regex, but I do not have all the possible emojis encodings.

答: All the Unicode emojis with their respective code points are here. They are 1F600 to 1F64F, so you can just build all of them with a range-like iterator. </p>

ContentLicense: CC BY-SA 3.0

Body:
Consider the following list:

a_list = ['  me así, bla es se  ds ']

How can I extract in a new list all the emojis inside a_list?:

new_lis = ['     ']

I tried to use regex, but I do not have all the possible emojis encodings.


问:
Android- Unable to download image to external storage from url using json and Picasso
My app function is something like i want have displayed several image from Json to custom adapter using volley and now what I need is to download all displayed image on that particular fragment to external memory when user click on download button.

I have given permission to manifest file:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

code for extracting image and downloading using picasso is :

```<code>public class AKVSeriesOneFragment extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private View view;
// Movies json url
private static final String url = "https://developers.kurtisgallery.in/example_api/kurtisone/id/8";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private GridView gridView;
private CustomListAdapter adapter;

public AKVSeriesOneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_akvseries_one, container, false);
    ImageView imageView = (ImageView) rootView.findViewById(R.id.downoadimgs);

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            for (int i = 0; i < movieList.size(); i++) {

                String url = movieList.get(i).getThumbnailUrl();
                Picasso.with(getContext())
                        .load(url)
                        .into(new Target() {
                            @Override
                            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                        File folder = new File(sd, "/Picasso/");
                                        if (!folder.exists()) {
                                            if (!folder.mkdir()) {
                                                Log.e("ERROR", "Cannot create a directory!");
                                            } else {
                                                folder.mkdir();
                                            }
                                        }

                                        for (int i=0; i< movieList.size(); i++) {

                                            File[] fileName = {new File("Image"+i)};

                                            if (!fileName[i].exists()) {
                                                try {
                                                    fileName[i].createNewFile();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            } else {

                                                try {
                                                    FileOutputStream outputStream = new FileOutputStream(String.valueOf(fileName[i]));
                                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                                    outputStream.close();

                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }

                                    }
                                }).start();

                            }

                            @Override
                            public void onBitmapFailed(Drawable errorDrawable) {

                            }

                            @Override
                            public void onPrepareLoad(Drawable placeHolderDrawable) {

                            }
                        });
            }

        }
    });

    gridView = (GridView) rootView.findViewById(R.id.list);
    adapter = new CustomListAdapter(getActivity(), movieList);
    gridView.setAdapter(adapter);

    pDialog = new ProgressDialog(getActivity());
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            //movie.setTitle(obj.getString("category_name"));
                            movie.setThumbnailUrl(obj.getString("thumb_img_dest"));
                     movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);

    return  rootView;
}
</code>```

Here I am getting error EROFS (Read-only file system)
I have searched stackoverflow before and found many similar probleb but non of solution is working for me.As I am beginner android developer.

答:
I solved my problem, as code was correct but problem arose due to permission on mashmallow. So I did this code:

```<code>    private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

//persmission method.
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have read or write permission
    int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}
</code>```

and in activity file i call the function

```<code>verifyStoragePermissions(this);
</code>```

Hope it help someone!!

Body:
My app function is something like i want have displayed several image from Json to custom adapter using volley and now what I need is to download all displayed image on that particular fragment to external memory when user click on download button.

I have given permission to manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

code for extracting image and downloading using picasso is :

public class AKVSeriesOneFragment extends Fragment {
private static final String TAG = MainActivity.class.getSimpleName();
private View view;
// Movies json url
private static final String url = "https://developers.kurtisgallery.in/example_api/kurtisone/id/8";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private GridView gridView;
private CustomListAdapter adapter;

public AKVSeriesOneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_akvseries_one, container, false);
    ImageView imageView = (ImageView) rootView.findViewById(R.id.downoadimgs);

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            for (int i = 0; i < movieList.size(); i++) {

                String url = movieList.get(i).getThumbnailUrl();
                Picasso.with(getContext())
                        .load(url)
                        .into(new Target() {
                            @Override
                            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {

                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                        File folder = new File(sd, "/Picasso/");
                                        if (!folder.exists()) {
                                            if (!folder.mkdir()) {
                                                Log.e("ERROR", "Cannot create a directory!");
                                            } else {
                                                folder.mkdir();
                                            }
                                        }

                                        for (int i=0; i< movieList.size(); i++) {

                                            File[] fileName = {new File("Image"+i)};

                                            if (!fileName[i].exists()) {
                                                try {
                                                    fileName[i].createNewFile();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            } else {

                                                try {
                                                    FileOutputStream outputStream = new FileOutputStream(String.valueOf(fileName[i]));
                                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                                                    outputStream.close();

                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }

                                    }
                                }).start();

                            }

                            @Override
                            public void onBitmapFailed(Drawable errorDrawable) {

                            }

                            @Override
                            public void onPrepareLoad(Drawable placeHolderDrawable) {

                            }
                        });
            }

        }
    });

    gridView = (GridView) rootView.findViewById(R.id.list);
    adapter = new CustomListAdapter(getActivity(), movieList);
    gridView.setAdapter(adapter);

    pDialog = new ProgressDialog(getActivity());
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            //movie.setTitle(obj.getString("category_name"));
                            movie.setThumbnailUrl(obj.getString("thumb_img_dest"));
                     movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);

    return  rootView;
}

Here I am getting error EROFS (Read-only file system)
I have searched stackoverflow before and found many similar probleb but non of solution is working for me.As I am beginner android developer.

Body:
I solved my problem, as code was correct but problem arose due to permission on mashmallow. So I did this code:

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

//persmission method.
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have read or write permission
    int writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);

    if (writePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

and in activity file i call the function

verifyStoragePermissions(this);

Hope it help someone!!


问:
Visual Studio 2015 quick action helpers have disappeared
Until very recently, my copy of Visual Studio 2015 Professional provided a very useful set of features, in particular...

changing the name of a property/method would give a light-bulb icon and the ability to update all instances of those properties/methods

using an unreferenced class/namespace would give a light-bulb icon and the ability to quickly add a using/Imports, along with multiple other options

Here is an example of the 2nd of the above... the light-bulb used to appear just to the left of the popup message.

I cannot find any obvious option that would turn this off.

The issue is happening in both C# and VB.Net projects

I recently had an issue with CodeLens, the solution I found told me to remove the %TEMP%\ALM directory.  This fixed the CodeLens, but I'm wondering if it could have effected the light-bulb helpers.

Does anybody know how to get the light-bulb helpers to return?

答: After updating to VS2015 Update 3 the light-bulb helpers have returned</p>


问:
Unable to display data in DataTable from a server via ajax
I want to display data in DataTable via ajax from a server. Here's what I have:

```<code> # server
  # ....
  return jsonify({"data": {1: (123, "something1", 333), 2: (456, "something2", 555)}})
</code>```

And a template:

```<code><script>
    $("#my_table").DataTable({
      ajax: "/my_url.json",
      processing: true,
      serverSide: true,
      columns: [
        {data: "id" },
        {data: "column2"},
        {data: "column3"}
      ]
    });
  </script>
</code>```

And a table:

```<code><table id="my_table">
  <thead>
   ......
</code>```

For some reason, nothing happens. At all. Neither an ajax request to a server. Nor errors either. The js and css files have been included into the template.

When I go to "/my_url.json" in a browser, it returns json.

How to fix it?

答:
You'll need to adapt your server-side script a little as DataTables expects the data to be in this form:

```<code>{
    "data": [
        {
            "id": 123,
            "column2": "something1",
            "column3": 333
        },{
            "id": 456,
            "column2": "something2",
            "column3": 555
        }
    ]
}
</code>```

I'm pretty sure that your data won't be in that sort of format, though well done for clocking the need for data!

I'm not up on Python so I'm not sure how you'd go about altering your server-side script, sorry. You could process it within DataTables but it might be better to do it server-side, hope that helps.

Body:
I want to display data in DataTable via ajax from a server. Here's what I have:

 # server
  # ....
  return jsonify({"data": {1: (123, "something1", 333), 2: (456, "something2", 555)}})

And a template:

And a table:

   ......

For some reason, nothing happens. At all. Neither an ajax request to a server. Nor errors either. The js and css files have been included into the template.

When I go to "/my_url.json" in a browser, it returns json.

How to fix it?

Body:
You'll need to adapt your server-side script a little as DataTables expects the data to be in this form:

{
    "data": [
        {
            "id": 123,
            "column2": "something1",
            "column3": 333
        },{
            "id": 456,
            "column2": "something2",
            "column3": 555
        }
    ]
}

I'm pretty sure that your data won't be in that sort of format, though well done for clocking the need for data!

I'm not up on Python so I'm not sure how you'd go about altering your server-side script, sorry. You could process it within DataTables but it might be better to do it server-side, hope that helps.


问:
How to display a text inside a tag if a value passed from controller is true using blade template?
I want to disable input if the value transferred from the controller is false. I read the blade template documentation for Laravel, but couldn't find any useful resource.

I tried the following code, but it yields an error.

```<code><input type="text" name="url" style="height:36px;"   value="http://theurl.in/{{$link_data->hash}}" @if $isEditable {{ 'enabled' }} @endif /> <br/>
</code>```

The exact code part is,

```<code>@if $isEditable {{ 'enabled' }} @endif
</code>```

If you can provide any suggestion, it would be very helpful.

Thanks!

答:
Not sure what the purpose of  the 'enabled' string is but you don't need it. HTML inputs are enabled by default. What you need is a simple ternary that prints disabled="disabled".

```<code>{{ !$isEnabled ? 'disabled="disabled"' : '' }}
</code>```

Body:
I want to disable input if the value transferred from the controller is false. I read the blade template documentation for Laravel, but couldn't find any useful resource.

I tried the following code, but it yields an error.

<input type="text" name="url" style="height:36px;"   value="http://theurl.in/{{$link_data->hash}}" @if $isEditable {{ 'enabled' }} @endif />

The exact code part is,

@if $isEditable {{ 'enabled' }} @endif

If you can provide any suggestion, it would be very helpful.

Thanks!

Body:
Not sure what the purpose of  the 'enabled' string is but you don't need it. HTML inputs are enabled by default. What you need is a simple ternary that prints disabled="disabled".

{{ !$isEnabled ? 'disabled="disabled"' : '' }}


问:
How can i change number Of Rows In each Components

How can i change number Of Rows In each Components
i have this:

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
return 3;
}
</code>```

BUT this change all of Components rows number,

And The next question is : How can i Change the values in third component Like UIDatePicker : for example: in Date (in january) days are 31 but (in February) days are (29/28) an the third components must change and values will be between 1-29 or 1-28.

答:
Every picker calls -pickerView:numberOfRowsInComponent: and asks it for the number of rows for each component. So this method is called three times, because you have three components. Thus you need to return different values for the components. You get an NSInteger in the component variable to indicate which component is asked for:

```<code>- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
    switch(component)
    {
        case 0: // first component has 42 rows
            return 42;
        case 1: // second component has 21 rows
            return 21;
        case 2: // third component has only two rows
            return 2;
    }
}
</code>```

Body:
How can i change number Of Rows In each Components
i have this:

- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
return 3;
}

BUT this change all of Components rows number,

And The next question is : How can i Change the values in third component Like UIDatePicker : for example: in Date (in january) days are 31 but (in February) days are (29/28) an the third components must change and values will be between 1-29 or 1-28.

Body:
Every picker calls -pickerView:numberOfRowsInComponent: and asks it for the number of rows for each component. So this method is called three times, because you have three components. Thus you need to return different values for the components. You get an NSInteger in the component variable to indicate which component is asked for:

- (NSInteger) pickerView:(UIPickerView *)pickerView  numberOfRowsInComponent:(NSInteger)component
{
    switch(component)
    {
        case 0: // first component has 42 rows
            return 42;
        case 1: // second component has 21 rows
            return 21;
        case 2: // third component has only two rows
            return 2;
    }
}

ContentLicense: CC BY-SA 2.5


问:
Drink Vending Machine Code
Hello Stackflow community,
I'm currently taking a class in Visual Basic and I'm in need of some assistance. I am creating a program that simulates a Drink Vending Machine using an array. The instructions follow:
Create an application that simulates a soft-drink vending machine. The application should let the user select one of the following soft drinks:

Cola ($1.00 each)
Root Beer ($1.00 each)
Lemon Lime Soda ($1.00 each)
Grape Soda ($1.50 each)
Cream Soda ($1.50 each)

When the application starts, the vending machine will have 20 of each type of soft drink. Each time the user selects a drink, the application should subtract 1 from the quantity of the selected drink. It should also update and display the total amount of sales. If the user selects a drink that is sold out, a message should be displayed indicating so.

In the application’s code, create a structure that has fields for the following data:

Drink name
Drink cost
Number of drinks in machine

The program should create an array of five structure objects. Each element of the array should keep data for a specific type of soft drink.

I can't figure out how to make my buttons work to decrement the quantity labels and then add each click to the label total. Please help.

```<code>Public Class Form1
' Class-level declarations
Const intMAX_SUBSCRIPT As Integer = 4               ' Upper subscript
Dim strProdNames(intMAX_SUBSCRIPT) As String        ' Product Names
Dim decPrice(intMAX_SUBSCRIPT) As Decimal           ' Drink Price
Dim intProdNums(intMAX_SUBSCRIPT) As Integer        ' Product Numbers

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Initialize the arrays with the product data.
    InitArrays()
End Sub

Private Sub InitArrays()
    ' Initialize the arrays.

    ' First Product
    strProdNames(0) = "Cola"
    decPrice(0) = 1D
    intProdNums(0) = 20

    ' Second Product
    strProdNames(1) = "Root Beer"
    decPrice(1) = 1D
    intProdNums(1) = 20

    ' Third Product
    strProdNames(2) = "Lemon Lime"
    decPrice(2) = 1D
    intProdNums(2) = 20

    ' Fourth Product
    strProdNames(3) = "Grape Soda"
    decPrice(3) = 1.5D
    intProdNums(3) = 20

    ' Fifth Product
    strProdNames(4) = "Cream Soda"
    decPrice(4) = 1.5D
    intProdNums(4) = 20

End Sub

Private Sub btnCola_Click(sender As Object, e As EventArgs) Handles btnCola.Click
    Dim intCount As Integer = 20        ' Loop Counter

    intCount -= 1                       ' Decrement drink count

    If intCount > 0 Then
        lblTotal.Text = decPrice(0).ToString("c")
    End If

End Sub
</code>```

答:
You need to decrement the cola count, which is in the array.</p>

```<code> Private Sub btnCola_Click(sender As Object, e As EventArgs)
        If intProdNums(0) > 0 Then
            intProdNums(0)-=1  ' decrement cola drink count
        End If

        ' show results here...
    End Sub
</code>```

Title: Drink Vending Machine Code

Body:
Hello Stackflow community,
I'm currently taking a class in Visual Basic and I'm in need of some assistance. I am creating a program that simulates a Drink Vending Machine using an array. The instructions follow:
Create an application that simulates a soft-drink vending machine. The application should let the user select one of the following soft drinks:

Cola ($1.00 each)
Root Beer ($1.00 each)
Lemon Lime Soda ($1.00 each)
Grape Soda ($1.50 each)
Cream Soda ($1.50 each)

When the application starts, the vending machine will have 20 of each type of soft drink. Each time the user selects a drink, the application should subtract 1 from the quantity of the selected drink. It should also update and display the total amount of sales. If the user selects a drink that is sold out, a message should be displayed indicating so.

In the application’s code, create a structure that has fields for the following data:

Drink name
Drink cost
Number of drinks in machine

The program should create an array of five structure objects. Each element of the array should keep data for a specific type of soft drink.

I can't figure out how to make my buttons work to decrement the quantity labels and then add each click to the label total. Please help.

Public Class Form1
' Class-level declarations
Const intMAX_SUBSCRIPT As Integer = 4               ' Upper subscript
Dim strProdNames(intMAX_SUBSCRIPT) As String        ' Product Names
Dim decPrice(intMAX_SUBSCRIPT) As Decimal           ' Drink Price
Dim intProdNums(intMAX_SUBSCRIPT) As Integer        ' Product Numbers

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Initialize the arrays with the product data.
    InitArrays()
End Sub

Private Sub InitArrays()
    ' Initialize the arrays.

    ' First Product
    strProdNames(0) = "Cola"
    decPrice(0) = 1D
    intProdNums(0) = 20

    ' Second Product
    strProdNames(1) = "Root Beer"
    decPrice(1) = 1D
    intProdNums(1) = 20

    ' Third Product
    strProdNames(2) = "Lemon Lime"
    decPrice(2) = 1D
    intProdNums(2) = 20

    ' Fourth Product
    strProdNames(3) = "Grape Soda"
    decPrice(3) = 1.5D
    intProdNums(3) = 20

    ' Fifth Product
    strProdNames(4) = "Cream Soda"
    decPrice(4) = 1.5D
    intProdNums(4) = 20

End Sub

Private Sub btnCola_Click(sender As Object, e As EventArgs) Handles btnCola.Click
    Dim intCount As Integer = 20        ' Loop Counter

    intCount -= 1                       ' Decrement drink count

    If intCount > 0 Then
        lblTotal.Text = decPrice(0).ToString("c")
    End If

End Sub

Body:
You need to decrement the cola count, which is in the array.

 Private Sub btnCola_Click(sender As Object, e As EventArgs)
        If intProdNums(0) > 0 Then
            intProdNums(0)-=1  ' decrement cola drink count
        End If

        ' show results here...
    End Sub


问:
Deletion a Node from binary search tree with 2 nodes, with a different method possible?
I have searched everywhere for this but there is only one method :

find predecessor (or successor) of node to delete

replace node with predecessor (or successor)

delete predecessor (or successor)

But i feel we can also do in this way :

pulloff the right(or left) element to the node to delete i.e just replace the
  element to delete with right (or left) element and keep doing it till we encounter
  the leaf and then delete the leaf.
  In brief, keep replacing element to delete with its right(or left) element and keep doing it till we reach the leaf , and then delete the leaf.

So Is this method right ?

答:
I don't truly follow your algorithm (both of them). But below is how you delete a node from a Binary Tree (non-balancing).

Find the node to be deleted. This node can only be replaced by one of the 2 nodes in the existing tree

1. The leftmost (i.e. smallest) element of your right child node or

2. The rightmost (i.e. largest) element of your left child node.

Replace it with whichever is available and you are done

No other nodes need to be moved since

1. RightMostChildOfLeftChild() < CurrentNode() < LeftMostChildOfRightChild()

2. No nodes exist between RightMostChildOfLeftChild() and LeftMostChildOfRightChild() other than the CurrentNode()

Now if you don't mind just moving a bunch of nodes around, then there are lot of other ways to delete a node.

Hope that clarifies it for you.


问:
Update after CTE: The multi-part identifier "MyCTE.SomeField" could not be bound
I have following SQL query in my sql-server:

```<code>WITH SampleCTE1 AS ( ... ),

MyCTE(SomeField) AS ( SELECT SomeField FROM ....)

UPDATE SomeTable WITH (serializable)
   set SomeColumnInSomeTable = MyCTE.SomeField
   where SomeFieldInSomeTable = 112
   if @@rowcount = 0
   begin
      insert into SomeTable.....
   end
</code>```

The multi-part identifier "MyCTE.SomeField" could not be bound.

Can you help me remove this error ?

Btw, I have a sql-server-2012. Is it ok to use MERGE ? In some places I did read that I shouldn't use it due to bugs.  What do you think ?

答:
You can only reference your common table expression(s) in the statement after the last cte, so you will have to repeat it to use it again for the following insert (or use merge) .

You also have not joined or accessed MyCte in your update statement.

```<code>WITH SampleCTE1 AS ( ... ),

MyCTE(SomeField) AS ( SELECT SomeField FROM ....)

UPDATE SomeTable WITH (serializable)
   set SomeColumnInSomeTable = MyCTE.SomeField
   from SomeTable
     inner join MyCTE
       on SomeTable.SomeId = MyCte.SomeId
   where SomeFieldInSomeTable = 112;

   if @@rowcount = 0
   begin;

    ;WITH SampleCTE1 AS ( ... ),

    MyCTE(SomeField) AS ( SELECT SomeField FROM ....)

      insert into SomeTable.....
   end;
</code>```

Body:
I have following SQL query in my sql-server:

WITH SampleCTE1 AS ( ... ),

MyCTE(SomeField) AS ( SELECT SomeField FROM ....)

UPDATE SomeTable WITH (serializable)
   set SomeColumnInSomeTable = MyCTE.SomeField
   where SomeFieldInSomeTable = 112
   if @@rowcount = 0
   begin
      insert into SomeTable.....
   end

The multi-part identifier "MyCTE.SomeField" could not be bound.

Can you help me remove this error ?

Btw, I have a sql-server-2012. Is it ok to use MERGE ? In some places I did read that I shouldn't use it due to bugs.  What do you think ?

Body:
You can only reference your common table expression(s) in the statement after the last cte, so you will have to repeat it to use it again for the following insert (or use merge) .

You also have not joined or accessed MyCte in your update statement.

WITH SampleCTE1 AS ( ... ),

MyCTE(SomeField) AS ( SELECT SomeField FROM ....)

UPDATE SomeTable WITH (serializable)
   set SomeColumnInSomeTable = MyCTE.SomeField
   from SomeTable
     inner join MyCTE
       on SomeTable.SomeId = MyCte.SomeId
   where SomeFieldInSomeTable = 112;

   if @@rowcount = 0
   begin;

    ;WITH SampleCTE1 AS ( ... ),

    MyCTE(SomeField) AS ( SELECT SomeField FROM ....)

      insert into SomeTable.....
   end;


问:
hover style of custom checkbox with font awesome
I have some simple html/css with font awesome fonts to customise a checkbox. I am struggling to modify the colour (to red for now) when the checkbox is hovered.

As I am using a font awesome font to customise the checkbox, I assumed I needed to apply the css on hover of the label but its not having the desired effect.

```<code> input.faChkRnd:hover + label:before {
   color: red;
 }
</code>```

This seems to change only on click of the checkbox and not when hovering.

any help appreciated!

fiddle here

答:
we cannot target hover state on an element which has display:none property. we can have a hover on label.

```<code>//when input is not checked
input.faChkRnd + label:hover:before {
  color: red;
}

//when input is checked
input.faChkRnd:checked + label:hover:before {
  color: green;
}
</code>```

https://jsfiddle.net/a0s0gkxb/3/

This library might help to customise checkboxes and radio buttons , https://lokesh-coder.github.io/pretty-checkbox/

Body:
I have some simple html/css with font awesome fonts to customise a checkbox. I am struggling to modify the colour (to red for now) when the checkbox is hovered.

As I am using a font awesome font to customise the checkbox, I assumed I needed to apply the css on hover of the label but its not having the desired effect.

 input.faChkRnd:hover + label:before {
   color: red;
 }

This seems to change only on click of the checkbox and not when hovering.

any help appreciated!

fiddle here

Body:
we cannot target hover state on an element which has display:none property. we can have a hover on label.

//when input is not checked
input.faChkRnd + label:hover:before {
  color: red;
}

//when input is checked
input.faChkRnd:checked + label:hover:before {
  color: green;
}

https://jsfiddle.net/a0s0gkxb/3/

This library might help to customise checkboxes and radio buttons , https://lokesh-coder.github.io/pretty-checkbox/


问:
How to load annotation image after opened, not before
I have thousands of annotations on the map. Each annotation is a unique image. So, I don't want to load all the images on the map unless requested by the user.

My annotations have this property:

```<code>detailCalloutView: <Image source={{uri: data[i].img_url, cache: 'force-cache'}} style={styles.thumbnail} resizeMode={Image.resizeMode.contain}/>
</code>```

How do I make the image only load when the annotation is opened? I don't want to shred through gigabytes of data by opening all annotations.

I think I need to do something with onFocus but I'm not quite sure how.

答:
Change this

detailCalloutView: <Image source={{uri: data[i].img_url, cache: 'force-cache'}} style={styles.thumbnail} resizeMode={Image.resizeMode.contain}/>

To this

detailCalloutView: <Image source="blanking.jpg" data-annotation={{uri: data[i].img_url, cache: 'force-cache'}}  style={styles.thumbnail} resizeMode={Image.resizeMode.contain}/>

Then add an event listener to all the images in the map

```<code>var attr = this.getAttribute("data-annotation");
this.src = attr;
</code>```

That's the main bit to add. And now even when closed it won't have to load again because the src will forever be the actual image. I'm not going to wrap the entire JavaScript for you but you should get the gist from this.

Body:
I have thousands of annotations on the map. Each annotation is a unique image. So, I don't want to load all the images on the map unless requested by the user.

My annotations have this property:

detailCalloutView: <Image source={{uri: data[i].img_url, cache: 'force-cache'}} style={styles.thumbnail} resizeMode={Image.resizeMode.contain}/>

How do I make the image only load when the annotation is opened? I don't want to shred through gigabytes of data by opening all annotations.

I think I need to do something with onFocus but I'm not quite sure how.

Body:
Change this

detailCalloutView: <Image source={{uri: data[i].img_url, cache: 'force-cache'}} style={styles.thumbnail} resizeMode={Image.resizeMode.contain}/>

To this

detailCalloutView: <Image source="blanking.jpg" data-annotation={{uri: data[i].img_url, cache: 'force-cache'}}  style={styles.thumbnail} resizeMode={Image.resizeMode.contain}/>

Then add an event listener to all the images in the map

var attr = this.getAttribute("data-annotation");
this.src = attr;

That's the main bit to add. And now even when closed it won't have to load again because the src will forever be the actual image. I'm not going to wrap the entire JavaScript for you but you should get the gist from this.


问:
Measure network traffic programmatically on iPhone
I'm interested in measuring the network traffic for my application. Ideally I would need to separate wireless from 3G network traffic. I can't seem to find any API that gets this information; however I see that there is at least one app in the AppStore that does something close (they actually sum up the traffic for the entire phone).

Any ideas?

答:
I've found one approximate solution: getifaddrs can be used to get statistics on network usage.

One advantage is that it can get separate statistics for Wi-Fi and WWAN interfaces.

A disadvantage is that on multi-tasking devices those interfaces may be used by multiple applications and the statistics are cumulated.


答:
You can use the emoji library. You can check if a single codepoint is an emoji codepoint by checking if it is contained in emoji.UNICODE_EMOJI.

```<code>import emoji

def extract_emojis(s):
  return ''.join(c for c in s if c in emoji.UNICODE_EMOJI['en'])
</code>```

Title: How to extract all the emojis from text?

Body:
Consider the following list:

a_list = ['  me así, bla es se  ds ']

How can I extract in a new list all the emojis inside a_list?:

new_lis = ['     ']

I tried to use regex, but I do not have all the possible emojis encodings.

Body:
You can use the emoji library. You can check if a single codepoint is an emoji codepoint by checking if it is contained in emoji.UNICODE_EMOJI.

import emoji

def extract_emojis(s):
  return ''.join(c for c in s if c in emoji.UNICODE_EMOJI['en'])

ContentLicense: CC BY-SA 4.0


答:
MyCTE is not referenced in UPDATE. It should be

```<code>...
UPDATE SomeTable WITH (serializable)
   set SomeColumnInSomeTable = MyCTE.SomeField
FROM SomeTable
{LEFT/ RIGHT / INNER}JOIN  MyCTE ON ...
</code>```

Title: Update after CTE: The multi-part identifier "MyCTE.SomeField" could not be bound

Body:
MyCTE is not referenced in UPDATE. It should be

...
UPDATE SomeTable WITH (serializable)
   set SomeColumnInSomeTable = MyCTE.SomeField
FROM SomeTable
{LEFT/ RIGHT / INNER}JOIN  MyCTE ON ...


问:
Finding multiple maxima for dictionary of lists
I'm trying to return all maximum values from a dictionary of lists. </p>

```<code>my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

maxima = max(my_dict.items(), key=operator.itemgetter(1))[0]
</code>```

<p>This is only returning '122', rather than both '111' and '122'. How can I modify this to return both keys? </p>

答:
To sort your list according to the max of items in the list you could do:

```<code>print(sorted(my_dict.keys(),key=lambda x: max(my_dict[x])))
</code>```

You get [144, 133, 122, 111] but that wouldn't tell you which keys bear the highest value in their associated list.

So you have to perform that in 2 steps:

compute maximum value of all values in lists

extract the keys matching the lists containing this value

like this for instance:

```<code>my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

max_value = max(x for l in my_dict.values() for x in l) # flat max of values
</code>```

or if you want to compute the max on a particular value given its position, for instance the first one:

```<code>max_value = max(l[0] for l in my_dict.values())
</code>```

then extract from dict with filter:

```<code>print([k for k,v in my_dict.items() if max_value in v]) # keys whose value contain the max
</code>```

result:

```<code>[122, 111]
</code>```

Body:
I'm trying to return all maximum values from a dictionary of lists.

my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

maxima = max(my_dict.items(), key=operator.itemgetter(1))[0]

This is only returning '122', rather than both '111' and '122'. How can I modify this to return both keys?

Body:
To sort your list according to the max of items in the list you could do:

print(sorted(my_dict.keys(),key=lambda x: max(my_dict[x])))

You get [144, 133, 122, 111] but that wouldn't tell you which keys bear the highest value in their associated list.

So you have to perform that in 2 steps:

compute maximum value of all values in lists

extract the keys matching the lists containing this value

like this for instance:

my_dict = { 111: [50, 2, 34], 122: [50 , 4, 45], 133: [40, 1, 12], 144: [20, 5, 7]}

max_value = max(x for l in my_dict.values() for x in l) # flat max of values

or if you want to compute the max on a particular value given its position, for instance the first one:

max_value = max(l[0] for l in my_dict.values())

then extract from dict with filter:

print([k for k,v in my_dict.items() if max_value in v]) # keys whose value contain the max

result:

[122, 111]


问:
How to find password protected pdf-files in a directory?
In a windows directory I have about 100 pdf-files, some are password protected, some are not. Is there an easy way (in the command-line or maybe with a freeware tool) to find the ones which are password protected without opening each of them in a pdf-reader?</p>

答:
Since you are on Windows, you can use the iTextSharp library to accomplish this.

First, extract itextsharp.dll, which is inside the itextsharp-dll-core archive.

Then, use the following PowerShell script:

```<code>Add-Type -Path .\itextsharp.dll

Get-ChildItem -Filter *.pdf |
ForEach-Object {
    $filename = $_.Name
    Try {
        $pdf = New-Object iTextSharp.text.pdf.PdfReader($_.FullName)
        If ($pdf.IsEncrypted()) {
            $filename
        }
    }
    Catch {
        $filename
    }
}
</code>```

The output will be the name of each PDF which is secured or encrypted.

Body:
Since you are on Windows, you can use the iTextSharp library to accomplish this.

First, extract itextsharp.dll, which is inside the itextsharp-dll-core archive.

Then, use the following PowerShell script:

Add-Type -Path .\itextsharp.dll

Get-ChildItem -Filter *.pdf |
ForEach-Object {
    $filename = $_.Name
    Try {
        $pdf = New-Object iTextSharp.text.pdf.PdfReader($_.FullName)
        If ($pdf.IsEncrypted()) {
            $filename
        }
    }
    Catch {
        $filename
    }
}

The output will be the name of each PDF which is secured or encrypted.


问:
Select Random item from list in Google Sheet
Im working on a google sheet document to randomly pick a protein and a side dish for weeknight meals based on a selection.  The idea is you select your meat (chicken, beef, pork, etc) and the max amount of calories for the meal and it will select a protein and side dish randomly from a list.  Not sure how to go about writing either the equation or a script to do this though.  Heres what im working with so far:

This is the main page where you select what you want

This is the protein sheet that will have all the possible selections, so based on the image above would want to randomly pick a chicken dish with 800 or less calories

And finally this is the side, for this I would want to choose a side that is less than the remaining calories, so if the protein had say 500 calories would want a side with 300 or less:

答:
On the Proteins sheet add E3 =randbetween(1,100) and copy the formula down. On the Side/Vegetables add C3 =randbetween(1,100) and copy down. On the Dinner Generator sheet add this query to A8:

```<code>=query(Sheet2!A3:E,"select A,B where D contains '"& A3 &"' and B <= "& B3 &" order by E desc Limit 1")
</code>```

and this to A9:

```<code>=query(Sheet3!A3:C,"Select A,B where B <= ("& B3 &" - "& B8 &") order by C desc Limit 1")
</code>```

And this to A10:

```<code>=B8+B9
</code>```

I named the sheets Sheet1, Sheet2, and Sheet3. Change the sheet names in the queries as needed. I also used desc in the queries so blanks would be at the bottom allowing the lists to be expanded without having to change the queries. I suggest you change fish entries in column D to Fish instead of Tuna, Salmon, etc. Below is a shared example spreadsheet. Make a copy to test.

https://docs.google.com/spreadsheets/d/17SWtKfzDFDV8OeffR7s5PcmmwRMzu6UKzWK26CX7KDU/edit?usp=sharing

Body:
On the Proteins sheet add E3 =randbetween(1,100) and copy the formula down. On the Side/Vegetables add C3 =randbetween(1,100) and copy down. On the Dinner Generator sheet add this query to A8:

=query(Sheet2!A3:E,"select A,B where D contains '"& A3 &"' and B <= "& B3 &" order by E desc Limit 1")

and this to A9:

=query(Sheet3!A3:C,"Select A,B where B <= ("& B3 &" - "& B8 &") order by C desc Limit 1")

And this to A10:

=B8+B9

I named the sheets Sheet1, Sheet2, and Sheet3. Change the sheet names in the queries as needed. I also used desc in the queries so blanks would be at the bottom allowing the lists to be expanded without having to change the queries. I suggest you change fish entries in column D to Fish instead of Tuna, Salmon, etc. Below is a shared example spreadsheet. Make a copy to test.

https://docs.google.com/spreadsheets/d/17SWtKfzDFDV8OeffR7s5PcmmwRMzu6UKzWK26CX7KDU/edit?usp=sharing


问:
Map properties to state in react-redux
I have a component that uses state to provide data to user. For example
this.state.variableInState
. This component can dispatch some method (for example on onClick action). I'm currently using react-redux an connect method to map store to props. Is there a way I can setState after dispatch?

```<code>// actions
export function executeAction() {
  return function (dispatch, getState) {
    dispatch({
      type: 'MY_ACTION',
      payload: axios.get('/some/url')
    });
  };
}
// reducer

export default function (state = {}, action) {
  switch (action.type) {
    case 'MY_ACTION_FULFILLED':
      return {...state, myVariable: action.payload.data}
  }
}
//component
class MyComponent extends Component {
  render() {
    (<div onClick={this.props.executeAction.bind(this)}>
      {this.state.variableInState}
      </div>)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);
</code>```

答:
Sure you can, onClick bind to some function like so:

```<code>onClick={this.myfunction.bind(this)}
</code>```

Then define this myfuntion to be:

```<code>myfunction() {
    this.setState({ somestate: value });
    this.props.executeAction();
}
</code>```

Here setState changes native component state, and calling action will change redux state if so defined by reducer. These states are independent.

Connect wrapper (first argument) maps state to props (redux state to react props) not component state itself.

Good question is why you need both, sure there are some examples where this could be useful...

In general if you need state that is needed globally then use redux state (easily applied to all components) and for some local states use react native state. (For example when you build some ui components like custom checkbox)

Title: Map properties to state in react-redux

Body:
I have a component that uses state to provide data to user. For example
this.state.variableInState
. This component can dispatch some method (for example on onClick action). I'm currently using react-redux an connect method to map store to props. Is there a way I can setState after dispatch?

// actions
export function executeAction() {
  return function (dispatch, getState) {
    dispatch({
      type: 'MY_ACTION',
      payload: axios.get('/some/url')
    });
  };
}
// reducer

export default function (state = {}, action) {
  switch (action.type) {
    case 'MY_ACTION_FULFILLED':
      return {...state, myVariable: action.payload.data}
  }
}
//component
class MyComponent extends Component {
  render() {
    (

      {this.state.variableInState}

)
  }

  someOtherMethod() {
    // I want to operate with state here, not with props
    // that's why my div gets state from this.state instead of this.props
    this.setState({variableInState: 'someValue'})
  }
}

export default connect((state, ownProperties) => {
  return {
    // So I want to change MyComponent.state.variableInState here
    // but this method updates MyComponent props only
    // What can I do?
    variableInProps: state.myVariable
  }
}, {executeAction})(MyComponent);

Body:
Sure you can, onClick bind to some function like so:

onClick={this.myfunction.bind(this)}

Then define this myfuntion to be:

myfunction() {
    this.setState({ somestate: value });
    this.props.executeAction();
}

Here setState changes native component state, and calling action will change redux state if so defined by reducer. These states are independent.

Connect wrapper (first argument) maps state to props (redux state to react props) not component state itself.

Good question is why you need both, sure there are some examples where this could be useful...

In general if you need state that is needed globally then use redux state (easily applied to all components) and for some local states use react native state. (For example when you build some ui components like custom checkbox)


问:
How long does RDD remain in memory?
Considering memory being limited, I had a feeling that spark automatically removes RDD from each node. I'd like to know is this time configurable? How does spark decide when to evict an RDD from memory

Note: I'm not talking about rdd.cache()

答:
According to the Resilient Distributed Data-set paper -

Our worker nodes cache RDD partitions in memory as
  Java objects. We use an LRU replacement policy at the
  level of RDDs (i.e., we do not evict partitions from an
  RDD in order to load other partitions from the same
  RDD) because most operations are scans. We found this
  simple policy to work well in all our user applications so
  far. Programmers that want more control can also set a
  retention priority for each RDD as an argument to cache.

Title: How long does RDD remain in memory?


问:
Is it more performant to add inferred keywords to Groovy
Groovy is an interpreted language. Right?
So I'm thinking: isn't it better to be verbose when we can to lessen the burden on the interpreter?

For example, in the following case:

```<code>def getStringy() {
   def result = ...
   ...

   result
}
</code>```

Groovy will know that we want to return result but isn't it more performant to write that explicitly?

Also, isn't it better to specify the type of the methods arguments when we can? Some people here disagree with me. For example:

```<code>void specialSort(list) {
     // do sorting of a list
}
</code>```

What about semi-colons? What about public keywords? Do these matters affect performance in any way?

答:
Groovy is an interpreted language. Right?

NO

Groovy is a compiled language. Before code is being executed it gets compiled to a normal JVM-compatible bytecode classes just like java code.

Groovy will know that we want to return result but isn't it more
  performant to write that explicitly?

As groovy avoids the boilerplate code you don't need to add the return statement (I personally prefer to write the return for readability purpose).

Groovy understands that whatever is on the last line of the function, you want to return it.

Declaring the type of variable

Groovy is dynamic language.

When using def in Groovy, the actual type holder is Object (so you can assign any object to variables defined with def, and return any kind of object if a method is declared returning def).

What about public keywords?

Groovy considers classes and methods public. So you don’t have to use the public modifier everywhere. Only if it’s not public, you should put a visibility modifier.

As stated above groovy has given us way to avoid the boilerplate code, we can use it that way OR java code is also valid in groovy so it's just matter of taste.

Body:
Groovy is an interpreted language. Right?
So I'm thinking: isn't it better to be verbose when we can to lessen the burden on the interpreter?

For example, in the following case:

def getStringy() {
   def result = ...
   ...

   result
}

Groovy will know that we want to return result but isn't it more performant to write that explicitly?

Also, isn't it better to specify the type of the methods arguments when we can? Some people here disagree with me. For example:

void specialSort(list) {
     // do sorting of a list
}

What about semi-colons? What about public keywords? Do these matters affect performance in any way?


问:
ListView in UWP
I am trying to Align my ListView items in dynamic way without setting explicitly Width for them. The problem i am getting is aligning them the attribute name that is above them. i.e attribute Name should have Coke below it, Quantity should have Integer value number and Subtotal should have floating points below it.
if i resize my Windows the ListView should also change with the respective attribute name but it doesn't. I have tried RelativePanel, ListBox for them but nothing works without explicity giving a width which i want it to be dynamic.

```<code><Grid Grid.Column="2" Margin="5,0,5,0">

            <ScrollViewer VerticalScrollBarVisibility="Hidden">
                <StackPanel>
                    <TextBlock Style="{StaticResource MyTextBlock1}" FontSize="20" HorizontalAlignment="Center" Margin="0,0,0,10">Order Summary</TextBlock>
                    <RelativePanel>
                        <TextBlock Name="ItemName" Style="{StaticResource MyTextBlock1}" FontSize="12">Name</TextBlock>
                        <TextBlock Name="ItemPrice" Style="{StaticResource MyTextBlock1}" FontSize="12" RelativePanel.AlignRightWithPanel="True">SubTotal</TextBlock>
                        <TextBlock Name="ItemQuantity" Style="{StaticResource MyTextBlock1}" Margin="0,0,10,0" FontSize="12" RelativePanel.LeftOf="ItemPrice">Quantity</TextBlock>
                    </RelativePanel>

                    <ListView ItemsSource="{x:Bind dumbList}">
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="local:Dumb">
                                <Grid Width="200">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="3*"/>
                                        <ColumnDefinition Width="1*"/>
                                        <ColumnDefinition Width="1*"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Text="{x:Bind name}"/>
                                    <TextBlock Text="{x:Bind id}" Grid.Column="1"/>
                                    <TextBlock Name="Quatity" Text="{x:Bind price}" Grid.Column="2"/>
                                </Grid>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
</Grid>
</code>```

CLICK HERE!! for the image

答:
Edit:

You can create one item with the DataTemplate layout above the listview.

To avoid setting explicitly the Width, you can set the HorizontalAlignment to Stretch (similiar to Android XML fill_parent) and use Margin.

Example:

```<code><Grid
    HorizontalAlignment="Stretch"
    Margin="12,12,12,12"
    Height="100">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Name"/>
    <TextBlock Text="Quantity" Grid.Column="1"/>
    <TextBlock Text="SubTotal" Grid.Column="2"/>
</Grid>

<ListView ItemsSource="{x:Bind dumbList}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:Dumb">
            <Grid
                HorizontalAlignment="Stretch"
                Margin="12,12,12,12"
                Height="100">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="3*"/>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="1*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{x:Bind name}"/>
                <TextBlock Text="{x:Bind id}" Grid.Column="1"/>
                <TextBlock Name="Quatity" Text="{x:Bind price}" Grid.Column="2"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Title: ListView in UWP

Body:
I am trying to Align my ListView items in dynamic way without setting explicitly Width for them. The problem i am getting is aligning them the attribute name that is above them. i.e attribute Name should have Coke below it, Quantity should have Integer value number and Subtotal should have floating points below it.
if i resize my Windows the ListView should also change with the respective attribute name but it doesn't. I have tried RelativePanel, ListBox for them but nothing works without explicity giving a width which i want it to be dynamic.

<Grid Grid.Column="2" Margin="5,0,5,0">

            <ScrollViewer VerticalScrollBarVisibility="Hidden">
                <StackPanel>
                    <TextBlock Style="{StaticResource MyTextBlock1}" FontSize="20" HorizontalAlignment="Center" Margin="0,0,0,10">Order Summary</TextBlock>
                    <RelativePanel>
                        <TextBlock Name="ItemName" Style="{StaticResource MyTextBlock1}" FontSize="12">Name</TextBlock>
                        <TextBlock Name="ItemPrice" Style="{StaticResource MyTextBlock1}" FontSize="12" RelativePanel.AlignRightWithPanel="True">SubTotal</TextBlock>
                        <TextBlock Name="ItemQuantity" Style="{StaticResource MyTextBlock1}" Margin="0,0,10,0" FontSize="12" RelativePanel.LeftOf="ItemPrice">Quantity</TextBlock>
                    </RelativePanel>

                    <ListView ItemsSource="{x:Bind dumbList}">
                        <ListView.ItemTemplate>
                            <DataTemplate x:DataType="local:Dumb">
                                <Grid Width="200">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="3*"/>
                                        <ColumnDefinition Width="1*"/>
                                        <ColumnDefinition Width="1*"/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Text="{x:Bind name}"/>
                                    <TextBlock Text="{x:Bind id}" Grid.Column="1"/>
                                    <TextBlock Name="Quatity" Text="{x:Bind price}" Grid.Column="2"/>
                                </Grid>
                            </DataTemplate>
                        </ListView.ItemTemplate>
                    </ListView>
</Grid>

CLICK HERE!! for the image

Body:
Edit:

You can create one item with the DataTemplate layout above the listview.

To avoid setting explicitly the Width, you can set the HorizontalAlignment to Stretch (similiar to Android XML fill_parent) and use Margin.

Example:

<Grid
    HorizontalAlignment="Stretch"
    Margin="12,12,12,12"
    Height="100">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="1*"/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Name"/>
    <TextBlock Text="Quantity" Grid.Column="1"/>
    <TextBlock Text="SubTotal" Grid.Column="2"/>
</Grid>

<ListView ItemsSource="{x:Bind dumbList}">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:Dumb">
            <Grid
                HorizontalAlignment="Stretch"
                Margin="12,12,12,12"
                Height="100">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="3*"/>
                    <ColumnDefinition Width="1*"/>
                    <ColumnDefinition Width="1*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{x:Bind name}"/>
                <TextBlock Text="{x:Bind id}" Grid.Column="1"/>
                <TextBlock Name="Quatity" Text="{x:Bind price}" Grid.Column="2"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


问:
Editable Form ReactJS

import React, { Component } from 'react';
let _ = require('lodash');

import {bindActionCreators} from "redux";
import {connect} from 'react-redux';

import {fetchedBeaconsEdit} from '../../actions/';
import {editBeacon} from '../../actions/index';

// TODO - come up with a decent name

class InfoRow extends Component {

    render() {
        return (

              { this.props.beacon === "name"
                || this.props.beacon === "major"
                || this.props.beacon === "minor"
                || this.props.beacon === "beaconType" ?
                  {this.props.beacon}*:
                  {this.props.beacon}
              }

                { this.props.beacon !== "beaconType" &&
                  this.props.beacon !== "uuid" &&
                  this.props.beacon !== "status" &&
                  this.props.beacon !== "store"&&
                  this.props.beacon !== "group" ?

                    <input type="text"
                       className="form-control"
                       defaultValue={this.props.beaconValue}
                       name={this.props.beaconValue}
                       onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}
                    />
:

                    this.props.beacon === "uuid" && this.props.beacon === "status" && this.props.beacon=== "store"?
                  :

                    this.props.beacon === "beaconType"?

                    <select defaultValue={this.props.beaconValue} name={this.props.beaconValue} className="form-control" onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}>

                      <option name="ibeacon">IBEACON</option>
                      <option name="eddystone">EDDYSTONE</option>
                    </select>:this.props.beaconValue

                }

        )
    }
}

class BeaconEdit extends Component {

  constructor(props){
    super(props);
    this.state = {

        };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleInputChange(beacon, value) {

        this.setState({
            [beacon]: value
        });
    }

 handleClick = () =>{
       Object.keys(this.props.ebcn).map((key)=> {
        if (this.state[key] !== undefined) {
          this.props.editBeaconGroup[key]=this.state[key];
        }

       })
        this.props.handleSubmitProp(this.props.editBeaconGroup);
  }

    render() {

        const rows = [];
        let a = this.props.ebcn;

       Object.keys(this.props.ebcn).map((keyName, keyIndex) =>{

          if (keyName === "store" || keyName === "group") {
            return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].name.toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
          }else{
            return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
       }
       });

        return (

                    {rows}

                        <button className="btn btn-sm btn-info btn-size btn-block" onClick={this.handleClick}>Save</button>

        )

    }

}

class BeaconDetailEditComponent extends Component {

  constructor(props){
    super(props);
    this.state = {
        editbeacons: {}
        };
        this.handleSubmit = this.handleSubmit.bind(this);

        this.validateName = this.validateName.bind(this);
        this.validateMajor = this.validateMajor.bind(this);
        this.validateMinor = this.validateMinor.bind(this);
    }

    validateMinor = (minor) => {
      var re = /^[0-9]+$/;
      return re.test(minor);
    }

    validateMajor = (major) => {
      var re = /^[0-9]+$/;
      return re.test(major);
    }

    validateName = (name) => {
      var re = /^[A-Za-z ]+$/;
      return re.test(name);
    };

  handleSubmit (beaconedited) {

    console.log(beaconedited.name);

    if (!this.validateName(beaconedited.name)) {
              alert('Name can not be an integer')
          }

    else if (!this.validateMajor(beaconedited.major)) {
              alert('Major number can only be an integer')
          }

        else if (beaconedited.major.length > 5) {
          alert('Major number can not exceed 5 digits')
        }

        else if (!this.validateMinor(beaconedited.minor)) {
              alert('Minor number can only be an integer')
          }

        else if (beaconedited.major > 65535) {
          alert('Major number can not exceed the limit of 65535')
        }

        else if (beaconedited.minor > 65535) {
          alert('Minor number can not exceed the limit of 65535')
        }

    else {

      this.props.editBeacon(beaconedited, this.props.location.query.id);

  }
    }

  componentWillMount = () => {
        this.props.fetchedBeaconsEdit(this.props.location.query.id);
    };

  render() {

    return (

Edit Beacon Information

                { this.props.ebcn != null?

                <BeaconEdit ebcn={this.props.ebcn} handleSubmitProp={this.handleSubmit} editBeaconGroup={this.state.editbeacons}/>

 :

            }

    )
  }
}

function mapStateToProps(state) {
    return {
        eBeacon: state.eBeacon,
        ebcn: state.beacons
    }

}

function matchDispatchToProps(dispatch){
    return bindActionCreators({editBeacon: editBeacon, fetchedBeaconsEdit: fetchedBeaconsEdit}, dispatch);
}

export default connect(mapStateToProps, matchDispatchToProps)(BeaconDetailEditComponent);```

i had provided the code snippet
what i am doing is
i had fetched the values from the server and were shown in the fields and I'm making this page as editable form
what i want to do is now to take the values changed or changed by the user and to print them in console.
i had applied handleInputChange and its showing changed values while changing but i want to see those values in console on button click as well
how to do it?

答:
First, the manner your are changing the state is not good. You are setting the new state to have only a single attribute which is the name and value of the field which is modified.

Coming to how to print the value of the field you are modifying, you should do a console log in the handle change method.

That said, your code should look like:

```<code>handleInputChange(event) {

    //const {name, value} = event.target;
    //const oldState = this.state;
    //const newState = Object.assign({},oldState,{[name]:value});
    //this.setState(newState);

    this.setState({
        [event.target.name]: event.target.value
    });

    //printing the input name and value as it is being modified.
    console.log(name + ":" + value);

    //if you want to see the value of the current state uncomment the line below
    //console.log("State=" + JSON.stringify(newState));

}

printState = () => {
  console.log("State="+JSON.stringify(this.state));
}
</code>```

For more insight on how to modify objects with assign method see: MDN doc on Object.assign()

If you want to print the current state on clicking the save button then add the onClick attribute to the button as shown in the code below:

```<code><button value="Save" onClick={this.printState}/>
</code>```

Title: Editable Form ReactJS

Body:
import React, { Component } from 'react';
let _ = require('lodash');

import {bindActionCreators} from "redux";
import {connect} from 'react-redux';

import {fetchedBeaconsEdit} from '../../actions/';
import {editBeacon} from '../../actions/index';

// TODO - come up with a decent name

class InfoRow extends Component {

    render() {
        return (

              { this.props.beacon === "name"
                || this.props.beacon === "major"
                || this.props.beacon === "minor"
                || this.props.beacon === "beaconType" ?
                  {this.props.beacon}*:
                  {this.props.beacon}
              }

                { this.props.beacon !== "beaconType" &&
                  this.props.beacon !== "uuid" &&
                  this.props.beacon !== "status" &&
                  this.props.beacon !== "store"&&
                  this.props.beacon !== "group" ?

                    <input type="text"
                       className="form-control"
                       defaultValue={this.props.beaconValue}
                       name={this.props.beaconValue}
                       onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}
                    />
:

                    this.props.beacon === "uuid" && this.props.beacon === "status" && this.props.beacon=== "store"?
                  :

                    this.props.beacon === "beaconType"?

                    <select defaultValue={this.props.beaconValue} name={this.props.beaconValue} className="form-control" onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}>

                      <option name="ibeacon">IBEACON</option>
                      <option name="eddystone">EDDYSTONE</option>
                    </select>:this.props.beaconValue

                }

        )
    }
}

class BeaconEdit extends Component {

  constructor(props){
    super(props);
    this.state = {

        };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleInputChange(beacon, value) {

        this.setState({
            [beacon]: value
        });
    }

 handleClick = () =>{
       Object.keys(this.props.ebcn).map((key)=> {
        if (this.state[key] !== undefined) {
          this.props.editBeaconGroup[key]=this.state[key];
        }

       })
        this.props.handleSubmitProp(this.props.editBeaconGroup);
  }

    render() {

        const rows = [];
        let a = this.props.ebcn;

       Object.keys(this.props.ebcn).map((keyName, keyIndex) =>{

          if (keyName === "store" || keyName === "group") {
            return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].name.toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
          }else{
            return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
       }
       });

        return (

                    {rows}

                        <button className="btn btn-sm btn-info btn-size btn-block" onClick={this.handleClick}>Save</button>

        )

    }

}

class BeaconDetailEditComponent extends Component {

  constructor(props){
    super(props);
    this.state = {
        editbeacons: {}
        };
        this.handleSubmit = this.handleSubmit.bind(this);

        this.validateName = this.validateName.bind(this);
        this.validateMajor = this.validateMajor.bind(this);
        this.validateMinor = this.validateMinor.bind(this);
    }

    validateMinor = (minor) => {
      var re = /^[0-9]+$/;
      return re.test(minor);
    }

    validateMajor = (major) => {
      var re = /^[0-9]+$/;
      return re.test(major);
    }

    validateName = (name) => {
      var re = /^[A-Za-z ]+$/;
      return re.test(name);
    };

  handleSubmit (beaconedited) {

    console.log(beaconedited.name);

    if (!this.validateName(beaconedited.name)) {
              alert('Name can not be an integer')
          }

    else if (!this.validateMajor(beaconedited.major)) {
              alert('Major number can only be an integer')
          }

        else if (beaconedited.major.length > 5) {
          alert('Major number can not exceed 5 digits')
        }

        else if (!this.validateMinor(beaconedited.minor)) {
              alert('Minor number can only be an integer')
          }

        else if (beaconedited.major > 65535) {
          alert('Major number can not exceed the limit of 65535')
        }

        else if (beaconedited.minor > 65535) {
          alert('Minor number can not exceed the limit of 65535')
        }

    else {

      this.props.editBeacon(beaconedited, this.props.location.query.id);

  }
    }

  componentWillMount = () => {
        this.props.fetchedBeaconsEdit(this.props.location.query.id);
    };

  render() {

    return (

Edit Beacon Information

                { this.props.ebcn != null?

                <BeaconEdit ebcn={this.props.ebcn} handleSubmitProp={this.handleSubmit} editBeaconGroup={this.state.editbeacons}/>

 :

            }

    )
  }
}

function mapStateToProps(state) {
    return {
        eBeacon: state.eBeacon,
        ebcn: state.beacons
    }

}

function matchDispatchToProps(dispatch){
    return bindActionCreators({editBeacon: editBeacon, fetchedBeaconsEdit: fetchedBeaconsEdit}, dispatch);
}

export default connect(mapStateToProps, matchDispatchToProps)(BeaconDetailEditComponent);

i had provided the code snippet
what i am doing is
i had fetched the values from the server and were shown in the fields and I'm making this page as editable form
what i want to do is now to take the values changed or changed by the user and to print them in console.
i had applied handleInputChange and its showing changed values while changing but i want to see those values in console on button click as well
how to do it?

Body:
First, the manner your are changing the state is not good. You are setting the new state to have only a single attribute which is the name and value of the field which is modified.

Coming to how to print the value of the field you are modifying, you should do a console log in the handle change method.

That said, your code should look like:

handleInputChange(event) {

    //const {name, value} = event.target;
    //const oldState = this.state;
    //const newState = Object.assign({},oldState,{[name]:value});
    //this.setState(newState);

    this.setState({
        [event.target.name]: event.target.value
    });

    //printing the input name and value as it is being modified.
    console.log(name + ":" + value);

    //if you want to see the value of the current state uncomment the line below
    //console.log("State=" + JSON.stringify(newState));

}

printState = () => {
  console.log("State="+JSON.stringify(this.state));
}

For more insight on how to modify objects with assign method see: MDN doc on Object.assign()

If you want to print the current state on clicking the save button then add the onClick attribute to the button as shown in the code below:

<button value="Save" onClick={this.printState}/>


问:
create new field based on multiple resident tables
Given multiple in-resident tables, I'd like to create a new field based on fields in different tables.

```<code>table1:
LOAD * INLINE [
id1,val1
a1,car1
a2,car1
];

table2:
LOAD * INLINE [
id2,id1,val2
b1,a1,type1
b2,a2,type2
];

table3:
LOAD * INLINE [
id3,id2,val3
c1,b1,mfr1
c2,b2,mfr2
];
</code>```

For the sake of argument, assume table1 has ~1M rows, table2 ~1K rows, and table3 ~10 rows. I'd like to create a new field that is either added to table1 or perhaps in a new table linked by id1, resulting in:

```<code>id1  val1  newval
a1   car1  car1type1mfr1
a2   car2  car2type2mfr2
</code>```

Efforts:

```<code>newtable:
load val1 & val2 & val3 as newval;
</code>```

No errors but no newtable or newval.

```<code>newtable:
left join (table2)
load val1&val2 as newval resident table1;
</code>```

Errs with Field not found - <val2>. (Obviously I want to extend this to include table3, but if I can't do it with 2 tables then 3 just won't work.

The real data includes seven tables for this new field (lots of foreign keys). The data is being loaded from QVDs (the data is shared across multiple QVWs), closely mimicking a SQL database; none of the tables are row-wise redundant, so combining db tables into a single QVD table may be inefficient. (Plus refreshing the data is incredibly easier one table at a time.) A colleague suggested I load-join each of the QVDs into one huge table, but that doesn't seem right (nor have I successfully chain-joined even a few tables).

Using QV 12.0 desktop on win10-x64 for deployment on QVS.

答:
@TheBudac's was part of the way there, but it only merged two of the three. Most of the problems were stemming from incorrect multi-table joins. My confusion was in the "join" syntax in Qlik; the docs make sense to me now that I see what's happening, but it wasn't as obvious to me initially.

Here's what eventually worked best for me:

```<code>temptable:
load id1 as id1a, val1 as val1a
resident table1;
left join (temptable)
load id2 as id2a, id1 as id1a, val2 as val2a
resident table2;
left join (temptable)
load id2 as id2a, val3 as val3a
resident table3;

newtable:
load id1a as id1,
  val1a & val2a & val3a as newval
resident temptable;

drop table temptable;
</code>```

This produced these tables:

and this tree:

Quick walk-through:

Because I'm using left join, I start with the largest table; other joins would dictate different starting condition requirements. In my case, table1 was representing the largest, so I start with that:

```<code>temptable:
load id1 as id1a, val1 as val1a
resident table1;
</code>```

Each join should be against the temporary table we're working on. Renaming variables is important so that Qlik doesn't create unnecessary synthetic keys.

```<code>left join (temptable)
load id2 as id2a, id1 as id1a, val2 as val2a
resident table2;
</code>```

The use of resident is important in that it does not re-query (SQL) or re-load (QVD or other file).

Repeat with the third and further tables, always joining against temptable with the new table.

Now we use that temporary table to create our new table. You can choose to augment table1 with this data instead (certainly feasible), but for me since I'm generating several new calculated fields (not shown here), it made sense to keep them logically separated.

```<code>newtable:
load id1a as id1,
  val1a & val2a & val3a as newval
resident temptable;

drop table temptable;
</code>```

Note that I rename the relevant key back to its original value so that this table correctly links to table. Dropping the temporary table helps clean things up, but it does no harm to keep it around (and doing so helps in debugging/learning).

Body:
Given multiple in-resident tables, I'd like to create a new field based on fields in different tables.

table1:
LOAD * INLINE [
id1,val1
a1,car1
a2,car1
];

table2:
LOAD * INLINE [
id2,id1,val2
b1,a1,type1
b2,a2,type2
];

table3:
LOAD * INLINE [
id3,id2,val3
c1,b1,mfr1
c2,b2,mfr2
];

For the sake of argument, assume table1 has ~1M rows, table2 ~1K rows, and table3 ~10 rows. I'd like to create a new field that is either added to table1 or perhaps in a new table linked by id1, resulting in:

id1  val1  newval
a1   car1  car1type1mfr1
a2   car2  car2type2mfr2

Efforts:

newtable:
load val1 & val2 & val3 as newval;

No errors but no newtable or newval.

newtable:
left join (table2)
load val1&val2 as newval resident table1;

Errs with Field not found - <val2>. (Obviously I want to extend this to include table3, but if I can't do it with 2 tables then 3 just won't work.

The real data includes seven tables for this new field (lots of foreign keys). The data is being loaded from QVDs (the data is shared across multiple QVWs), closely mimicking a SQL database; none of the tables are row-wise redundant, so combining db tables into a single QVD table may be inefficient. (Plus refreshing the data is incredibly easier one table at a time.) A colleague suggested I load-join each of the QVDs into one huge table, but that doesn't seem right (nor have I successfully chain-joined even a few tables).

Using QV 12.0 desktop on win10-x64 for deployment on QVS.

Body:
@TheBudac's was part of the way there, but it only merged two of the three. Most of the problems were stemming from incorrect multi-table joins. My confusion was in the "join" syntax in Qlik; the docs make sense to me now that I see what's happening, but it wasn't as obvious to me initially.

Here's what eventually worked best for me:

temptable:
load id1 as id1a, val1 as val1a
resident table1;
left join (temptable)
load id2 as id2a, id1 as id1a, val2 as val2a
resident table2;
left join (temptable)
load id2 as id2a, val3 as val3a
resident table3;

newtable:
load id1a as id1,
  val1a & val2a & val3a as newval
resident temptable;

drop table temptable;

This produced these tables:

and this tree:

Quick walk-through:

Because I'm using left join, I start with the largest table; other joins would dictate different starting condition requirements. In my case, table1 was representing the largest, so I start with that:

temptable:
load id1 as id1a, val1 as val1a
resident table1;

Each join should be against the temporary table we're working on. Renaming variables is important so that Qlik doesn't create unnecessary synthetic keys.

left join (temptable)
load id2 as id2a, id1 as id1a, val2 as val2a
resident table2;

The use of resident is important in that it does not re-query (SQL) or re-load (QVD or other file).

Repeat with the third and further tables, always joining against temptable with the new table.

Now we use that temporary table to create our new table. You can choose to augment table1 with this data instead (certainly feasible), but for me since I'm generating several new calculated fields (not shown here), it made sense to keep them logically separated.

newtable:
load id1a as id1,
  val1a & val2a & val3a as newval
resident temptable;

drop table temptable;

Note that I rename the relevant key back to its original value so that this table correctly links to table. Dropping the temporary table helps clean things up, but it does no harm to keep it around (and doing so helps in debugging/learning).


问:
SparkSQL on pyspark: how to generate time series?
I'm using SparkSQL on pyspark to store some PostgreSQL tables into DataFrames and then build a query that generates several time series based on a start and stop columns of type date.

Suppose that my_table contains:

```<code> start      | stop
-------------------------
 2000-01-01 | 2000-01-05
 2012-03-20 | 2012-03-23
</code>```

In PostgreSQL it's very easy to do that:

```<code>SELECT generate_series(start, stop, '1 day'::interval)::date AS dt FROM my_table
</code>```

and it will generate this table:

```<code> dt
------------
 2000-01-01
 2000-01-02
 2000-01-03
 2000-01-04
 2000-01-05
 2012-03-20
 2012-03-21
 2012-03-22
 2012-03-23
</code>```

but how to do that using plain SparkSQL? Will it be necessary to use UDFs or some DataFrame methods?

答:
Suppose you have dataframe df from spark sql, Try this

```<code>from pyspark.sql.functions as F
from pyspark.sql.types as T

def timeseriesDF(start, total):
    series = [start]
    for i xrange( total-1 ):
        series.append(
            F.date_add(series[-1], 1)
        )
    return series

df.withColumn("t_series", F.udf(
                timeseriesDF,
                T.ArrayType()
            ) ( df.start, F.datediff( df.start, df.stop ) )
    ).select(F.explode("t_series")).show()
</code>```

Body:
I'm using SparkSQL on pyspark to store some PostgreSQL tables into DataFrames and then build a query that generates several time series based on a start and stop columns of type date.

Suppose that my_table contains:

 start      | stop
-------------------------
 2000-01-01 | 2000-01-05
 2012-03-20 | 2012-03-23

In PostgreSQL it's very easy to do that:

SELECT generate_series(start, stop, '1 day'::interval)::date AS dt FROM my_table

and it will generate this table:

 dt
------------
 2000-01-01
 2000-01-02
 2000-01-03
 2000-01-04
 2000-01-05
 2012-03-20
 2012-03-21
 2012-03-22
 2012-03-23

but how to do that using plain SparkSQL? Will it be necessary to use UDFs or some DataFrame methods?

Body:
Suppose you have dataframe df from spark sql, Try this

from pyspark.sql.functions as F
from pyspark.sql.types as T

def timeseriesDF(start, total):
    series = [start]
    for i xrange( total-1 ):
        series.append(
            F.date_add(series[-1], 1)
        )
    return series

df.withColumn("t_series", F.udf(
                timeseriesDF,
                T.ArrayType()
            ) ( df.start, F.datediff( df.start, df.stop ) )
    ).select(F.explode("t_series")).show()


问:
Find documents with empty string value on elasticsearch
I've been trying to filter with elasticsearch only those documents that contains an empty string in its body. So far I'm having no luck.

Before I go on, I should mention that I've already tried the many "solutions" spread around the Interwebz and StackOverflow.

So, below is the query that I'm trying to run, followed by its counterparts:

```<code>{
    "query": {
        "filtered":{
            "filter": {
                "bool": {
                    "must_not": [
                        {
                            "missing":{
                                "field":"_textContent"
                            }
                        }
                    ]
                }
            }
        }
    }
}
</code>```

I've also tried the following:

```<code> {
    "query": {
        "filtered":{
            "filter": {
                "bool": {
                    "must_not": [
                        {
                            "missing":{
                                "field":"_textContent",
                                "existence":true,
                                "null_value":true
                            }
                        }
                    ]
                }
            }
        }
    }
}
</code>```

And the following:

```<code>   {
    "query": {
        "filtered":{
            "filter": {
                    "missing": {"field": "_textContent"}
            }
        }
    }
}
</code>```

None of the above worked. I get an empty result set when I know for sure that there are records that contains an empty string field.

If anyone can provide me with any help at all, I'll be very grateful.

Thanks!

答:
For those of you using elastic search 5.2 or above, and still stuck. Easiest way is to reindex your data correctly with the keyword type. Then all the searches for empty values worked. Like this:

```<code>"query": {
    "term": {"MY_FIELD_TO_SEARCH": ""}
}
</code>```

Actually, when I reindex my database and rerun the query. It worked =)

The problem was that my field was type: text and NOT a keyword. Changed the index to keyword and reindexed:

```<code>curl -X PUT https://username:password@host.io:9200/mycoolindex

curl -X PUT https://user:pass@host.io:9200/mycoolindex/_mapping/mycooltype -d '{
  "properties": {
            "MY_FIELD_TO_SEARCH": {
                    "type": "keyword"
                },
}'

curl -X PUT https://username:password@host.io:9200/_reindex -d '{
 "source": {
   "index": "oldindex"
 },
 "dest": {
    "index": "mycoolindex"
 }
}'
</code>```

I hope this helps someone who was as stuck as I was finding those empty values.

Body:
I've been trying to filter with elasticsearch only those documents that contains an empty string in its body. So far I'm having no luck.

Before I go on, I should mention that I've already tried the many "solutions" spread around the Interwebz and StackOverflow.

So, below is the query that I'm trying to run, followed by its counterparts:

{
    "query": {
        "filtered":{
            "filter": {
                "bool": {
                    "must_not": [
                        {
                            "missing":{
                                "field":"_textContent"
                            }
                        }
                    ]
                }
            }
        }
    }
}

I've also tried the following:

 {
    "query": {
        "filtered":{
            "filter": {
                "bool": {
                    "must_not": [
                        {
                            "missing":{
                                "field":"_textContent",
                                "existence":true,
                                "null_value":true
                            }
                        }
                    ]
                }
            }
        }
    }
}

And the following:

   {
    "query": {
        "filtered":{
            "filter": {
                    "missing": {"field": "_textContent"}
            }
        }
    }
}

None of the above worked. I get an empty result set when I know for sure that there are records that contains an empty string field.

If anyone can provide me with any help at all, I'll be very grateful.

Thanks!

Body:
For those of you using elastic search 5.2 or above, and still stuck. Easiest way is to reindex your data correctly with the keyword type. Then all the searches for empty values worked. Like this:

"query": {
    "term": {"MY_FIELD_TO_SEARCH": ""}
}

Actually, when I reindex my database and rerun the query. It worked =)

The problem was that my field was type: text and NOT a keyword. Changed the index to keyword and reindexed:

curl -X PUT https://username:password@host.io:9200/mycoolindex

curl -X PUT https://user:pass@host.io:9200/mycoolindex/_mapping/mycooltype -d '{
  "properties": {
            "MY_FIELD_TO_SEARCH": {
                    "type": "keyword"
                },
}'

curl -X PUT https://username:password@host.io:9200/_reindex -d '{
 "source": {
   "index": "oldindex"
 },
 "dest": {
    "index": "mycoolindex"
 }
}'

I hope this helps someone who was as stuck as I was finding those empty values.


问:
postmark mail provider says. mails "In queue" ?
I am currently working on postmark mail provider. it was working for me good. but now it is not working. it says " in queue. This email uses a Postmark Template, but has not yet been rendered by our system. Please check again shortly." please explain me.</p>

答: I'm a developer on Postmark. When you're using a Postmark Template, we need to take the template model you submit, construct HTML and Text from it, and then send it through our normal sending pipeline. This typically happens so fast that you'll rarely see the "In Queue" status, if you're seeing this frequently, you should contact support via https://support.postmarkapp.com and we can provide more specific help for your case.</p>