答:
1. In your adapter, take two variable which can hold currentExpandable and previousExpandable positions.

```<code>   private var previousExpandedPosition = -1
   private var currentExpandedPosition = -1
</code>```

2.  Initialize them where you are expanding your row. In my case, I am expanding the view on click of that row. Hence, I am assigning it in my ViewHolder.

```<code>inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        init {
            itemView.myExpandableView.setOnClickListener {
                previousExpandedPosition = currentExpandedPosition
                currentExpandedPosition = adapterPosition

                if (previousExpandedPosition == currentExpandedPosition) {
                    currentExpandedPosition = -1
                }
                notifyItemChanged(previousExpandedPosition)
                notifyItemChanged(currentExpandedPosition)
            }
        }
    }
</code>```

3. In your onBindViewHolder method, if the position is currently expanded then view it Expanded otherwise collapse it.

```<code>if (position == currentExpandedPosition) {
            // showExpandedView
        } else {
            // showCollapsedView
        }
</code>```

Title: How to reiterate through all the view in recyclerview?

Body: I want to achieve expandable item inside RecyclerView and when one item is expanded the other expanded item must automatically close, can someone please help?

Body:
1. In your adapter, take two variable which can hold currentExpandable and previousExpandable positions.

   private var previousExpandedPosition = -1
   private var currentExpandedPosition = -1

2.  Initialize them where you are expanding your row. In my case, I am expanding the view on click of that row. Hence, I am assigning it in my ViewHolder.

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        init {
            itemView.myExpandableView.setOnClickListener {
                previousExpandedPosition = currentExpandedPosition
                currentExpandedPosition = adapterPosition

                if (previousExpandedPosition == currentExpandedPosition) {
                    currentExpandedPosition = -1
                }
                notifyItemChanged(previousExpandedPosition)
                notifyItemChanged(currentExpandedPosition)
            }
        }
    }

3. In your onBindViewHolder method, if the position is currently expanded then view it Expanded otherwise collapse it.

if (position == currentExpandedPosition) {
            // showExpandedView
        } else {
            // showCollapsedView
        }


来源: stackexchange

问:
notifyDataSetChange not working from custom adapter
When I repopulate my ListView, I call a specific method from my Adapter.

Problem:

When I call updateReceiptsList from my Adapter, the data is refreshed, but my ListView doesn't reflect the change.

Question:

Why doesn't my ListView show the new data when I call notifyDataSetChanged?

Adapter:

```<code>public class ReceiptListAdapter extends BaseAdapter {

    public List<Receipt> receiptlist;
    private Context context;
    private LayoutInflater inflater;
    private DateHelpers dateH;

    public ReceiptListAdapter(Activity activity, Context mcontext, List<Receipt> rl) {
        context = mcontext;
        receiptlist = rl;
        Collections.reverse(receiptlist);
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        dateH = new DateHelpers();
    }

    @Override
    public int getCount() {
        try {
            int size = receiptlist.size();
            return size;
        } catch(NullPointerException ex) {
            return 0;
        }
    }

    public void updateReceiptsList(List<Receipt> newlist) {
        receiptlist = newlist;
        this.notifyDataSetChanged();
    }

    @Override
    public Receipt getItem(int i) {
        return receiptlist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return receiptlist.get(i).getReceiptId() ;
    }

    private String getPuntenString(Receipt r) {
        if(r.getPoints().equals("1")) {
            return "1 punt";
        }
        return r.getPoints()+" punten";
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;

        final Receipt receipt = receiptlist.get(position);
        ReceiptViewHolder receiptviewholder;
        Typeface tf_hn = Typeface.createFromAsset(context.getAssets(), "helveticaneue.ttf");
        Typeface tf_hn_bold = Typeface.createFromAsset(context.getAssets(), "helveticaneuebd.ttf");

        if (vi == null) { //convertview==null
            receiptviewholder = new ReceiptViewHolder();
            vi = inflater.inflate(R.layout.view_listitem_receipt, null);
            vi.setOnClickListener(null);
            vi.setOnLongClickListener(null);
            vi.setLongClickable(false);
            receiptviewholder.shop = (TextView) vi.findViewById(R.id.tv_listitemreceipt_shop);
            receiptviewholder.date = (TextView) vi.findViewById(R.id.tv_listitemreceipt_date);
            receiptviewholder.price = (TextView) vi.findViewById(R.id.tv_listitemreceipt_price);
            receiptviewholder.points = (TextView) vi.findViewById(R.id.tv_listitemreceipt_points);
            receiptviewholder.shop.setTypeface(tf_hn_bold);
            receiptviewholder.price.setTypeface(tf_hn_bold);
            vi.setTag(receiptviewholder);
        }else{//convertview is not null
            receiptviewholder = (ReceiptViewHolder)vi.getTag();
        }

        receiptviewholder.shop.setText(receipt.getShop());
        receiptviewholder.date.setText(dateH.timestampToDateString(Long.parseLong(receipt.getPurchaseDate())));
        receiptviewholder.price.setText("€ "+receipt.getPrice());
        receiptviewholder.points.setText(getPuntenString(receipt));

        vi.setClickable(false);
        return vi;
    }

    public static class ReceiptViewHolder {
        public TextView shop;
        public TextView date;
        public TextView price;
        public TextView points;
    }

    public Object getFilter() {
        // XXX Auto-generated method stub
        return null;
    }

}
</code>```

--EDIT:

found Workaround

Just to have some functional code i do now:

```<code>listview.setAdapter( new ReceiptListAdapter(activity,mcontext, -new dataset-);
</code>```

Works, but not how it is supposed to work.

答:
If by any chance you landed on this thread and wondering why adapter.invaidate() or adapter.clear() methods are not present in your case then maybe because you might be using RecyclerView.Adapter instead of BaseAdapter which is used by the asker of this question. If clearing the list or arraylist not resolving your problem then it may happen that you are making two or more instances of the adapter for ex.:

MainActivity

...

adapter = new CustomAdapter(list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);

...
```

<p>and<br>
<em>SomeFragment</em></p>

<pre class="lang-java prettyprint-override"><code>...

adapter = new CustomAdapter(newList);
adapter.notifyDataSetChanged();

...
</code>```

If in the second case you are expecting a change in the list of inflated views in recycler view then it is not gonna happen as in the second time a new instance of the adapter is created which is not attached to the recycler view. Setting notifyDataSetChanged in the second adapter is not gonna change the content of recycer view. For that make a new instance of the recycler view in SomeFragment and attach it to the new instance of the adapter.

SomeFragment

...

recyclerView = new RecyclerView();
adapter = new CustomAdapter();
recyclerView.setAdapter(adapter);

...
```

Although, I don't recommend making multiple instances of the same adapter and recycler view.

ContentLicense: CC BY-SA 3.0

Body:
When I repopulate my ListView, I call a specific method from my Adapter.

Problem:

When I call updateReceiptsList from my Adapter, the data is refreshed, but my ListView doesn't reflect the change.

Question:

Why doesn't my ListView show the new data when I call notifyDataSetChanged?

Adapter:

public class ReceiptListAdapter extends BaseAdapter {

    public List<Receipt> receiptlist;
    private Context context;
    private LayoutInflater inflater;
    private DateHelpers dateH;

    public ReceiptListAdapter(Activity activity, Context mcontext, List<Receipt> rl) {
        context = mcontext;
        receiptlist = rl;
        Collections.reverse(receiptlist);
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        dateH = new DateHelpers();
    }

    @Override
    public int getCount() {
        try {
            int size = receiptlist.size();
            return size;
        } catch(NullPointerException ex) {
            return 0;
        }
    }

    public void updateReceiptsList(List<Receipt> newlist) {
        receiptlist = newlist;
        this.notifyDataSetChanged();
    }

    @Override
    public Receipt getItem(int i) {
        return receiptlist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return receiptlist.get(i).getReceiptId() ;
    }

    private String getPuntenString(Receipt r) {
        if(r.getPoints().equals("1")) {
            return "1 punt";
        }
        return r.getPoints()+" punten";
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;

        final Receipt receipt = receiptlist.get(position);
        ReceiptViewHolder receiptviewholder;
        Typeface tf_hn = Typeface.createFromAsset(context.getAssets(), "helveticaneue.ttf");
        Typeface tf_hn_bold = Typeface.createFromAsset(context.getAssets(), "helveticaneuebd.ttf");

        if (vi == null) { //convertview==null
            receiptviewholder = new ReceiptViewHolder();
            vi = inflater.inflate(R.layout.view_listitem_receipt, null);
            vi.setOnClickListener(null);
            vi.setOnLongClickListener(null);
            vi.setLongClickable(false);
            receiptviewholder.shop = (TextView) vi.findViewById(R.id.tv_listitemreceipt_shop);
            receiptviewholder.date = (TextView) vi.findViewById(R.id.tv_listitemreceipt_date);
            receiptviewholder.price = (TextView) vi.findViewById(R.id.tv_listitemreceipt_price);
            receiptviewholder.points = (TextView) vi.findViewById(R.id.tv_listitemreceipt_points);
            receiptviewholder.shop.setTypeface(tf_hn_bold);
            receiptviewholder.price.setTypeface(tf_hn_bold);
            vi.setTag(receiptviewholder);
        }else{//convertview is not null
            receiptviewholder = (ReceiptViewHolder)vi.getTag();
        }

        receiptviewholder.shop.setText(receipt.getShop());
        receiptviewholder.date.setText(dateH.timestampToDateString(Long.parseLong(receipt.getPurchaseDate())));
        receiptviewholder.price.setText("€ "+receipt.getPrice());
        receiptviewholder.points.setText(getPuntenString(receipt));

        vi.setClickable(false);
        return vi;
    }

    public static class ReceiptViewHolder {
        public TextView shop;
        public TextView date;
        public TextView price;
        public TextView points;
    }

    public Object getFilter() {
        // XXX Auto-generated method stub
        return null;
    }

}

--EDIT:

found Workaround

Just to have some functional code i do now:

listview.setAdapter( new ReceiptListAdapter(activity,mcontext, -new dataset-);

Works, but not how it is supposed to work.

Body:
If by any chance you landed on this thread and wondering why adapter.invaidate() or adapter.clear() methods are not present in your case then maybe because you might be using RecyclerView.Adapter instead of BaseAdapter which is used by the asker of this question. If clearing the list or arraylist not resolving your problem then it may happen that you are making two or more instances of the adapter for ex.:

MainActivity

...

adapter = new CustomAdapter(list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);

...

and

SomeFragment

...

adapter = new CustomAdapter(newList);
adapter.notifyDataSetChanged();

...

If in the second case you are expecting a change in the list of inflated views in recycler view then it is not gonna happen as in the second time a new instance of the adapter is created which is not attached to the recycler view. Setting notifyDataSetChanged in the second adapter is not gonna change the content of recycer view. For that make a new instance of the recycler view in SomeFragment and attach it to the new instance of the adapter.

SomeFragment

...

recyclerView = new RecyclerView();
adapter = new CustomAdapter();
recyclerView.setAdapter(adapter);

...

Although, I don't recommend making multiple instances of the same adapter and recycler view.

ContentLicense: CC BY-SA 4.0


问:
I can't install udev on plain ubuntu 14.04
I've plain Ubuntu 14.04 Server (64-bit) installation.

When use:

```<code>sudo apt-get update
</code>```

Print this error:

```<code>....
Hit http://security.ubuntu.com trusty-security/universe Translation-en
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.
</code>```

After removing tmp.i /var/lib/dpkg/updates# sudo rm tmp.i apt-get update went OK but...

When I tried 'sudo apt-get upgrade':

```<code>Fetched 534 kB in 4s (112 kB/s)
Reading package lists... Done
root@vps****:/# sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] Y
Setting up udev (204-5ubuntu20.9) ...
 * udev requires hotplug support, not started
   ...fail!
invoke-rc.d: initscript udev, action "restart" failed.
dpkg: error processing package udev (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 udev
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

I can't find any solution for that so far on web, tried many ways but nothing worked...

答:
For people who are getting this on OVH servers, the above hacks are no longer needed!

This answer by proxy should work:

```<code>$ apt-get download udev
$ sudo dpkg -i --force-confmiss udev_*_amd64.deb
$ sudo apt-get upgrade
</code>```

Worked for me. For more info go to Dimitri's comment in Ubuntu's bug tracker.

It seems this is because OVH doesn't put /etc/init/udev.conf in your system. 10/10

Body:
I've plain Ubuntu 14.04 Server (64-bit) installation.

When use:

sudo apt-get update

Print this error:

....
Hit http://security.ubuntu.com trusty-security/universe Translation-en
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

After removing tmp.i /var/lib/dpkg/updates# sudo rm tmp.i apt-get update went OK but...

When I tried 'sudo apt-get upgrade':

Fetched 534 kB in 4s (112 kB/s)
Reading package lists... Done
root@vps****:/# sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] Y
Setting up udev (204-5ubuntu20.9) ...
 * udev requires hotplug support, not started
   ...fail!
invoke-rc.d: initscript udev, action "restart" failed.
dpkg: error processing package udev (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 udev
E: Sub-process /usr/bin/dpkg returned an error code (1)

I can't find any solution for that so far on web, tried many ways but nothing worked...

Body:
For people who are getting this on OVH servers, the above hacks are no longer needed!

This answer by proxy should work:

$ apt-get download udev
$ sudo dpkg -i --force-confmiss udev_*_amd64.deb
$ sudo apt-get upgrade

Worked for me. For more info go to Dimitri's comment in Ubuntu's bug tracker.

It seems this is because OVH doesn't put /etc/init/udev.conf in your system. 10/10


问:
I want to delay the animation on my div so that they could appear one after the other, how can i do that?
I have a list offers made by a user which I want to display using the slideInLeft animation I've found online in this repo/the animations in action but I want to make it that each offers arrives 100ms after the first one. How can I do that?

My code would look something like this:

```<code><div *ngFor="let offer of offers">
      <div class="animated infinite slideInLeft delay-2s">offer data</div>
    </div>
</code>```

答:
```<code><div *ngFor="let offer of offers; let i= index;">
  <div class=`animated infinite slideInLeft delay-${i}`>offer data</div>
</div>
</code>```

take each offer index and add it to class  the number to delay- class!
now u can add for each class a delay!

Body:
I have a list offers made by a user which I want to display using the slideInLeft animation I've found online in this repo/the animations in action but I want to make it that each offers arrives 100ms after the first one. How can I do that?

My code would look something like this:

offer data

Body:
<div *ngFor="let offer of offers; let i= index;">
  <div class=`animated infinite slideInLeft delay-${i}`>offer data</div>
</div>

take each offer index and add it to class  the number to delay- class!
now u can add for each class a delay!


问:
Multi threading with third party library in C++
I'm using two functions from a third party library currently in my application. The first function, aka .SourceMeasure basically collecting data from some hardware while the second function, aka .ComputeErrors is purely calculation based on the data collected from the first function. And the measure-calculate executions will be looped for 5 times.
I'm thinking create a multi thread to move the .ComputeErrors to the worker thread to save some times.
Will there be a issue if the.SourceMeasure is in main thread and the .ComputeErrors in the worker thread and both of them coming from the same library?</p>

```<code>//The execution is something like this..
for (int i=0; z < 5; z++)
{
   Lib.SourceMeasure (data)
   Lib.ComputeErorrs (data)  //Want to put this in a separate thread
}
</code>```

答:
I don't know, which library you're using, but it's almost sure that you can not start Lib.ComputeErorrs() until Lib.SourceMeasure() is still running, on the same data set.

What you can do is to set up a queue and two threads:

The "measure thread":

create a data item

call Lib.SourceMeasure() on it

push data to a FIFO queue

The "compute thread":

hang on some if the queue is empty

pick a data item from the queue

call Lib.ComputeErorrs() with the data

On result, the measurement and the computation will run parallel (but not the same items, measurement will be some ahead). All you need to find is a thread-safe queue.

Body:
I'm using two functions from a third party library currently in my application. The first function, aka .SourceMeasure basically collecting data from some hardware while the second function, aka .ComputeErrors is purely calculation based on the data collected from the first function. And the measure-calculate executions will be looped for 5 times.
I'm thinking create a multi thread to move the .ComputeErrors to the worker thread to save some times.
Will there be a issue if the.SourceMeasure is in main thread and the .ComputeErrors in the worker thread and both of them coming from the same library?

//The execution is something like this..
for (int i=0; z < 5; z++)
{
   Lib.SourceMeasure (data)
   Lib.ComputeErorrs (data)  //Want to put this in a separate thread
}


问:
I want to learn how to make customize xpath for selenium java
I want to learn how to make customize xpath
I tried this

```<code>//*[@class='btn btn-primary goliveBtn btn-lg float-right']//*[@text()="Go Live"]
</code>```

but its not working

答:
I got your point.You are probably looking after this.

```<code>//*[@class='btn btn-primary goliveBtn btn-lg float-right'][contains(.,"Go Live")]
</code>```

OR use normalize-space

```<code>//*[@class='btn btn-primary goliveBtn btn-lg float-right'][normalize-space(text())='Go Live']
</code>```

Body:
I want to learn how to make customize xpath
I tried this

//*[@class='btn btn-primary goliveBtn btn-lg float-right']//*[@text()="Go Live"]

but its not working

Body:
I got your point.You are probably looking after this.

//*[@class='btn btn-primary goliveBtn btn-lg float-right'][contains(.,"Go Live")]

OR use normalize-space

//*[@class='btn btn-primary goliveBtn btn-lg float-right'][normalize-space(text())='Go Live']


问:
Why image upload is not displaying the image preview text?
I have customized my form upload button and hide the input field via css display:none but when I select an image the input is not showing the preview text!

I want to display the selected image preview text so that user know he has selected an image!

HTML:

```<code><div class="form-group">
    <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
    <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
    <span>No file chosen</span>
</div>
</code>```

CSS:

```<code>.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}
input[type=file] {
    display: none;
}
</code>```

 input[type=file]{
    display:none;
}
 .custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
 <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
 <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">                        <span>No file chosen</span>
</div></code>```

UPDATE: I tried all these solutions (How to display file name for custom styled input file using jquery?) but none worked for me. In my scenario I have two upload buttons one is before image upload and second is after image upload as shown in video.

Still I can't display the preview text in front of the upload buttons.

答:
Just add a new function in input type file on onchange event. Please find the attached code.

 input[type=file]{
    display:none;
}
 .custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
 <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
  <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image" onChange="((e)=>{
file = e.target.files.item(0);
var fr = new FileReader;
fr.onloadend =(imgsrc)=>{
  imgsrc = imgsrc.target.result; // file reader
var img = document.createElement('img');
    img.src =imgsrc;
this.nextSibling.nextSibling.innerHTML='';
this.nextSibling.nextSibling.appendChild(img);
};
fr.readAsDataURL(file);
})(event)">
<span>No file chosen</span>
</div></code>```

Body:
I have customized my form upload button and hide the input field via css display:none but when I select an image the input is not showing the preview text!

I want to display the selected image preview text so that user know he has selected an image!

HTML:

     Before Image*
    <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">
    No file chosen

CSS:

.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}
input[type=file] {
    display: none;
}

 input[type=file]{
    display:none;
}
 .custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

  Before Image*
 <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image">                        No file chosen

UPDATE: I tried all these solutions (How to display file name for custom styled input file using jquery?) but none worked for me. In my scenario I have two upload buttons one is before image upload and second is after image upload as shown in video.

Still I can't display the preview text in front of the upload buttons.

Body:
Just add a new function in input type file on onchange event. Please find the attached code.

 input[type=file]{
    display:none;
}
 .custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

<div class="form-group">
 <label for="before_image" class="custom-file-upload"><i class="fa fa-cloud-upload"></i> Before Image*</label>
  <input type="file" id="before_image" name="before_image" class="form-group" placeholder="Before Image" data-bind="value: before_image" onChange="((e)=>{
file = e.target.files.item(0);
var fr = new FileReader;
fr.onloadend =(imgsrc)=>{
  imgsrc = imgsrc.target.result; // file reader
var img = document.createElement('img');
    img.src =imgsrc;
this.nextSibling.nextSibling.innerHTML='';
this.nextSibling.nextSibling.appendChild(img);
};
fr.readAsDataURL(file);
})(event)">
<span>No file chosen</span>
</div>


问:
How to set image path in django template
I'm trying to display already stored database image in template. But here i'm getting only name of the image. How to solve this, Where i did mistake.

models.py

```<code>class Images(models.Model):
    image = models.ImageField(upload_to='images', blank=True, null=True)
</code>```

settings.py

```<code>STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'
</code>```

urls.py

```<code>urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

views.py

```<code>def display(request):
     myimages_objs = Images.objects.all().values()
     for i in myimages_objs :
          myimages_objs = i['image']
          return render(request, 'index.html', {'myimages_obj ': myimages_objs })
</code>```

index.html

```<code><div class="divi">
   <img src="{{ myimages_obj }}" alt="image">
</div>
</code>```

答:
I don't understand why you are returning the objects inside the for loop, this causes only a single image to be displayed in the template. Instead of doing this, you can pass all the image objects in the template, then loop through the objects in the template to display the images.

You can change your view as:

```<code>def display(request):
    myimages_objs = Images.objects.all() # get all the images
    return render(request, 'index.html', {'myimages_objs':myimages_objs})
</code>```

Then in your template:

```<code><div class="divi">
    {% for item in myimages_objs %} //loop through all the images
        <img src="{{ item.image.url }}" alt="image">
    {% endfor %}
</div>
</code>```

Edit:

Change the upload_to to upload_to="images/".

As far as I am concerned, your images are not being stored inside the images folder as you have missed the backslash(which represents a folder name). So, the images are being saved inside the media folder.

But the image url is something like project_path/media/images/something.jpg which cannot be found as the images are not being saved inside the images folder.

Change the field as stated for new images to be stored in the specified folder. For old images, copy them to the images folder manually.

I hope this will help.

Body:
I'm trying to display already stored database image in template. But here i'm getting only name of the image. How to solve this, Where i did mistake.

models.py

class Images(models.Model):
    image = models.ImageField(upload_to='images', blank=True, null=True)

settings.py

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

urls.py

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

def display(request):
     myimages_objs = Images.objects.all().values()
     for i in myimages_objs :
          myimages_objs = i['image']
          return render(request, 'index.html', {'myimages_obj ': myimages_objs })

index.html

Body:
I don't understand why you are returning the objects inside the for loop, this causes only a single image to be displayed in the template. Instead of doing this, you can pass all the image objects in the template, then loop through the objects in the template to display the images.

You can change your view as:

def display(request):
    myimages_objs = Images.objects.all() # get all the images
    return render(request, 'index.html', {'myimages_objs':myimages_objs})

Then in your template:

<div class="divi">
    {% for item in myimages_objs %} //loop through all the images
        <img src="{{ item.image.url }}" alt="image">
    {% endfor %}
</div>

Edit:

Change the upload_to to upload_to="images/".

As far as I am concerned, your images are not being stored inside the images folder as you have missed the backslash(which represents a folder name). So, the images are being saved inside the media folder.

But the image url is something like project_path/media/images/something.jpg which cannot be found as the images are not being saved inside the images folder.

Change the field as stated for new images to be stored in the specified folder. For old images, copy them to the images folder manually.

I hope this will help.


问:
createPortal does not overwrite div contents (like ReactDOM.render)
I am trying to get ReactDOM.createPortal to override the contents of the container I am mounting it too. However it seems to appendChild.

Is it possible to override contents? Similar to ReactDOM.render?

Here is my code:

```<code>import React from 'react';
import { createPortal } from 'react-dom';

class PrivacyContent extends React.Component {

    render() {
        return createPortal(
            <div>
                <button onClick={this.handleClick}>
                    Click me
                </button>
            </div>,
            document.getElementById('privacy')
        )
    }

    handleClick() {
        alert('clicked');
    }

}

export default PrivacyContent;
</code>```

答:
If you know what you're doing, here is a <Portal /> component that under the hoods creates a portal, empties the target DOM node and mounts any component with any props:

```<code>const Portal = ({ Component, container, ...props }) => {
  const [innerHtmlEmptied, setInnerHtmlEmptied] = React.useState(false)
  React.useEffect(() => {
    if (!innerHtmlEmptied) {
      container.innerHTML = ''
      setInnerHtmlEmptied(true)
    }
  }, [innerHtmlEmptied])
  if (!innerHtmlEmptied) return null
  return ReactDOM.createPortal(<Component {...props} />, container)
}
</code>```

Usage:

```<code><Portal Component={MyComponent} container={document.body} {...otherProps} />
</code>```

This empties the content of document.body, then mounts MyComponent while passing down otherProps.

Hope that helps.

Body:
I am trying to get ReactDOM.createPortal to override the contents of the container I am mounting it too. However it seems to appendChild.

Is it possible to override contents? Similar to ReactDOM.render?

Here is my code:

import React from 'react';
import { createPortal } from 'react-dom';

class PrivacyContent extends React.Component {

    render() {
        return createPortal(

                <button onClick={this.handleClick}>
                    Click me
                </button>

,
            document.getElementById('privacy')
        )
    }

    handleClick() {
        alert('clicked');
    }

}

export default PrivacyContent;

Body:
If you know what you're doing, here is a <Portal /> component that under the hoods creates a portal, empties the target DOM node and mounts any component with any props:

const Portal = ({ Component, container, ...props }) => {
  const [innerHtmlEmptied, setInnerHtmlEmptied] = React.useState(false)
  React.useEffect(() => {
    if (!innerHtmlEmptied) {
      container.innerHTML = ''
      setInnerHtmlEmptied(true)
    }
  }, [innerHtmlEmptied])
  if (!innerHtmlEmptied) return null
  return ReactDOM.createPortal(<Component {...props} />, container)
}

Usage:

<Portal Component={MyComponent} container={document.body} {...otherProps} />

This empties the content of document.body, then mounts MyComponent while passing down otherProps.

Hope that helps.


问:
Avoiding paste values on different dropdown excel vba
I am trying to have an Excel file with some columns that have dropdown and I would to avoid people to copy and paste in those columns. But if the value they are pasting is correct then they can paste.

The code I have is working for one column. I am trying to do for multiple columns with different dropdowns each one.

In this code example it is just for two columns (C and D) with the dropdowns in sheet "dropdowns" in columns A and B respectively.

Any help on how to modify the code below to make it work for more columns?

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

Dim rng1 As Range
Dim rng2 As Range
Dim isect As Range
Dim isect2 As Range
Dim cell As Range
Dim dd() As Variant
Dim i As Long
Dim mtch As Boolean
Dim msg As String
Dim myEntries As String
Dim ddRange As Range
Dim ddRange2 As Range

Set rng1 = Range("C:C")
Set rng2 = Range("D:D")

Set ddRange = Sheets("Dropdowns").Range("A2:A11")
Set ddRange2 = Sheets("Dropdowns").Range("B2:B8")

Set isect = Intersect(rng1, Target)

Set isect2 = Intersect(rng2, Target)

If (isect Is Nothing) And (isect2 Is Nothing) Then Exit Sub

Application.EnableEvents = False

If Not isect Is Nothing Then

    ReDim dd(ddRange.Cells.Count)
    i = 0
    For Each cell In ddRange
        dd(i) = cell.Value
        i = i + 1
    Next cell

    For Each cell In isect

        mtch = False
        For i = LBound(dd) To UBound(dd)
            If cell.Value = dd(i) Then
                mtch = True
                Exit For
            End If
        Next i

        If mtch = False Then
            cell.ClearContents
            msg = msg & cell.Address(0, 0) & ","
        End If
    Next cell

    For i = LBound(dd) To UBound(dd)
        myEntries = myEntries & dd(i) & ","
    Next i
    myEntries = Left(myEntries, Len(myEntries) - 1)

    With rng1.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
            xlBetween, Formula1:=myEntries
    End With

    If Len(msg) > 0 Then
        MsgBox "Invalid entries in cells: " & vbCrLf & Left(msg, Len(msg) - 1), vbOKOnly, "ERROR!"
    End If
End If

If Not isect2 Is Nothing Then

    For Each cell In isect2
        If (Len(cell) > 0) And (Len(cell) <> 11) Then
            cell.ClearContents
            msg = msg & cell.Address(0, 0) & ","
        End If
    Next cell

    With rng2.Validation
        .Delete
        .Add Type:=xlValidateTextLength, AlertStyle:=xlValidAlertStop, _
            Operator:=xlEqual, Formula1:="11"
    End With

    If Len(msg) > 0 Then
        MsgBox "Invalid entries in cells: " & vbCrLf & Left(msg, Len(msg) - 1), vbOKOnly, "ERROR!"
    End If
End If

Application.EnableEvents = True

End Sub
</code>```

I was thinking trying to create a Function and every column with a dropdown to call that function with the corresponding correct dropdowns.

Is this a correct approach? Any help on this?

Thank you in advance for your time!!

答:
What about this? It's kind of dirty, but it's really useful.

Let's say you want to avoid people pasting values in any cell of 2 specific columns (in my case it would be any cell of columns C or D). For that I use:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Column = 3 Or Target.Column = 4 Then Application.CutCopyMode = False
End Sub
</code>```

So if user copies a cell into clipboard, and then selects a cell in column C or D, the clipboard will empty, so they can't paste anything.

You can customize the conditions to check this and be more restrictive (only a specific range, a table, a group of cells, and so on). My example is the easy one.

You can combine this with normal dropwdowns provided by data validations in cells, so they cannot paste anything in those cells.

I know this may look dirty and tricky, but it works awesome at my office with some teammates in specific forms.

Body:
I am trying to have an Excel file with some columns that have dropdown and I would to avoid people to copy and paste in those columns. But if the value they are pasting is correct then they can paste.

The code I have is working for one column. I am trying to do for multiple columns with different dropdowns each one.

In this code example it is just for two columns (C and D) with the dropdowns in sheet "dropdowns" in columns A and B respectively.

Any help on how to modify the code below to make it work for more columns?

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rng1 As Range
Dim rng2 As Range
Dim isect As Range
Dim isect2 As Range
Dim cell As Range
Dim dd() As Variant
Dim i As Long
Dim mtch As Boolean
Dim msg As String
Dim myEntries As String
Dim ddRange As Range
Dim ddRange2 As Range

Set rng1 = Range("C:C")
Set rng2 = Range("D:D")

Set ddRange = Sheets("Dropdowns").Range("A2:A11")
Set ddRange2 = Sheets("Dropdowns").Range("B2:B8")

Set isect = Intersect(rng1, Target)

Set isect2 = Intersect(rng2, Target)

If (isect Is Nothing) And (isect2 Is Nothing) Then Exit Sub

Application.EnableEvents = False

If Not isect Is Nothing Then

    ReDim dd(ddRange.Cells.Count)
    i = 0
    For Each cell In ddRange
        dd(i) = cell.Value
        i = i + 1
    Next cell

    For Each cell In isect

        mtch = False
        For i = LBound(dd) To UBound(dd)
            If cell.Value = dd(i) Then
                mtch = True
                Exit For
            End If
        Next i

        If mtch = False Then
            cell.ClearContents
            msg = msg & cell.Address(0, 0) & ","
        End If
    Next cell

    For i = LBound(dd) To UBound(dd)
        myEntries = myEntries & dd(i) & ","
    Next i
    myEntries = Left(myEntries, Len(myEntries) - 1)

    With rng1.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
            xlBetween, Formula1:=myEntries
    End With

    If Len(msg) > 0 Then
        MsgBox "Invalid entries in cells: " & vbCrLf & Left(msg, Len(msg) - 1), vbOKOnly, "ERROR!"
    End If
End If

If Not isect2 Is Nothing Then

    For Each cell In isect2
        If (Len(cell) > 0) And (Len(cell) <> 11) Then
            cell.ClearContents
            msg = msg & cell.Address(0, 0) & ","
        End If
    Next cell

    With rng2.Validation
        .Delete
        .Add Type:=xlValidateTextLength, AlertStyle:=xlValidAlertStop, _
            Operator:=xlEqual, Formula1:="11"
    End With

    If Len(msg) > 0 Then
        MsgBox "Invalid entries in cells: " & vbCrLf & Left(msg, Len(msg) - 1), vbOKOnly, "ERROR!"
    End If
End If

Application.EnableEvents = True

End Sub

I was thinking trying to create a Function and every column with a dropdown to call that function with the corresponding correct dropdowns.

Is this a correct approach? Any help on this?

Thank you in advance for your time!!

Body:
What about this? It's kind of dirty, but it's really useful.

Let's say you want to avoid people pasting values in any cell of 2 specific columns (in my case it would be any cell of columns C or D). For that I use:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Column = 3 Or Target.Column = 4 Then Application.CutCopyMode = False
End Sub

So if user copies a cell into clipboard, and then selects a cell in column C or D, the clipboard will empty, so they can't paste anything.

You can customize the conditions to check this and be more restrictive (only a specific range, a table, a group of cells, and so on). My example is the easy one.

You can combine this with normal dropwdowns provided by data validations in cells, so they cannot paste anything in those cells.

I know this may look dirty and tricky, but it works awesome at my office with some teammates in specific forms.


问:
React native Tab View congested when number of tab is increase
I am using react-native-tab-view for display tab on the top of the screen. Screen view looks congested in case of number of screen is going to increase (more than 5)

Below is my code snippet

```<code>export default class CustomTabViewComponent extends React.Component{
state = {
    index: 0,
    routes: [
      { key: 'tab1', title: 'Tab1' },
      { key: 'tab2', title: 'Tab2' },
      { key: 'tab3', title: 'Tab3' },
      { key: 'tab4', title: 'Tab4' },
      { key: 'tab5', title: 'Tab5' },
    ],
  };
render(){
   return(
   <TabView
          navigationState={this.state}
          renderScene={this.renderScene}
          renderTabBar={this._renderTabBar}
          onIndexChange={this.onIndexChange}
          initialLayout={{
            width: Dimensions.get('window').width,
            height: 100,
          }}
        />

)}
}
</code>```

I am posting image also for reference.

Is there any property with the help of that i can make TabView scrollable to the right with individual tab fix width ?

PS: I have try react-native-scrollable-tab-view but stuck at the same place.

答:
pass renderTabBar prop to TableView which returns a custom React Element and return <TabBar>, add tabStyle and scrollEnabled={true} to TabBar.

renderTabBar - Callback which returns a custom React Element to use as the tab bar

TabBar - Material design themed tab bar.

scrollEnabled - Boolean indicating whether to enable scrollable tabs.

tabStyle - Style to apply to the individual tab items in the tab bar.

```<code>import { TabView, SceneMap, TabBar } from 'react-native-tab-view';

<TabView
  navigationState={this.state}
  renderScene={this.renderScene}
  renderTabBar={this._renderTabBar}
  onIndexChange={this.onIndexChange}
  renderTabBar={props => (
    <TabBar
      {...props}
      indicatorStyle={{ backgroundColor: 'white' }}
      tabStyle={{ width: 100 }}
      scrollEnabled={true}
      style={{ backgroundColor: 'blue' }}
    />
  )}
  initialLayout={{
    width: Dimensions.get('window').width,
    height: 100,
  }}
/>
</code>```

Demo

Body:
I am using react-native-tab-view for display tab on the top of the screen. Screen view looks congested in case of number of screen is going to increase (more than 5)

Below is my code snippet

export default class CustomTabViewComponent extends React.Component{
state = {
    index: 0,
    routes: [
      { key: 'tab1', title: 'Tab1' },
      { key: 'tab2', title: 'Tab2' },
      { key: 'tab3', title: 'Tab3' },
      { key: 'tab4', title: 'Tab4' },
      { key: 'tab5', title: 'Tab5' },
    ],
  };
render(){
   return(
   <TabView
          navigationState={this.state}
          renderScene={this.renderScene}
          renderTabBar={this._renderTabBar}
          onIndexChange={this.onIndexChange}
          initialLayout={{
            width: Dimensions.get('window').width,
            height: 100,
          }}
        />

)}
}

I am posting image also for reference.

Is there any property with the help of that i can make TabView scrollable to the right with individual tab fix width ?

PS: I have try react-native-scrollable-tab-view but stuck at the same place.

Body:
pass renderTabBar prop to TableView which returns a custom React Element and return <TabBar>, add tabStyle and scrollEnabled={true} to TabBar.

renderTabBar - Callback which returns a custom React Element to use as the tab bar

TabBar - Material design themed tab bar.

scrollEnabled - Boolean indicating whether to enable scrollable tabs.

tabStyle - Style to apply to the individual tab items in the tab bar.

import { TabView, SceneMap, TabBar } from 'react-native-tab-view';

<TabView
  navigationState={this.state}
  renderScene={this.renderScene}
  renderTabBar={this._renderTabBar}
  onIndexChange={this.onIndexChange}
  renderTabBar={props => (
    <TabBar
      {...props}
      indicatorStyle={{ backgroundColor: 'white' }}
      tabStyle={{ width: 100 }}
      scrollEnabled={true}
      style={{ backgroundColor: 'blue' }}
    />
  )}
  initialLayout={{
    width: Dimensions.get('window').width,
    height: 100,
  }}
/>

Demo


问:
VSTS build fails with MSB3325, Cannot import PFX key file
I had created a build definition to build a desktop application online on visualstudio.com which fail at task Build Solution (Visual Studio build) with following error,

[error]C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(3156,5):
  Error MSB3325: Cannot import the following key file:
  Sixmod5Certificate.pfx. The key file may be password protected. To
  correct this, try to import the certificate again or manually install
  the certificate to the Strong Name CSP with the following key
  container name: VS_KEY_3B2BCC84AE4E26F1

I followed solution specified at, https://developercommunity.visualstudio.com/content/problem/156086/vsts-build-msb3325-cannot-import-the-following-key.html

then as specified at, https://stackoverflow.com/a/48698229/3531672
I had added a powershell script task before build task, as follows,

```<code>[CmdletBinding()]
param(
    [Parameter(Mandatory)][string] $pfxpath,
    [Parameter(Mandatory)][string] $password
)

Add-Type -AssemblyName System.Security
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($pfxpath, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "MY", CurrentUser
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
$store.Add($cert)
$store.Close()
</code>```

but no luck yet,

There are different SO post similar to this specifying solution to build from Admin user, or installing pfx certificate manually, but as they are related to personal computer and I am trying to configure Continuous integration on visualstudio.com, they don't seem useful to me.

Please note I am able to successfully build on my local machine.

If you wish to regenerate this problem at your end, follow these steps,

STEP 1: Create a new VSTO Addin Project (Any Excel/Word/Powerpoint).

STEP 2: Attach this to VSTS.

STEP 3: In signing tab of Application properties, instead of using temperory certificate, create a new password protected certificate (PFX - Personal Information Exchange in my case) and use this to sign ClickOnce Manifest

STEP 4: Try to build on local machine, it will succeed.

STEP 5: Push it over and try to build on VSTS, you will get the same error as above.

答: I unchecked the "Sign the assembly" checkbox from the "project properties -> Signing" page and everything worked like a charm. The build was signed successfully through VSTS. Somehow I missed this solution provided in many SO threads related to the problem.</p>

Body:
I had created a build definition to build a desktop application online on visualstudio.com which fail at task Build Solution (Visual Studio build) with following error,

[error]C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(3156,5):
  Error MSB3325: Cannot import the following key file:
  Sixmod5Certificate.pfx. The key file may be password protected. To
  correct this, try to import the certificate again or manually install
  the certificate to the Strong Name CSP with the following key
  container name: VS_KEY_3B2BCC84AE4E26F1

I followed solution specified at, https://developercommunity.visualstudio.com/content/problem/156086/vsts-build-msb3325-cannot-import-the-following-key.html

then as specified at, https://stackoverflow.com/a/48698229/3531672
I had added a powershell script task before build task, as follows,

[CmdletBinding()]
param(
    [Parameter(Mandatory)][string] $pfxpath,
    [Parameter(Mandatory)][string] $password
)

Add-Type -AssemblyName System.Security
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($pfxpath, $password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")
$store = new-object system.security.cryptography.X509Certificates.X509Store -argumentlist "MY", CurrentUser
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
$store.Add($cert)
$store.Close()

but no luck yet,

There are different SO post similar to this specifying solution to build from Admin user, or installing pfx certificate manually, but as they are related to personal computer and I am trying to configure Continuous integration on visualstudio.com, they don't seem useful to me.

Please note I am able to successfully build on my local machine.

If you wish to regenerate this problem at your end, follow these steps,

STEP 1: Create a new VSTO Addin Project (Any Excel/Word/Powerpoint).

STEP 2: Attach this to VSTS.

STEP 3: In signing tab of Application properties, instead of using temperory certificate, create a new password protected certificate (PFX - Personal Information Exchange in my case) and use this to sign ClickOnce Manifest

STEP 4: Try to build on local machine, it will succeed.

STEP 5: Push it over and try to build on VSTS, you will get the same error as above.


问:
JQuery - How to add a class to every last list item?
Got some code here that isn't working:

```<code>$("#sidebar ul li:last").each(function(){
      $(this).addClass("last");
});
</code>```

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

```<code><ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li class="last">Item 3</li>
</ul>
</code>```

Hope that makes sense,
Cheers!

答:
The reason that won't work is due to the fact that :last only matches one element.  From the jQuery documentation:

Matches the last selected element.

So what your code is doing is getting a set of all the
 elements in a
 and then from that set taking the last value.  Example:

```<code> <ul>
   <li>1</li>
   <li>2</li>
 </ul>
 <ul>
   <li>3</li>
   <li>4</li>
 </ul>
 <ul>
   <li>5</li>
   <li>6</li>
 </ul>
</code>```

Your code would return the element
6
.  (Internally, it'd collect
1
 to
6
 and then lop off the last one and return it).

What you're looking for is what the other answers here have said: :last-child.

OwnerDisplayName: Keith Donegan

ContentLicense: CC BY-SA 2.5

Body:
Got some code here that isn't working:

$("#sidebar ul li:last").each(function(){
      $(this).addClass("last");
});

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

Item 1

Item 2

Item 3

Hope that makes sense,
Cheers!

Body:
The reason that won't work is due to the fact that :last only matches one element.  From the jQuery documentation:

Matches the last selected element.

So what your code is doing is getting a set of all the <li> elements in a <ul> and then from that set taking the last value.  Example:

 <ul>
   <li>1</li>
   <li>2</li>
 </ul>
 <ul>
   <li>3</li>
   <li>4</li>
 </ul>
 <ul>
   <li>5</li>
   <li>6</li>
 </ul>

Your code would return the element <li>6</li>.  (Internally, it'd collect <li>1</li> to <li>6</li> and then lop off the last one and return it).

What you're looking for is what the other answers here have said: :last-child.

OwnerDisplayName: Cameron McKay


问:
Tricks for generating SQL statements in Excel
Do you have any tricks for generating SQL statements, mainly INSERTs, in Excel for various data import scenarios?

I'm really getting tired of writing formulas with like

="INSERT INTO Table (ID, Name) VALUES (" & C2 & ", '" & D2 & "')"

答:
the VBA approach would be:
declare your string and assign your SQL statement like this

```<code>dim SqlString as String
SqlString = "SELECT * FROM %1 WHERE (var=%2)"
SqlString = Replace("%1", "Table_Name")
SqlString = Replace("%2", ""value"")
</code>```

Excel approach is similar, but using the SUBSTITUTE function.

I prefer this approach because it makes the SQL text legible and avoids all the annoying & and concatenate problems. Yes, it takes an extra cell, but its worth it for the audit trail.

OwnerDisplayName: David Vidmar

LastEditorDisplayName: David Vidmar

Body:
the VBA approach would be:
declare your string and assign your SQL statement like this

dim SqlString as String
SqlString = "SELECT * FROM %1 WHERE (var=%2)"
SqlString = Replace("%1", "Table_Name")
SqlString = Replace("%2", ""value"")

Excel approach is similar, but using the SUBSTITUTE function.

I prefer this approach because it makes the SQL text legible and avoids all the annoying & and concatenate problems. Yes, it takes an extra cell, but its worth it for the audit trail.


问:
Execute commands in session without passing it to every one of them
In my application I use repository pattern and I want to be able to execute some methods from repository (or more repositories) in a session with transaction.
It should be optional, so sometimes I want to add user without using a transaction, but somewhere else I want to execute the same method in session and transaction.
I dont want to create overload on every repository method with optional IClientSessionHandle parameter, that sounds very ugly to me.

I tried to basically implement Unit of Work pattern like I used in Entity Framework. Code I have but doesn't work looks like this:

```<code>using (var uow = _uowProvider.Create())
{
     repository.Add(someEntity);
     repository.Add(otherEntity);
     uow.Commit(); //just calls CommitTransaction on wrapped session
}

</code>```

The "uow" in this example just wraps IClientSessionHandle and I hoped that if I create collections from this session, they would be included in it and its transaction, but they are not.

Inside IUnitOfWorkProvider I instantiate collections (simplified) like this:

```<code>_unitOfWorkProvider.Current == null
                       ? collection
                       : _unitOfWorkProvider.Current.Session.Client.GetDatabase(collection.Database.DatabaseNamespace.DatabaseName)
                           .GetCollection<T>(collection.CollectionNamespace.CollectionName);
</code>```

Result is, that my commands (like InsertOneAsync etc.) are not executed in session, because I don't pass the session object to them. If I pass null session the the call (because session/transaction is optional) it throws NRE.

Is there a way to optionally execute commands on mongo collections without explicitly passing session instance to them?

答:
have a look at the source code of MongoDB.Entities to see how it tackles this issue. end result is transaction code that looks like this:

    using (var TN = new Transaction())
    {
         var author1 = new Author { Name = "one" };
         var author2 = new Author { Name = "two" };

         TN.Save(author1);
         TN.Save(author2);

         TN.Commit();
         }
    }
```

Body:
In my application I use repository pattern and I want to be able to execute some methods from repository (or more repositories) in a session with transaction.
It should be optional, so sometimes I want to add user without using a transaction, but somewhere else I want to execute the same method in session and transaction.
I dont want to create overload on every repository method with optional IClientSessionHandle parameter, that sounds very ugly to me.

I tried to basically implement Unit of Work pattern like I used in Entity Framework. Code I have but doesn't work looks like this:

using (var uow = _uowProvider.Create())
{
     repository.Add(someEntity);
     repository.Add(otherEntity);
     uow.Commit(); //just calls CommitTransaction on wrapped session
}

The "uow" in this example just wraps IClientSessionHandle and I hoped that if I create collections from this session, they would be included in it and its transaction, but they are not.

Inside IUnitOfWorkProvider I instantiate collections (simplified) like this:

_unitOfWorkProvider.Current == null
                       ? collection
                       : _unitOfWorkProvider.Current.Session.Client.GetDatabase(collection.Database.DatabaseNamespace.DatabaseName)
                           .GetCollection<T>(collection.CollectionNamespace.CollectionName);

Result is, that my commands (like InsertOneAsync etc.) are not executed in session, because I don't pass the session object to them. If I pass null session the the call (because session/transaction is optional) it throws NRE.

Is there a way to optionally execute commands on mongo collections without explicitly passing session instance to them?


问:
How can we count number of records and show in rest api?
controller:

```<code><?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }
</code>```

unexpected output:

```<code>[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]
</code>```

expected output:

```<code>{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]
</code>```

}

In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.

Thank You

答:
replace your function with the following code:</p>

```<code>function country_get()
   {
         $this->db->select('id,name');
         $this->db->from('countries');
         $sql = $this->db->get();
         $res = $sql->result_array();
         $result['Status'] = "Success";
         $result['Message'] = "Total country found ".count($res);
         $result['Country'] = $res
         $this->response($result, 200);
    }
</code>```

Body:
controller:

<?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function country_get()
        {
            $this->db->select('id,name');
            $this->db->from('countries');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }
    }

unexpected output:

[
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

expected output:

{
"Message": "Number of Country found: 5",
"Status": "Success",
"Country": [
    {
        "id": "1",
        "name": "Afghanistan"
    },
    {
        "id": "2",
        "name": "Albania"
    },
    {
        "id": "3",
        "name": "Algeria"
    },
    {
        "id": "4",
        "name": "American Samoa"
    },
    {
        "id": "5",
        "name": "Andorra"
    }
]

}

In this code I want to show number of records as I mention in my expected output. So, How can I do this? Please help me.

Thank You

Body:
replace your function with the following code:

function country_get()
   {
         $this->db->select('id,name');
         $this->db->from('countries');
         $sql = $this->db->get();
         $res = $sql->result_array();
         $result['Status'] = "Success";
         $result['Message'] = "Total country found ".count($res);
         $result['Country'] = $res
         $this->response($result, 200);
    }


问:
Clang/LLVM 7 and 8 on Windows initialize inline static data member multiple times (with both link.exe and lld-link.exe)
Clang/LLVM 7 and 8 on Windows initialize an inline static data member once per TU. As far as I understand C++17 this is not correct.

Although an inline variable may be defined in multiple TUs the compiler and/or linker must ensure that it exists only once in a program and hence is initialized exactly once.

The following little program shows what happens with Clang/LLVM (tested in Visual Studio 2017 and 2019 RC with LLVM Compiler Toolchain extension):

// header.h

```<code>#include <iostream>

struct A
{
  A()      { std::cout << "ctor " << this << std::endl; }
  ~A()     { std::cout << "dtor " << this << std::endl; }
  void f() { std::cout << "f " << this << std::endl;  }
};

struct S
{
  inline static A a; // C++17 inline variable, thus also a definition
};
</code>```

// TU1.cpp

```<code>#include "header.h"

int main()
{
  S::a.f();
}
</code>```

// TU2.cpp

```<code>#include "header.h"
</code>```

// TU3.cpp

```<code>#include "header.h"
</code>```

// TU4.cpp

```<code>#include "header.h"
</code>```

This program prints:

```<code>ctor 010D4020
ctor 010D4020
ctor 010D4020
ctor 010D4020
f 010D4020
dtor 010D4020
dtor 010D4020
dtor 010D4020
dtor 010D4020
</code>```

That's four initializations for the one and only object of A (in fact one per TU) instead of exactly one (as C++17 demands).

The program should print:

```<code>ctor 010D4020
f 010D4020
dtor 010D4020
</code>```

This is what MSVC does, by the way.

This is a bug in clang/LLVM, right?

答: This bug is fixed in the current snapshot build based on SVN r361807.</p>

Body:
Clang/LLVM 7 and 8 on Windows initialize an inline static data member once per TU. As far as I understand C++17 this is not correct.

Although an inline variable may be defined in multiple TUs the compiler and/or linker must ensure that it exists only once in a program and hence is initialized exactly once.

The following little program shows what happens with Clang/LLVM (tested in Visual Studio 2017 and 2019 RC with LLVM Compiler Toolchain extension):

// header.h

#include <iostream>

struct A
{
  A()      { std::cout << "ctor " << this << std::endl; }
  ~A()     { std::cout << "dtor " << this << std::endl; }
  void f() { std::cout << "f " << this << std::endl;  }
};

struct S
{
  inline static A a; // C++17 inline variable, thus also a definition
};

// TU1.cpp

#include "header.h"

int main()
{
  S::a.f();
}

// TU2.cpp

#include "header.h"

// TU3.cpp

#include "header.h"

// TU4.cpp

#include "header.h"

This program prints:

ctor 010D4020
ctor 010D4020
ctor 010D4020
ctor 010D4020
f 010D4020
dtor 010D4020
dtor 010D4020
dtor 010D4020
dtor 010D4020

That's four initializations for the one and only object of A (in fact one per TU) instead of exactly one (as C++17 demands).

The program should print:

ctor 010D4020
f 010D4020
dtor 010D4020

This is what MSVC does, by the way.

This is a bug in clang/LLVM, right?


问:
Get greatest rows based on multiple columns in MySQL
I have a table that looks like:

```<code>id | title | value | language
---+-------+-------+---------
1  | a     | 1800  |    NULL
2  | a     | 1900  |    NULL
3  | b     | 1700  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL
</code>```

Would like to have the following result:

```<code>id | title | value | language
---+-------+-------+---------
2  | a     | 1900  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL
</code>```

The point is to select the greatest value in value column of every language of every title - greatest being the latest. Secondly, would like to avoid Aggregate functions like MAX, DISTINCT or GROUP-BY as I am building a MySQL View using the MERGE algorithm, and don't want to end up creating a temporary table (See the bottom section of https://dev.mysql.com/doc/refman/5.6/en/view-algorithms.html).

So far this works, but only returns greatest row per title:

```<code>SELECT t1.title
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.title = t2.title
        AND t1.value < t2.value
WHERE t2.title IS NULL
</code>```

How can I create one that takes language into account like the results above? Thanx.

答:
You can do it with NOT EXISTS:

```<code>select t.*
from tablename t
where not exists (
  select 1 from tablename
  where
    title = t.title and
    coalesce(language, 0) = coalesce(t.language, 0) and
    value > t.value
)
</code>```

See the demo.

Results:

```<code>| id  | title | value | language |
| --- | ----- | ----- | -------- |
| 2   | a     | 1900  | NULL     |
| 4   | b     | 1750  | NULL     |
| 5   | b     | 1790  | 1        |
| 6   | c     | 1892  | NULL     |
| 7   | c     | 1900  | 1        |
| 8   | c     | 1910  | 2        |
| 9   | d     | 3020  | NULL     |
</code>```

Body:
I have a table that looks like:

id | title | value | language
---+-------+-------+---------
1  | a     | 1800  |    NULL
2  | a     | 1900  |    NULL
3  | b     | 1700  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL

Would like to have the following result:

id | title | value | language
---+-------+-------+---------
2  | a     | 1900  |    NULL
4  | b     | 1750  |    NULL
5  | b     | 1790  |    1
6  | c     | 1892  |    NULL
7  | c     | 1900  |    1
8  | c     | 1910  |    2
9  | d     | 3020  |    NULL

The point is to select the greatest value in value column of every language of every title - greatest being the latest. Secondly, would like to avoid Aggregate functions like MAX, DISTINCT or GROUP-BY as I am building a MySQL View using the MERGE algorithm, and don't want to end up creating a temporary table (See the bottom section of https://dev.mysql.com/doc/refman/5.6/en/view-algorithms.html).

So far this works, but only returns greatest row per title:

SELECT t1.title
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.title = t2.title
        AND t1.value < t2.value
WHERE t2.title IS NULL

How can I create one that takes language into account like the results above? Thanx.

Body:
You can do it with NOT EXISTS:

select t.*
from tablename t
where not exists (
  select 1 from tablename
  where
    title = t.title and
    coalesce(language, 0) = coalesce(t.language, 0) and
    value > t.value
)

See the demo.

Results:

| id  | title | value | language |
| --- | ----- | ----- | -------- |
| 2   | a     | 1900  | NULL     |
| 4   | b     | 1750  | NULL     |
| 5   | b     | 1790  | 1        |
| 6   | c     | 1892  | NULL     |
| 7   | c     | 1900  | 1        |
| 8   | c     | 1910  | 2        |
| 9   | d     | 3020  | NULL     |


问:
Schema::dropIfExists() Deleted ALL tables in DB on migrate:rollback
I ran php artisan migrate:rollback on command line, so the migration deleted ALL TABLES in db.

There is only one migration created but have others tables in used db.

The laravel documentation says:

To drop an existing table, you may use the drop or dropIfExists methods.

and the function down() on migration code is the default like as bellow:

```<code>public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('image')->unsigned()->nullable();
            $table->string('name', 64);
            $table->string('slug', 64)->unique();
            $table->integer('price')->unsigned();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
</code>```

I don't think the Schema::dropIfExists('products') work properlly in this case, this is a bug? or my(and laravel documentation) mistake?

答:
Roll back, rolls back each migration of the last batch.

If your all migration in same batch then it will rollback all the migrations. So your all tables will be deleted from the database.

Body:
I ran php artisan migrate:rollback on command line, so the migration deleted ALL TABLES in db.

There is only one migration created but have others tables in used db.

The laravel documentation says:

To drop an existing table, you may use the drop or dropIfExists methods.

and the function down() on migration code is the default like as bellow:

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('image')->unsigned()->nullable();
            $table->string('name', 64);
            $table->string('slug', 64)->unique();
            $table->integer('price')->unsigned();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

I don't think the Schema::dropIfExists('products') work properlly in this case, this is a bug? or my(and laravel documentation) mistake?


问:
Validator.ValidateObject with "validateAllProperties" to true stop at first error
I have a custom class (to be simple) :

```<code>using System;
using System.ComponentModel.DataAnnotations;

public class MyClass {
    [Required]
    public string Title { get; set;}
    [Required]
    public string Description { get; set;}
}
</code>```

I want to validate this object, and get an exception with everything not correct.

If I do :

```<code>void Validate() {
    var objectToValidate = new MyClass { }; // Both properties are null at this time
    var ctx = new ValidationContext(objectToValidate, null, null);
    Validator.ValidateObject(objectToValidate, ctx, true);
}
</code>```

A ValidationException is thrown but it shows only the first error, even I specify true to the validateAllProperties parameter.

if I refactor a bit my code :

```<code>void Validate() {
    var objectToValidate = new MyClass { }; // Both properties are null at this time
    var ctx = new ValidationContext(objectToValidate, null, null);
    var errors = new List<ValidationResult>();
    var isValid = Validator.TryValidateObject(objectToValidate, ctx, errors, true);

    if(!isValid) {
        throw new AggregateException(
            errors.Select((e)=>new ValidationException(e.ErrorMessage)
        );
    }
}
</code>```

I can actually have all my errors.

Why does the first code snippet works as expected ? Did I do something wrong?

答:
Validator.ValidateObject goes through all validation attributes and throws ValidationException for the first one that fails. I don't think one can get the list of all properties that failed this way.

The MSDN documentation is a bit confusing here, it says:

The ValidateObject method evaluates each ValidationAttribute attribute that is associated with the object type. If validateAllProperties is set to true, the method validates the property values of the object.

TryValidateObject method manual continues:

It also checks whether each property that is marked with RequiredAttribute is provided.

I confirm that it always checks all the Required attributes, regardless of validateAllProperties. But if you have, for example, a Range validation attribute it will only check it when validateAllProperties is true (because this is when it validates the property value). A bit confusing, but as you noticed, TryValidateObject shows all the failed properties and this is what I'm using for my project as well.

Body:
I have a custom class (to be simple) :

using System;
using System.ComponentModel.DataAnnotations;

public class MyClass {
    [Required]
    public string Title { get; set;}
    [Required]
    public string Description { get; set;}
}

I want to validate this object, and get an exception with everything not correct.

If I do :

void Validate() {
    var objectToValidate = new MyClass { }; // Both properties are null at this time
    var ctx = new ValidationContext(objectToValidate, null, null);
    Validator.ValidateObject(objectToValidate, ctx, true);
}

A ValidationException is thrown but it shows only the first error, even I specify true to the validateAllProperties parameter.

if I refactor a bit my code :

void Validate() {
    var objectToValidate = new MyClass { }; // Both properties are null at this time
    var ctx = new ValidationContext(objectToValidate, null, null);
    var errors = new List<ValidationResult>();
    var isValid = Validator.TryValidateObject(objectToValidate, ctx, errors, true);

    if(!isValid) {
        throw new AggregateException(
            errors.Select((e)=>new ValidationException(e.ErrorMessage)
        );
    }
}

I can actually have all my errors.

Why does the first code snippet works as expected ? Did I do something wrong?


问:
how to limit checkbox selection in listview?
friends,

i want to limit checkbox selection in android listivew to for example only 3 checkboxes should be selected otherwise it should give error message.

user can select any three checkboxes from the list
any one guide me how to achieve this? here is my adapter

```<code>public class AdapterContacts extends BaseAdapter  {

    private LayoutInflater mInflater;

    public Context context;
    public static List<myContacts> contacts;

    public AdapterContacts(Context context,List<myContacts> list) {
      mInflater = LayoutInflater.from(context);
      this.context = context;
      contacts= list;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

      ViewHolder holder;

      if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_contacts, null);
        holder = new ViewHolder();
        holder.contactName = (TextView) convertView.findViewById(R.id.contactName);
        holder.contactNumber = (TextView) convertView.findViewById(R.id.contactNumber);
        holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
        convertView.setTag(holder);

      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      myContacts contact = getItem(position);
      holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked) {
                 myContacts c = (myContacts) checkboxView.getTag();
                 c.setSelected(isChecked);
                 // to put that check of selection limit with error

            }
        });

      holder.checkBox.setTag(contact);
      holder.checkBox.setChecked(contact.isSelected());

      holder.contactName.setText(contact.getContactName());
      holder.contactNumber.setText(contact.getPhoneNumber());

        return convertView;

        }

    @Override
    public int getCount() {
        return contacts.size();
    }

    @Override
    public myContacts getItem(int position) {
        return contacts.get(position);
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    class ViewHolder {
        TextView contactName;
        TextView contactNumber;
        CheckBox  checkBox;
      }

}
</code>```

any help would be appreciated.

答:
i solved the issue "after scroll listview user can also again select more than 3 check boxex" Thanks for you patience
 set static int count = 0;

```<code>                     if (isChecked) {
                        count++;
                    } else if (!isChecked) {
                        count--;
                    }

                    if (count >= 4) {
                        buttonView.setChecked(false);
                        count--;
                    } else {
                        int getPosition = (Integer) buttonView.getTag();

                       contact.get(getPosition).setSelected(buttonView.isChecked());
                    }
</code>```

And Most imprtant is that add count=0 in else and viewHolder.chkContact.setTag(position) after else;

```<code>if(convertView == null){

}else
{
 viewHolder = (ViewHolder) convertView.getTag();
 count=0;
 }
 viewHolder.chkContact.setTag(position);
</code>```

`

Body:
friends,

i want to limit checkbox selection in android listivew to for example only 3 checkboxes should be selected otherwise it should give error message.

user can select any three checkboxes from the list
any one guide me how to achieve this? here is my adapter

public class AdapterContacts extends BaseAdapter  {

    private LayoutInflater mInflater;

    public Context context;
    public static List<myContacts> contacts;

    public AdapterContacts(Context context,List<myContacts> list) {
      mInflater = LayoutInflater.from(context);
      this.context = context;
      contacts= list;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

      ViewHolder holder;

      if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_contacts, null);
        holder = new ViewHolder();
        holder.contactName = (TextView) convertView.findViewById(R.id.contactName);
        holder.contactNumber = (TextView) convertView.findViewById(R.id.contactNumber);
        holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
        convertView.setTag(holder);

      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      myContacts contact = getItem(position);
      holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked) {
                 myContacts c = (myContacts) checkboxView.getTag();
                 c.setSelected(isChecked);
                 // to put that check of selection limit with error

            }
        });

      holder.checkBox.setTag(contact);
      holder.checkBox.setChecked(contact.isSelected());

      holder.contactName.setText(contact.getContactName());
      holder.contactNumber.setText(contact.getPhoneNumber());

        return convertView;

        }

    @Override
    public int getCount() {
        return contacts.size();
    }

    @Override
    public myContacts getItem(int position) {
        return contacts.get(position);
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }

    class ViewHolder {
        TextView contactName;
        TextView contactNumber;
        CheckBox  checkBox;
      }

}

any help would be appreciated.

Body:
i solved the issue "after scroll listview user can also again select more than 3 check boxex" Thanks for you patience
 set static int count = 0;

                     if (isChecked) {
                        count++;
                    } else if (!isChecked) {
                        count--;
                    }

                    if (count >= 4) {
                        buttonView.setChecked(false);
                        count--;
                    } else {
                        int getPosition = (Integer) buttonView.getTag();

                       contact.get(getPosition).setSelected(buttonView.isChecked());
                    }

And Most imprtant is that add count=0 in else and viewHolder.chkContact.setTag(position) after else;

if(convertView == null){

}else
{
 viewHolder = (ViewHolder) convertView.getTag();
 count=0;
 }
 viewHolder.chkContact.setTag(position);

`


问:
How can I secure an ASP .NET website that already uses Forms authentication?
I've got an ASP .NET website which uses Forms authentication to secure certain parts of the site. We have a test version of the site on a server and are making it available to partners over the web, e.g. at test.mydomain.com.

I need to secure all parts of the site so that only our partners can use it. Ideally it would be nice to have basic authentication pop up when they first hit the site, then have it work as normal thereafter, i.e. forms auth for certain areas.

However it seems ASP .NET and IIS don't support this. I'm aware of MADAM but that achieves something slightly different to what I need.

I'm considering restricting access by IP but that has two drawbacks, one it requires parters to "sign up" with their IP, and two, their IP could change.

Does anyone else have any suggestions?

答:
One solution is to check for the existence of a 'basic authentication' cookie on each request. If it doesn't exist or doesn't have valid data, don't allow access to the site. This could be checked in a base page that all pages inherit from or masterpage etc.

In order to set the cookie, you could create page that you send your partners to. It might just be at a obscure url, or require that they enter a password. Basically what ever security mechanism suits you, but once they 'pass the test', you set the cookie that gives them access to the site.

Then they would have access and be able to login using your existing forms authentication.

Does that make sense.


问:
Need my angular service to know when all component async operations have ended
I have an angular service that owns an Observable. I have multiple (variable number) of components subscribed to it that react executing async operations. I need my service to know when all these component async operations have ended.

This is an approach of my situation:

Filter Service

```<code>...

appliedFilter$: Observable<FormattedFilter[]> = new Observable<FormattedFilter[]>(
    o => (this.appliedFilter = o)
  ).pipe(shareReplay(1));
  private appliedFilter: Observer<FormattedFilter[]>;

  onFiltersApplied(filters: Filter[]): void {
    if (this.appliedFilter) {
      const formattedFilters = this.formatFilters(filters);
      this.appliedFilter.next(formattedFilters);
    }
  }

...
</code>```

Filtrable Component 1

```<code>...

this.filterService.appliedFilter$.subscribe(filters => {
  // multiple pipelined async operations
});

...
</code>```

Filtrable Component 2

```<code>...

this.filterService.appliedFilter$.subscribe(filters => {
  // multiple pipelined async operations
});

...
</code>```

Filtrable Component 3

```<code>...

this.filterService.appliedFilter$.subscribe(filters => {
  // multiple pipelined async operations
});

...
</code>```

So what I need is the Filter Service to notice when all components have applied the received filters via appliedFilter$ Observable and when all the filtered data is finally loaded.

The aim of this is to prevent the user to update the filters before all components have finished their filtering process.

Thanks!

答:
Are you sure you need to wait till components will be updated instead of updating components respectively to filter changes?
In majority of nice, user-friendly apps approach seems to be different:
If some component didn't finish updating while new filter applied - updates are just cancelled and started new.

In your case it can be achieved using rxjs switchMap operator. This operator allows you do exactly what I just said - give up on current async operations and start new if new emit comes.

Here is an example:

```<code>...

this.filterService.appliedFilter$
    .pipe(
        switchMap(
            filters => { return yourObservableChain()} // chain is your async opeartions
        )
    )
    .subscribe(); // you have only the most relevant values here

...
</code>```

So, what going here:

When new filter is applied yourObservableChain is called (it can be http request or any other things you mean when you said (async operations).

If during those operations new filter applied again - those old would be ignored, calls would be cancelled and new operations will start.

Only the most relevant result will come to the subscribe.

Note, that switchMap must return an observable. Here is one more short example of its usage in scope of Angular (with http calls).

```<code>import { switchMap } from 'rxjs/operators'; // don't forget

... your components code:...

this.triggerSubject$.pipe( // assume this emits with some urls
    switchMap(data => { // assume new url is a prop of data
      return this.http.get(data.URL); // returns observable
    })
).subscribe(results => {
   // having only fresh results here
   // because switchMap cancelled other requests
   console.log(results) // or do whatever you need
})
</code>```

Body:
I have an angular service that owns an Observable. I have multiple (variable number) of components subscribed to it that react executing async operations. I need my service to know when all these component async operations have ended.

This is an approach of my situation:

Filter Service

...

appliedFilter$: Observable<FormattedFilter[]> = new Observable<FormattedFilter[]>(
    o => (this.appliedFilter = o)
  ).pipe(shareReplay(1));
  private appliedFilter: Observer<FormattedFilter[]>;

  onFiltersApplied(filters: Filter[]): void {
    if (this.appliedFilter) {
      const formattedFilters = this.formatFilters(filters);
      this.appliedFilter.next(formattedFilters);
    }
  }

...

Filtrable Component 1

...

this.filterService.appliedFilter$.subscribe(filters => {
  // multiple pipelined async operations
});

...

Filtrable Component 2

...

this.filterService.appliedFilter$.subscribe(filters => {
  // multiple pipelined async operations
});

...

Filtrable Component 3

...

this.filterService.appliedFilter$.subscribe(filters => {
  // multiple pipelined async operations
});

...

So what I need is the Filter Service to notice when all components have applied the received filters via appliedFilter$ Observable and when all the filtered data is finally loaded.

The aim of this is to prevent the user to update the filters before all components have finished their filtering process.

Thanks!

Body:
Are you sure you need to wait till components will be updated instead of updating components respectively to filter changes?
In majority of nice, user-friendly apps approach seems to be different:
If some component didn't finish updating while new filter applied - updates are just cancelled and started new.

In your case it can be achieved using rxjs switchMap operator. This operator allows you do exactly what I just said - give up on current async operations and start new if new emit comes.

Here is an example:

...

this.filterService.appliedFilter$
    .pipe(
        switchMap(
            filters => { return yourObservableChain()} // chain is your async opeartions
        )
    )
    .subscribe(); // you have only the most relevant values here

...

So, what going here:

When new filter is applied yourObservableChain is called (it can be http request or any other things you mean when you said (async operations).

If during those operations new filter applied again - those old would be ignored, calls would be cancelled and new operations will start.

Only the most relevant result will come to the subscribe.

Note, that switchMap must return an observable. Here is one more short example of its usage in scope of Angular (with http calls).

import { switchMap } from 'rxjs/operators'; // don't forget

... your components code:...

this.triggerSubject$.pipe( // assume this emits with some urls
    switchMap(data => { // assume new url is a prop of data
      return this.http.get(data.URL); // returns observable
    })
).subscribe(results => {
   // having only fresh results here
   // because switchMap cancelled other requests
   console.log(results) // or do whatever you need
})


问:
Unable to parse JSON data returned via fetch method in React
Before marking it duplicate would be great if you please read once. I really, searched on this.
I am writing a React app to generate meme. I can connect the REST API successfully and able to fetch data. The problem is, while trying to parse data, I am getting an error which summarize that I am trying to access an undefined object, which I am not.

I tried same code statically (without React's rendering flavor) in another editor and it is working fine.

Here is my code,

```<code>class App extends React.Component{

    state = {memes : []};

    componentDidMount(){
        fetch(
            `https://api.imgflip.com/get_memes`

        ).then(
            (response) => {
                if(response.ok){
                    return response;
                }else{
                    console.log('no response');
                }
            }
        ).then(data => data.json()).then(data => {
            console.log(data); //This is getting printed fine
           // console.log(data.memes[1].name); //un-commenting this is throwing error that 'Cannot read property '1' of undefined'
            this.setState({memes:data.memes});

        });
 }
    render(){
        if(this.state.memes.length > 0){
            //For this I am getting error
            //Uncaught TypeError: Cannot read property 'length' of undefined
            console.log('array length is : ' + this.state.memes.length);
        }else{
            //This is printed fine
            console.log('Here array length is : ' + this.state.memes.length);

        }
        return (
            <div>
                <MemeImage/>
            </div>
        );
    }
}

export default App;
</code>```

The problem is, during the second time rendering (after data is fetched) React assuming data.memes doesn't exist which is absurd for me. As per my console log, it exists.
EX:

```<code>data:
memes: Array(100)
0: {id: "112126428", name: "Distracted Boyfriend", url: "https://i.imgflip.com/1ur9b0.jpg", width: 1200, height: 800, …}
1: {id: "87743020", name: "Two Buttons", url: "https://i.imgflip.com/1g8my4.jpg", width: 600, height: 908, …}
2: {id: "102156234", name: "Mocking Spongebob", url: "https://i.imgflip.com/1otk96.jpg", width: 502, height: 353, …}
3: {id: "129242436", name: "Change My Mind", url: "https://i.imgflip.com/24y43o.jpg", width: 482, height: 361, …}

</code>```

I checked the demo data as below from the respective website. As per this, data.memes[0].name is perfectly valid. I tried it and it worked.

```<code>    {
    "success": true,
    "data": {
        "memes": [
            {
                "id": "61579",
                "name": "One Does Not Simply",
                "url": "https://i.imgflip.com/1bij.jpg",
                "width": 568,
                "height": 335,
                "box_count": 2
            }
    ]
    }
  }
</code>```

But really, clueless what is happening during React rendering, that it is fetching the 'data' object but can't access properties inside. Any help regarding what I am failing to understand about React's rendering would be very much appreciated.

答:
Use this code

```<code>this.setState({memes:data.data.memes});
</code>```

When you console.log your data

```<code>console.log(data)

</code>```

You get

```<code>{
 data: Object
 success: true
}

</code>```

So you need to go inside data to access the memes,

Body:
Before marking it duplicate would be great if you please read once. I really, searched on this.
I am writing a React app to generate meme. I can connect the REST API successfully and able to fetch data. The problem is, while trying to parse data, I am getting an error which summarize that I am trying to access an undefined object, which I am not.

I tried same code statically (without React's rendering flavor) in another editor and it is working fine.

Here is my code,

class App extends React.Component{

    state = {memes : []};

    componentDidMount(){
        fetch(
            `https://api.imgflip.com/get_memes`

        ).then(
            (response) => {
                if(response.ok){
                    return response;
                }else{
                    console.log('no response');
                }
            }
        ).then(data => data.json()).then(data => {
            console.log(data); //This is getting printed fine
           // console.log(data.memes[1].name); //un-commenting this is throwing error that 'Cannot read property '1' of undefined'
            this.setState({memes:data.memes});

        });
 }
    render(){
        if(this.state.memes.length > 0){
            //For this I am getting error
            //Uncaught TypeError: Cannot read property 'length' of undefined
            console.log('array length is : ' + this.state.memes.length);
        }else{
            //This is printed fine
            console.log('Here array length is : ' + this.state.memes.length);

        }
        return (

                <MemeImage/>

        );
    }
}

export default App;

The problem is, during the second time rendering (after data is fetched) React assuming data.memes doesn't exist which is absurd for me. As per my console log, it exists.
EX:

data:
memes: Array(100)
0: {id: "112126428", name: "Distracted Boyfriend", url: "https://i.imgflip.com/1ur9b0.jpg", width: 1200, height: 800, …}
1: {id: "87743020", name: "Two Buttons", url: "https://i.imgflip.com/1g8my4.jpg", width: 600, height: 908, …}
2: {id: "102156234", name: "Mocking Spongebob", url: "https://i.imgflip.com/1otk96.jpg", width: 502, height: 353, …}
3: {id: "129242436", name: "Change My Mind", url: "https://i.imgflip.com/24y43o.jpg", width: 482, height: 361, …}

I checked the demo data as below from the respective website. As per this, data.memes[0].name is perfectly valid. I tried it and it worked.

    {
    "success": true,
    "data": {
        "memes": [
            {
                "id": "61579",
                "name": "One Does Not Simply",
                "url": "https://i.imgflip.com/1bij.jpg",
                "width": 568,
                "height": 335,
                "box_count": 2
            }
    ]
    }
  }

But really, clueless what is happening during React rendering, that it is fetching the 'data' object but can't access properties inside. Any help regarding what I am failing to understand about React's rendering would be very much appreciated.

Body:
Use this code

this.setState({memes:data.data.memes});

When you console.log your data

console.log(data)

You get

{
 data: Object
 success: true
}

So you need to go inside data to access the memes,


问:
Non-recursive search on the file system
I want to search for files only under the parent directory and ignore all the other subd irectories with in the parent directory. However the script is searching for files in all the directories within the parent directory.</p>

```<code>Get-ChildItem -File -Path "\\flamingdev\files\inbound\","*.csv" -Depth 0`
| Select-Object -ExpandProperty FullName`
| Add-Content -Path "\\flamingdev\files\input\files.txt"
</code>```

答:
To get all files, do not specify -Recurse or -Depth, just use -Filter:

```<code>Get-ChildItem -File -Path "\\flamingdev\files\inbound\" -Filter "*.csv"
</code>```

By using -Path "\\flamingdev\files\inbound\","*.csv" you just specify two different locations for the search:

```<code>\\flamingdev\files\inbound\
*.csv
</code>```

Title: Non-recursive search on the file system

Body:
I want to search for files only under the parent directory and ignore all the other subd irectories with in the parent directory. However the script is searching for files in all the directories within the parent directory.

Get-ChildItem -File -Path "\\flamingdev\files\inbound\","*.csv" -Depth 0`
| Select-Object -ExpandProperty FullName`
| Add-Content -Path "\\flamingdev\files\input\files.txt"

Body:
To get all files, do not specify -Recurse or -Depth, just use -Filter:

Get-ChildItem -File -Path "\\flamingdev\files\inbound\" -Filter "*.csv"

By using -Path "\\flamingdev\files\inbound\","*.csv" you just specify two different locations for the search:

\\flamingdev\files\inbound\
*.csv


问:
how to find sum and count of duplicates values in pyspark?
i have dataframe dd1

```<code>colA    colB    Total
 A       A        12
 A       A         1
 B       B        45
 B       B         0
 B       B         5
 C       C         1
 D       D         12
</code>```

and i want output like this dd2:

```<code>colA    colB    count  Total
 A       A        2      13
 B       B        3      50
 C       C        1       1
 D       D        1      12
</code>```

In count column the value is how many time it occurred and Total column contain sum of Total.

答:
Try this - </p>

```<code>from pyspark.sql import functions as F

dd2 = dd1.groupBy('colA','colA').agg(F.count('colA').alias('count'),F.sum('Total').alias('Total'))
</code>```

Body:
i have dataframe dd1

colA    colB    Total
 A       A        12
 A       A         1
 B       B        45
 B       B         0
 B       B         5
 C       C         1
 D       D         12

and i want output like this dd2:

colA    colB    count  Total
 A       A        2      13
 B       B        3      50
 C       C        1       1
 D       D        1      12

In count column the value is how many time it occurred and Total column contain sum of Total.

Body:
Try this -

from pyspark.sql import functions as F

dd2 = dd1.groupBy('colA','colA').agg(F.count('colA').alias('count'),F.sum('Total').alias('Total'))


问:
Starting windows service programatically using impersonation
I've been searching for an answer for my problem for hours but after trying lots of suggestion I'm still stuck.

I have a C# Windows form based application I work on and I have to launch a windows service (also part of the solution) programatically (when the user clicks the appropriate button). This part is already in place - I can launch the service but... I have some problems in Windows 7 and 2008 Server.

The problem is that I can't do it as my application is loaded by the machine administrator but as a filtered standard and not as full administrator (more info here). If we launch the application as Administrator it works fine, but I don't want to bother the user to do it every time.

I would like to know if it is possible to pop the  Windows confirmation screen when the user enters the form where he can start the service - as a full administrator.

Any ideas?

Thanks

答:
IIRC - you can't elevate an existing processes privileges, you would need to spawn a new process to perform the operation which requires it.

Found a previous question which further explains this.