How to connect one set of wire (+ ground wire) to outlet

Question: So I've been going through the house and have been updating our outlets and it usually involved connecting two sets of wires and a ground wire. Today however, I ran into a set up that consisted of one set of wires (one black wire, one white wire and one ground wire) and am unsure how to proceed.
So here is an image I took of all of the wires that need to be connected to an outlet:

This was the original outlet, where the wires were inserted into the socket that I have circled in white. The white wire was connected to the left side, black wire was connected to the right side, and the copper wire was connected to the screw on the bottom.

And this is the outlet I am trying to update it with:

As of now, I have tried:

black wire to top brass terminal, white wire to top silver terminal
black wire to top brass terminal, white wire to bottom silver terminal
black wire to bottom brass terminal, white wire to bottom silver terminal
black wire to bottom brass terminal, white wire to top silver terminal

And of course, I had the copper wire connected to the grounding terminal on the bottom with each of these set ups, but none of these set ups seem to work.
Can anyone point out where I am making an error?
Thanks!
Comment: I think your _error_ may be in thinking that one set of wires does one outlet and the other set does the other outlet.  In normal usage, one set of wires brings power in, and the other set takes power out to the next outlet.  You have now found the end of the chain.
Comment: BTW, a friend of mine in the insurance business says to never use those push-in connectors (always use the screws, like you're doing) to reduce the risk of fire.
Comment: If you know that both this current outlet and the previous one that you replaced are controlled by the same switch it may make sense to go back and re-check the work on the previous one. It is possible that a wire ended up with a loose connection. It could be a loose connection in a wire nutted bundle in the back of the electrical box.
Comment: The black (hot) wire goes on the brass side.  The white (neutral) wire goes on the silver side.  The bare copper wire is ground and goes on the terminal that connects to the mounting bracket.  If you do this and the outlet isn't "live" (after turning on the breaker) then there's a problem somewhere else.
Comment: All those combinations are correct. Normally I warn people not to experiment, but you confined your experimentation to very sensible values.  Did the outlet work before?  Have you tried turning on every switch in the  area?
Comment: Yes, it did work before. And when I was carrying out my tests, I inserted a lamp into two different outlets that was connected to the same switch: one was the outlet I was testing and the other was an outlet that I had just switched before this one and is functioning correctly so I don't think it was a mistake in that area.

I'll try switching out the outlet with a new one and will see if that changes fixes my problem tomorrow.
Comment: @Duston -- yeah, backstabs have a habit of stabbing their users in the back down the road, in a melty and sparky way....
Comment: Can you post photos of the inside of the box that provides the feed to the box in question please?
Comment: Did you remember to turn the power back on after doing the wiring?  Don't  laugh... it's been done before.
Answer: Are the tabs on the outlet intact? I am thinking the outlet prior may have a broken tab so the feed is not making it to this outlet. Many times only 1/2 of a switched outlet is switched we snap the tab between the top and bottom screw on the hot side take the switch to 1 and always hot to the other. In the case with 2 cables or 2 blacks and 2 whites in the box 1 is the hot the other feeds the next device , if that tab is broken on either side the next outlet will not get both the hot and neutral.
Answer: Is this outlet connected to a GFCI outlet? If so, the GFCI may have tripped during your experimentation, effectively disconnecting these wires from power.


DirectX 12 does not draw to the render target

Question: I've got a problem with DirectX 12 I cannot figure out by myself. I wrote a small program that should render a triangle onto the screen.
When I executed the application, however, there was no triangle visible. So I launched NVidia's nsight debugger. The weird thing is that the triangle has been drawn to the depth-stencil buffer but not to the back buffer.

If you need any code snippets please write it in the comments and I will post it.
Thanks in advance
Answer: You do not give a lot of details to work on, but if your depth buffer got updated, my first guess would be to look at the color write mask.
In D3D12_RENDER_TARGET_BLEND_DESC, you have a member named RenderTargetWriteMask, it has to be set to D3D12_COLOR_WRITE_ENABLE_ALL.


Albedo image map to color's Light Reflectance Value (LRV)

Question: In many datasets in the literature of both Computer Vision and Computer Graphics there is the albedo map of a scene represented as RGB images, which in principle corresponds to the diffuse reflecting component. The diffuse reflectance factor though of a material/surface is represented a one value, usually as ρ (rho), e.g. in the radiosity formulation. Thus, I am trying to understand how to go from an RGB representation to the corresponding diffuse value. I saw some people averaging the RGB values of the albedo map, e.g. for a pixel value (0, 168, 170) this would give:
((0/255) + (168/255) + (170/255)) / 3 = 0.441830065359477
however is just averaging enough/correct or there is a specific formulation.
I am puzzled quite some time now about it and I cannot really find a good answer. Thus, I would appreciate any feedback.
Comment: Radiosity (and any type of rendering formulation) needs to represent diffuse reflectance as a color, whether RGB or spectral, not as a single value for the whole spectrum. That wouldn't be correct; you wouldn't get colored bounce light e.g. in the Cornell Box.
Comment: @NathanReed this is not necessary. What you are saying is correct if you work on the color world. But in case that you do not care to represent the radiance/irradiance as color but rather than as energy color does not matter.
Answer: I am not aware of what LRV is and what is a usage of it. However, I can recommend using luma instead of simply averaging RGB values with equal weight:

https://en.wikipedia.org/wiki/Luma_(video)
https://en.wikipedia.org/wiki/Relative_luminance
Example of using luma - http://blog.simonrodriguez.fr/articles/30-07-2016_implementing_fxaa.html

Human eyes are more sensitive to green colors [1], that's why 16 bit (aka high color [2]) palettes, might prefer to use R5G6B5 format.
[1] https://en.wikipedia.org/wiki/Color_vision
[2] https://en.wikipedia.org/wiki/High_color
Comment: from my research you answer is almost correct the suggested way to do it is first to linearize your image, address the gamma correction and then get the luma.


How to aggregate filtered listapiview queryset and return value once

Question: How to perform aggregations on filtered querysets and return the value only once?
My existing code below. In the serializer, of course PZ.objects.all() makes it aggregate all items. I don't know how to get the queryset from the serializer level. To make the total value appear once, it would be a good idea to add a field in the view. However, overriding def list(): makes the filtering stop working.
I need this because I am working on a table that shows documents with filtering capabilities. In addition, there will be pagination. After selecting, for example, a creation date range, the values of the documents must be summed.
View:
class PZListAPIView(ListAPIView):
    queryset = PZ.objects.all()
    serializer_class = PZModelSerializer
    filterset_fields = {
        'id': ['exact', 'in', 'contains', 'range']
    }

Serializer:
class PZModelSerializer(serializers.ModelSerializer):
    net_value_sum = serializers.SerializerMethodField('get_net_value_sum')
    class Meta:
        model = PZ
        fields = '__all__'

    def get_net_value_sum(self, obj):
        return PZ.objects.aggregate(Sum('net_value'))['net_value__sum']

Response:
[
    {
        "id": 41,
        "net_value_sum": 28.0,
        "status": "C",
        "net_value": "6.00"
    },
    {
        "id": 42,
        "net_value_sum": 28.0,
        "status": "S",
        "net_value": "10.00"
    }
]

Desired response:
[
    "net_value_sum": 16.0,
    {
        "id": 41,
        "status": "C",
        "net_value": "6.00"
    },
    {
        "id": 42,
        "status": "S",
        "net_value": "10.00"
    }
]

Answer: I managed to find a solution to this problem myself. You need to override the 'def list():' method while returning the filtered queryset. Then on this queryset in the view we return with the aggregated value. The code looks like this:
class PZListAPIView(ListAPIView):
    queryset = PZ.objects.all()
    serializer_class = PZModelSerializer
    filterset_fields = {
        'id': ['exact', 'in', 'contains', 'range']
    }

    def get_queryset(self):
        return PZ.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        net_value = queryset.aggregate(Sum('net_value'))['net_value__sum']
        return Response([{'net_value': net_value},serializer.data])

Comment: what about pagination?


How can I record Minecraft with Roxio PC Game Capture?

Question: Just bought Roxio PC Game Capture to record Minecraft sessions.
I've set up as per instructions but no matter what I try it doesn't want to record Minecraft.  Has anyone used this software with Minecraft successfully? If so, how can it be done?
Comment: Saying something "doesn't want" to work is the worst way to describe a problem. In what exact manner does it fail?
Comment: Just a note on the possible source of the problem: Minecraft uses OpenGL as the graphics library instead of DirectX like many PC games.  It's possible that your software can only tap into DirectX buffers.
Answer: I personally don't use Roxio Game Capture, but I do know that it is highly sensitive; my friend was having a few issues getting it to work too:

Start up Minecraft, THEN start up Roxio Game Capture (order matters)
Do NOT resize the game screen. Game Capture is especially sensitive

You should probably post more specific qualifiers with the problem though, for instance:

Your computer specs
The update version of Minecraft you are using (hopefully most recent)
The version of Roxio Game Capture that you are using (again, hopefully most updated)
Any and all mods of Minecraft you are running

Additional thought, unless you are bent on using Roxio Game Capture, check out Camtasia or Fraps, they are much more user friendly and versatile.
Comment: Hard drive space = smard drive shace, amirite?
Comment: Or Bandicam if you like hard drive space. :)
Comment: FRAPS may be friendly to use, but it's not exactly kind to your hard disk space...


Scroll throttle how to choose a good amount for miliseconds?

Question: I am throttling a scroll event like so:
window.addEventListener('scroll', throttle(() => {
    console.log('scroll event triggered with throttle');
}, 150));

Because I do not want the scroll event to trigger 100's of times per second when somebody scrolls I have throttled it with a lodash throttle function.
I have read up on numerous articles which talk about doing this for obvious performance reasons but none talk about what kind of amount to set for the milliseconds on the throttle.
Of course this might depend on the use case and what code actually gets executed within the throttle. In my case I am doing a viewport check to see if something is still within the viewport.
How would you try and find a suitable amount for the milliseconds? Of course I would love to go as low as possible because it will fire an AJAX requests faster when it comes to an infinite scroll but I also do not want to cause performance issues.
It is hard testing this on a high-end desktop because I will probably never run into performance issues.
A pretty broad question but I would love to know (preferably in chrome) if this can be profiled for worst case scenarios.
Comment: I'm not a computer scientist by trade, so hopefully someone can chime in, but first you need a way to "measure" your current processing time, and also think about your min/max that you can handle. But the basics of a feedback control system would be using that measurement to either increase or decrease the current throttle time. So basically, as the processing time increases, increase the throttling, or as it decreases, decreases the throttling. Profiling it for worst case scenarios is just asking for a crappy mobile phone that runs at the speed of snail.
Comment: First off .... would you like to use someone else's accepted answer, and then, after spending time to implement it, later find out it does not work cross browsers? ... If not, then reconsider this accepted answer: https://stackoverflow.com/questions/47887564/flexbox-equal-column-height-set-dominant-column-height
Comment: Second...  when it comes to throttle an event, it boils down to how long time between each redraw you want. A common time is what [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) use, which is about 60 times per second. `requestAnimationFrame` is suggested here, [Events/resize](https://developer.mozilla.org/en-US/docs/Web/Events/resize), to be used to throttle the `resize` event, with a 66 ms set on its fallback using `setTimeout`
Answer: In your case, I suggest using IntersectionObserver.
There still will be performance considerations, but if you only want to check that content is visible, it is a relatively fast operation - the observer will give you this information on IntersectionObserverEntry.
When doing some animations, try to target your animation's frame rate of 60fps (one frame per 16ms) and use. If you want to handle orientation change or resize, I'd suggest to add a delay of 450ms (empirically counted duration of orientation change on iPad which in our experiments was largest value of all devices tested).
As for testing, chromium-based browsers allow you to throttle the CPU:

I'm not sure if it is available in other browsers.
In any case it might be a good idea to postpone code execution with requestAnumationFrame (for animations) or requestIdleCallback (for computations). It will help to avoid bottlenecks to some degree.


How to save set a boolean property in the viewmodel, if any of its properties binding to the text box has error in the input

Question: public class SampleViewModel
{
   public double InputA
   {get; set;}

   public double InputB
   {get; set;}

   public bool HasErrors
   {get; set;}
}

When this view model is binded to a usercontrol.xaml with two text boxes. And there is a main window which contains this usercontrol.xaml and has a submit button.
The submit button should be enabled only if the input values to the textboxes are doubles.
Answer: from my experience you can go two ways. if you want validate user input (eg. with IDataErrorInfo) then it would be best if all viewmodel properties are strings and then if the input is valid you can convert it to the model object type eg. double.
this is because if you create a double viewmodel property and bind to it the following can happen:

input a nice value 1.23 to textbox
through binding this value is in your viewmodel
the user set "abc" to the textbox
a binding exception is happen but the viewmodel is not notified and still 1.23
this means for the viewmodel all is still fine

another way would be to use behaviors or "special" controls to limit the input values to valid values.
Answer: Bind HasError field to enable property of button and update your model as below.
class SampleViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        private double inputA = 0;

        public string InputA
        {
          get { return inputA.ToString(); }
          set
          {
            if(double.TryParse(value, out inputA))
    {
     OnPropertyChanged("InputA");
             UpdateHasError();
    }
          }
        }

        private double inputB = 0;

        public string InputB
        {
          get { return inputB.ToString(); }
          set
          {
            if(double.TryParse(value, out inputB))
    {
     OnPropertyChanged("InputB");
             UpdateHasError();
    }
          }
        }

        private bool hasError;

        public bool HasError
        {
            get { return hasError; }
            set
            {
                hasError = value;
                OnPropertyChanged("HasError");
            }
        }

        private void UpdateHasError()
        {
            //If inputA and inputB decimal we update hasError
            if(inputA > 0 && inputB > 0)
                HasError = true;
            else
                HasError = false;
        }
    }

Edit : Added UpdateHasError() calling code.
Comment: It because you bind textbox text property to a double property. Change its type to string and cast it into double inside setter.

Check updated code..
Comment: Who calls UpdateHasError?
Comment: Sorry.. I added UpdateHasError() calling part. It should be called when inputA or inputB updating.
Comment: In my case the setter property doesn't get fired when I am entering any illegal value. It just shows red border around the text box.
Comment: Is there any solution not changing the type from double to string?
Comment: did you look at my answer? the only way is to restrict entering  illegal values
Comment: Actually, I have used behavior.


Using button for input file in Vuejs issue

Question: I am trying to use a button for the input file to trigger. But the issue I am facing here is whenever I click on the button it takes me to http://localhost:3000/availability?vue-file-input= url instead of opening the file selector. Please help me find where I am going wrong.

 <button class="vue-button" @click="document.getElementById('fileInput').click()">Choose File
 </button>

{{ filename }}

 <input
   type="file"
   ref="file"
   style="display:none"
   name="vue-file-input"
   id="fileInput"
   :disabled="user.availability"
   @change="onFileSelected"
 >

Comment: please check this [answer](https://stackoverflow.com/a/63125006/8172857)
Answer: Use Vue Refs instead of querying the DOM, this should work just fine:

  <button class="vue-button" @click.prevent="$refs.file.click()">Choose File
  </button>

{{ filename }}

  <input
    type="file"
    ref="file"
    style="display:none"
    name="vue-file-input"
    id="fileInput"
    :disabled="user.availability"
    @change="onFileSelected"
  />

This is the jsfiddle showing that it works: https://jsfiddle.net/Lgc5rnzs
Comment: Yes i did try your answer it is the same issue. Whatever I try inside name="vue-file-input" it take me to that url.

in case I type name="file-input" then it take me to

http://localhost:3000/availability?file-input=
Comment: Or don't use a button at all... See e.g. https://bulma.io/documentation/form/file/ which demonstrate, that you can wrapp a input type file in a "button" that still uses the default html5 input mechanism.. :)
Comment: I have tried what you suggest above. It is still the same issue. I need to use button due to styling in our platform.
Comment: @user12763413 have you tried my answer? it should work fine.
Comment: @hammed-oyedele here is a jsfiddle with your answer, showing that it works: https://jsfiddle.net/sLmoyjv7/
Comment: I have updated the answer with "click.prevent" to disable browser's default action, try it again now.


Fish oil stained hardwood floor

Question: We have several fish oil stains that have soaked into our hardwood floor.  I have tried to clean it and sand it out but it does not seem to be coming up.  If I can't get it out, is there a way I can cover it up with special oil or sealant? We just moved into the house, so I couldn't tell you the most recent time it's been sealed.
Here is the picture of the stains
Answer: This can be more art than science for fixing small spots like that. A lot depends how far into the wood the oil penetrated. Often it can become a matter of spot sanding, staining, refinishing...
Two pretty safe options are baking soda & dawn. Start by putting 1/8" or more baking soda over each of the oil spots. Leave it a few hours to overnight. If that worked, you can try it again. Make sure to vacuum it very well.
After the baking soda, mix a couple to few drops of regular Dawn (not ultra, etc) into a glass of room temp to warm water. Use a cotton ball or q-tips to clean the area following the grain.
Between the above, this should take care of cleaning the surface. Do not use a brush or anything abrasive as that will hurt the finish.
Before recommending any other type of cleaner/de-greaser, we would need to know what kind of stain finish you have. Otherwise, it's easy to make it worse.
Do you know anything more about the floors? Do you have an inconspicuous area (e.g. closet) where you can test cleaners for compatibility (better safe than sorry, those are nice floors)...
Comment: These stains have been here quite a while.  Do you think the baking soda and dawn will still work? I, unfortunately, don't know anything about the floors.  The previous owners didn't leave any stains.  I could test behind our TV.  No one really sees that area at least.  Thanks for your suggestions!
Comment: Baking soda and hydrogen peroxide mixed together, approx equal portions. Can not be removed completely. Cover with another finish may help to hide it. It may change a color but at least everything will be even.
Comment: Finish based on tung oil is good for bare wood. Also protect from water absorbing. Danish oil is not bad too.

Fish oil stained hardwood floor


Why does the blade of my table saw stop?

Question: I have a cheap, old (but, until recently, serviceable) belt-drive, table-top table saw, Skil 10" model 3400.

Last week while cutting a 2x4, the blade stopped but the motor kept going.  I finished up with a hand-held circular saw and let the table saw cool down. When I came back to it, I looked it over.  The blade is still firmly attached to the shaft.  The nuts are secure and if I manually move the blade, the shaft turns.  When I turn it on, the blade turns (though it seems to lag the motor a bit) but when it makes contact with wood, it stops.  There's a weird, rhythmic ying-ying-ying noise when it is running.  I have some weak intuition that a bearing failed.
Any thoughts on further diagnosing -- or, better yet, repairing -- my saw?  Or should just hit Craig's List looking for a replacement?
Comment: Posting the make and model might get you more accurate answers.
Comment: Have you read through the documentation?
Comment: It's a 10" Skil, model 3400.  I have no documentation.  I might find something online, I guess.
Comment: Did I find and include the right model and photo?
Comment: Mine is a table-top (that is, no bench built in) and it's silver not red but certainly very close.
Comment: Manuals are [here](https://www.skiltools.com/parts-and-service/pages/owners-manuals-and-parts-lists.aspx); choose "Benchtop" from the popup menu and there are three flavors of 3400, each with user manual and parts list.
Answer: At this point I would take it apart. It's already broke you have nothing to lose. I had an older Delta saw that had a gearbox fail. The parts were more than I paid for the saw. It may not be a total loss though. Some of the older models had a router mount cast into the table. It was useless as a saw but made a dandy router table.
Comment: First, definitely a Model 3400.

I took it part far enough to see that the gear housing is full of metal filings. The teeth of the gears appear to be intact and when I slide the gear back in, turning the shaft seems to turn the motor without the slippage I saw before.  I may clean out the housing, grease it up, put it together and see what happens.  It's a start...
Comment: I cleaned it out and greased it up.  If anything, it sounds worse.  Now that I'm no this trail, I realize it sounds like the next stage of the gears aren't meshing. I got this free and parts would likely cost more than a second-hand saw of comparable quality.
Answer: Guessing, admittedly:
If the motor turns and the blade doesn't move, something is slipping between the two that shouldn't.
Direct-drive saw means no belt. There has to be some kind of linkage between the motor and the drive shaft unless the latter is built into the former (possible but unlikely). It sounds like that connection has come loose.
So I'd suggest checking  back along the drive shaft toward the motor for anything that looks like a connection, and see if there's a setscrew; if so, tighten that. Depending on what's going on, you may need to rotate the two pieces relative to each other to get the setscrew to line up with a flat for best hold.
Comment: Problem might be as simple as a loose nut on the motor shaft that lets the blade spin freely. The blade will still spin up because it's in contact with the shaft, but will have no power other than the momentum of the blade itself because it's not firmly attached to the motor.
Answer: Direct drive does not always mean what it says. Some of these so-called direct drive motors have a belt drive inside the casing.
Comment: Please explain how having a belt-drive table saw might cause the OP's problem. Thanks!
Answer: This is an old thread, but I'll respond anyway.  You've probably stripped the key in the output gear.  Take it to a machine shop, press it off and replace the key.
Comment: No gears in sight. Tightening the belt was all it needed.
Comment: @ChrisNelson, if it is a belt drive, calling it direct drive in the question will lead to answers appropriate to a direct drive machine.  Since the question is still attracting answers, it might be worth clarifying the terminology in the question.


dropdown selected value not setting and displaying blank text in angular js

Question: I am working on C#/MVC application with angularJS. I need to display dropdown on popup, If record already have value then by default that value should be selected otherwise default option choose an option.
I am able to bind dropdown and If I debug I am getting correct ng-model value but its displaying blank.
Here is controller code on pop up open click
$scope.ShowAdPopup = function (adId) {

  $scope.Popup.CategoryId = 0;
  $scope.Popup.InterestId = 0;
  $scope.Popup.SourceId = 0;

  var filteredData = $filter('filter')($scope.gridAdData, { id: adId }, true);

  if (filteredData.length > 0) {
     $scope.Popup.Id = filteredData[0].id;
     $scope.Popup.AdId = filteredData[0].adId;
     $scope.Popup.AdName = filteredData[0].adName;
     $scope.Popup.Category = filteredData[0].category;
     $scope.Popup.Interest = filteredData[0].interest;
     $scope.Popup.Source = filteredData[0].source;
     $scope.Popup.AdUrl = filteredData[0].adUrl;
     $scope.Popup.CategoryId = filteredData[0].categoryId;
     $scope.Popup.InterestId = filteredData[0].interestId;
     $scope.Popup.SourceId = filteredData[0].sourceId;
 }
 $("#divAddGroup").modal({ show: true, backdrop: 'static', keyboard: false });

}

And html is as below

Category

    <select class="form-control" name="categoryDrp" ng-model="Popup.CategoryId">
        <option value="">-- choose an option --</option>
        <option ng-repeat="item in CategoryData" value="{{item.id}}">{{item.categoryName}}</option>
    </select>

Now If I debug and I can see CategoryId setting correct id . e.g. 7 or 8 or 9 which CategoryData have already but its display 'blank' as first option if Id is available
If CategoryId is null then it display '-- choose an option --'  which is correct
Comment: have a look here- https://docs.angularjs.org/api/ng/directive/ngSelected
Comment: still not displaying correct value
Answer: Try ng-selected="item.id == Popup.CategoryId" as :
<select class="form-control" name="categoryDrp" ng-model="Popup.CategoryId">
  <option value="">-- choose an option --</option>
  <option ng-repeat="item in CategoryData" value="{{item.id}}"
          ng-selected="item.id == Popup.CategoryId">{{item.categoryName}}</option>
</select>


How can I show some text on a textbox in a user control by clicking a button in another user control?

Question: please be kind enough to note that I'm new to visual studio.I have a form named form1 in it I have 2 user controls namely uctxt and ucbtn. uctxt has a textbox named txt1 and ucbtn has a button named btn1.
I need to fill txt1 with some text by clicking btn1(I tried public modifiers). I searched everywhere on the internet for a solution for this and I found nothing.
I tried:
public void Btn1_Click(object sender, EventArgs e)
        {
            uctxt ucText = new uctxt();
            ucText.txt1.Text = "welcome";
        }

Comment: It is pretty easy to implement. You need to do some more research. Long story short - you need a way to set a `uctxt.txt1.Text` value from a public member of your `uctxt` (public property or method) and a public event on your `ucbtn` which is rises on `ucbtn.btn1.Click` event rised.
Answer: You need at least to expose the OnClick event on the ucbtn:
public event EventHandler UserControlButtonClick;

protected void Btn1_Click(object sender, EventArgs e) =>
    if (this.UserControlButtonClick != null)
        this.UserControlButtonClick(this, e);

And the label on the uctxt:
public String UserControlLabelText
{
    get{return txt1.Text;}
    set{txt1.Text = value;}
}

After that you can use them both from the main form like this:
ucbtn1.UserControlButtonClick += new EventHandler(ucbtn1_ButtonClick);

protected void ucbtn1_ButtonClick(object sender, EventArgs e)
{
    uctxt1.UserControlLabelText = "your text";
}

Comment: I created an Object uctxt inside OnClick event to give refference to txt1,it did't work the code is.. private void Btn1_Click(object sender, EventArgs e)
        {
            uctxt ucText = new uctxt();
            ucText.txt1.Text = "welcome";
        }
Comment: thanks @Giulio Caccin, ucbtn1.UserControlButtonClick += new EventHandler(ucbtn1_ButtonClick); what is ucbtn1 here?
Comment: @jzen when i used numbers i mean an actual instance of one of your user controls. It means, if you have a user control, once you drag it inside the main form, visual studio create an automatic id for the dropped control and usually it calls it with the `name + number`. If you think it's the answer mark it as such.


gnome-terminal (also LibreOffice) doesn't launch any more

Question: I have a problem with gnome-terminal; since 2 or 3 days ago, it doesn't launch any more.
It began with LibreOffice, which for no reason I know of also didn't launch anymore.
I'm actually able to use Gnome-Terminal with VisualStudio Code, which contains terminal, but when I try to launch it with Ctrl+Alt+T or just click on it, nothing happens.
I got those following lines:
soyrimk@Process:~$ gnome-terminal
# Error creating terminal: Message recipient disconnected from message bus without replying
soyrimk@Process:~$ libreoffice
Application Error
soyrimk@Process:~$

I'm on Ubuntu 18.04.4 LTS.
Answer: I had this same symptom (though I doubt it was the same problem). In my case, it was due to an application I had built for my $HOME folder and for which certain libraries had been created under $HOME/.local/lib and perhaps $HOME/.local/libexec as well. Then I upgraded the OS (for me, it was going from 19.10 to 20.04) and I could no longer launch gnome-terminal.
My problem may not have been the same as yours, but if you can do an apt depends gnome-terminal that might give you a good starting point to look (in my case, I think it was the gir1xxx dependency). Gnome-terminal has a Python3 wrapper so it may involve something recent on your system involving Python3.
Comment: So I did the "apt depends gnome-terminal" and I got a lot of depends, and Python3 is also a part of it, I'm still looking how to deal with that
Comment: You may try doing a "sudo journalctl -xe" or "sudo less /var/log/syslog" (either one) to look at system log messages right after you try to run the gnome-terminal command. I don't think VS Code is running gnome-terminal, but just spawning a bash shell. Anyways, the above commands can give you some ideas as to what is going wrong and why.
Comment: Oh! Also, try doing a "sudo apt-get check" to make sure there are no broken packages on your system.


Django syncdb conflicting related_name when using inheritance and ForeignKey

Question: This time I think it's not me being stupid but an actual conflict. I have the below code (simplified):
from django.db import models

class Alpha(models.Model):
    relation = models.ForeignKey('Delta', related_name = 'reverse_relation', blank = True, null = True)

    class Meta:
        abstract = True

class Beta(Alpha):
    pass

class Gamma(Alpha):
    pass

class Delta(models.Model):
    pass

The problem is that Delta.reverse_relation could refer to an instance of Beta or an instance of Gamma. I would somehow have to provide multiple related_name values (or one that depends on the class name).I think the problem is clear but to be complete, the error (when running syncdb):
    app.beta: Accessor for field 'relation' clashes with related field 'Delta.reverse_relation'. Add a related_name argument to the definition for 'relation'.
    app.beta: Reverse query name for field 'relation' clashes with related field 'Delta.reverse_relation'. Add a related_name argument to the definition for 'relation'.
    app.gamma: Accessor for field 'relation' clashes with related field 'Delta.reverse_relation'. Add a related_name argument to the definition for 'relation'.
    app.gamma: Reverse query name for field 'relation' clashes with related field 'Delta.reverse_relation'. Add a related_name argument to the definition for 'relation'.
Is it possible at all to place the ForeignKey in the parent Alpha, or is the only way to cut-paste this code to Beta and Gamma? I prefer not to do that because it kind of defeats the point of inheritance if I can't define in the parent half the fields that all children share.
Any help is much apprectiated!
(If anyone can comment with why the error messages aren't in a code box I'll fix that.)
Comment: Found my own question through Google again. Happens more than I'd like to admit.
Answer: I think that you will find the following advice in the Django documentation helpful and relevant:
https://docs.djangoproject.com/en/1.7/topics/db/models/#be-careful-with-related-name
Essentially change the declaration of the relation field to:
relation = models.ForeignKey('Delta', related_name="%(app_label)s_%(class)s")

Best of luck...
Comment: Thanks for the reply, hope it helps more people to find this solution!
Comment: What if I have two foreign keys with same app labels? I m not able to find answer.
Comment: The `related_name` is simply a templated string with keywords `app_label` and `class`. If needed, you could specify the `related_name` for the first foreign_key as `"%(app_label)s_%(class)s_fk1_set"` and for the second as `"%(app_label)s_%(class)s_fk2_set"` (or any other string of your choice)


Non-interactive functional requirements software engineering

Question: I'm having a problem with listing some non-interactive functional requirements for building a project about "Smart food court system for a university" with self-service. In that system, customer can order through mobile app or machine, pay by e-wallet, and when ordering by machine, the machine will automatic print a bill after payment. I can't understand clearly what a concept non-interactive functional requirements in software engineering. And with the example that machine print a bill automatically after payment is a non-interactive functional requirements or not? Can anyone give more examples about non-interactive functional requirements to help me understand clearly? Thank you!
Answer: The concept of non-interactive requirement is not a  common nor well-defined terminology in software engineering.
Interactive requirements are about what the system shall do in response to a user action, or to enable a user action.
Automatically printing a bill is therefore an interactive requirement: even if the printing is by itself not interactive, the sheer fact of enabling the user to pick the bill makes it interactive.
Interactive requirements are captured in the use-cases or in UI requirements. Non-interactive requirements are all the rest, for example:

general business rules
requirements about the data objects to be managed, about their consistency, and how they relate to each-other;
non-functional requirements, such as operating constraints, or performance, security or maintainability related requirements.


60fps ingame vs 60fps on Youtube

Question: I've wanted to ask this question for a while now... Why doesn't my 200fps in game with Vsync off look as smooth as 60fps on Youtube? I play CS:GO and my game doesn't look as good as Youtube. Any explanations?
Comment: Short answer: because with Vsync turned off, the game/graphics card is updating the screen as fast as possible, (literally) not waiting for your monitor to catch up, which can lead to 'tearing' or screen artifacts as the monitor starts drawing a frame that has already been replaced. Youtube at 60fps is a reasonable framerate for your monitor, thus looks smoother
Comment: what do you mean by "look as good" you can increase graphic settings if you'd like, fps just means it doesn't stutter, ie it'll look smooth and not freeze for a second and then jump forward.
Comment: to expand on Robotnik: if the video frames were captured at a higher framerate (like 120fps) and then (temporally) downsampled to 30 or 60fps, this can improve quality, provided you are using an algorithm that does not merely delete every other frame
Comment: Unless your monitor is operating on 200 hz, it cannot display those 200 frames anyway. It only creates tearing and uses more power for no actually benefit. The "you need more than 100 fps on counter-strike" is a myth that people continue to fall for because they are uninformed..
Answer: Because your video card doesn't space those frames out in equal measures. So the resulting motion is janky.
Vsync helps somewhat, but there is much more real work to be done on the drivers by popular video accelerator makers before this improves much.

60fps ingame vs 60fps on Youtube


Error in setDefaultClusterOptions(type = .sfOption$type) :could not find function "setDefaultClusterOptions"

Question: I'm new here. I've been struggling with analysing some data with the BaSTA package, the data works ok after running the "Datacheck" code , but right after running the following code this happens:
multiout <- multibasta(object = datosJ, studyStart = 1999, studyEnd = 2018, model = "LO",
             shape = "simple", niter = 20001, burnin = 2001, thinning = 100,
             parallel = TRUE)

No problems were detected with the data.

Starting simulation to find jump sd's...  done.

Multiple simulations started...

**Error in setDefaultClusterOptions(type = .sfOption$type) :
  could not find function "setDefaultClusterOptions"**

I believe this error has something to do with the usage of "parallel = TRUE" which is a function of the snow package that comes incorporated in the BaSTA package and makes the analysis run faster. If I don't use parallel the analysis takes weeks in running  and I've been told that's not normal for the package I'm using.
Any help would be very helpful, thank you.
Answer: I came across this same behavior when using another R package that depends on snowfall. setDefaultClusterOptions is housed within a dependency of BaSTA so this is error message is because packages are not being loaded. Try calling library(snowfall) prior to running the BaSTA package command to see if that fixes it for you.
Comment: Hey, thank you. The snowfall package had already been called by that time. Somehow I managed to runned but now the analysis is taking way too long, something is not working because I was told it should take 2 minutes.


Microwave not heating: Should I pay a contractor to diagnose?

Question: My microwave is turning on, but it's no longer heating food. It just runs until the timer finishes, but the food is not being heated.
I read a few articles online that say microwaves aren't easy for DIYers to troubleshoot, and that they can be costly to repair.
So is it worth paying a contractor to come out and diagnose the problem (and potentially tell me I need a new microwave), or should I just bite the bullet and buy a new microwave?
Comment: For most portable microwaves the cost of "diagnosis" and the cost of a new microwave are not much different. IF you can just haul it into an appliance shop the price might be more reasonable - or not.
Comment: Be careful, even when unplugged there can be quite a charge in the high voltage capacitors. Discharge these first!
Comment: Sounds like the magnetron is broken. If the microwave isn't expensive (less than $200-300), it's probably not worth it.
Comment: Older ones had user replaceable ceramic cartridge fuses, see if there is a service panel in the back and take a look (unplug first of course). Check for continuity and replace if needed, might save you some $$.
Comment: Is it an expensive microwave? It's going to be around $100 just to have someone look at it. If it's old at all, I'd just buy a newer one.
Comment: It's a Kenmore microwave from Sears, so we're not talking top of the line. It's also mounted above the range, so I'm assuming it would cost extra to service because of that.
Answer: Depends on if it was expensive, if it is mounted, and how much the one you'd buy would cost. (and install)
Encountered a similar problem, once it was a safety switch for the door, another time it was a burnt out magnetron. Worth replacing either on a $600+ unit. $200? Just buy a nice new clean one.
Comment: Diagnosed by pushing up on the handle. That would engage the safety catch and it would work. Not sure how we narrowed it down to the magnetron. We must have took it all apart and checked everything with a tester.
Answer: I would just get a new microwave.  Almost assuredly this is cheaper/better in the long run.
I might consider having it fixed if two conditions were met - that I generally knew what was wrong and if I knew someone that I could really trust.
The fact is having someone fix something so specialized that you really can't see or check yourself is hardly ever a good recipe.  You can get a really good over the range microwave for $400-500.  Your contractor could could charge you $200-300 easy.  And then you are stuck with a machine that could have other issues or never had an underlying issue fixed.  Let's say he replaces a relay... fixed.  Well what caused the relay to go bad?  So what happens when same issue comes up again.  Contractor then offers to fix it for a discount or maybe free within 30 days.
The fact that microwaves have a shelf life now of 8-10 years (older ones would last 30), a 5 year old microwave that was $500 is at best $250 worth to you allowing for depreciation.  So basically if you pay $200-250 you are continuing with your used microwave vs. new for the same price.
Comment: Mine is passing 20, I guess. Must be "older." An acquaintance has shorter service life - likes to use the µwave as a timer, sometimes forgets to hit the right mode, doesn't have anything in the oven, kills the tube. Has at least learned to buy cheap ones ;-)
Comment: That's a pretty expensive timer..
Answer: Replacing is NOT a good option for some models--Repairs are NOT that hard.
Hate to offer this advice, since I've heard of quite a few DIY that have been killed attempting this, since the power is, or can be still stored in the capacitor of the microwave, and KILL you dead, WHEN unplugged!  Still, you can DIY or find a friend that can easily do this.
OTOH, I've got two very nice KitchenAid microwaves.  I replaced the plain one that was installed over the oven, with a convection/microwave, (cost > $550).  Eventually after 14 years, they BOTH "broke"--no heat, but everything else worked fine.
There is no possible good way to replace these microwaves inexpensively, since there is trim work that just isn't going to match properly or easily.  So for me, the best option was to learn how to do it SAFELY and inexpensively.  My cost for replacing both magnetrons was less than $80 total.  It took about an hour each, plus a few hours learning and a few hours properly sourcing the part.  Note that I am already an "almost" a real electrical and electronics tech/engineer.  I will walk through what I did:
Troubleshooting:
If it won't heat water at all, but everything else is working fine, then proceed.
Safety:
Before you take it apart, KNOW that ANY of the exposed wiring can KILL you.  Treat it all like a loaded gun.  If charged, it has 5,000 high current volts available to do you in.  After unplugged, FIND the exposed capacitor.  You will need to ensure that the leads have been shorted together and also shorted to ground to the chassis.  I've seen others use insulated screwdrivers to do this, which are likely fine.  I built my own resistor network that both would discharge a 5,000 volt capacitor, but do it slowly, and would not arc over the resistors that were not natively rated for > 5000v.  Do NOT "check" the live voltage, unless you have a high voltage probe made for tube TVs, rated over 20,000 volts.  Now, make or get a permanent wire to short that capacitor while working on it.
Check the components:
Transformer
I checked the transformer with an ohm meter, on all the leads, and also checked it to ground.  (I don't remember if ANY of the leads are supposed to be grounded, but if not, make sure it is infinite..)  Also look for anything that might look burned or loose connections and repair if necessary.  If the DOOR is broken, especially mechanically, do NOT try to replace!!  If this leaks, it can slowly kill you--microwaves are really nasty, if let out of that box.
Diode
With an ohm meter, verify that it works--conducts in one direction only.
Capacitor
You should be able to use the ohm meter to first start charging the capacitor, and then reverse the leads, and charge it in reverse.
Magnetron
There are two wires that go to a heating element inside, designed to use 2-3v.  That element is most certainly burned out, but you should be able to check it, (and check on the new replacement you just bought.)  NOTE that neither of my broken magnetrons showed ANY problem, and yet still did NOT work!  The element showed it was not broken or grounded.
Buying a replacement magnetron
You can buy the "official" KitchenAid for about $150-$200 if you are stupid, or buy the exact same part elsewhere.  These are difficult and expensive to make, so there are really only a few models, and they are all private labeled and multiplied by 5x cost as a profit.
The magnetrons are not the same for Panasonic and likely others.  GE, Amana and likely about 30 others are all going to use the "same" magnetron.  The only differences will be how they mount, which is important.  Notice which direction the main leads in the center come down from the magnetron, which will either follow, or oppose the exposed fins.  This 90 degree mount determines MOST of the model, and possibly if the bolts come mounted on the frame or not.  VERIFY YOUR part by looking up your model # microwave.  But, the photos should match.  You can buy these from Amazon, Ebay, or other specialty parts appliance sites for $35 - $45 DELIVERED.  When you buy, you might also buy and replace the light bulb.
Unscrew the old, and screw on the new magnetron TIGHTLY, so the microwaves don't leak out.  Connect all the leads up.  Plug it in with a cup of water, and test it.  (IF you have a chassis lockout switch, with obviously won't work until you reconnect it).
Reassembly
Now for the DANGEROUS part....  Remember that residual charge??  First unplug it, and ASSUME that all those wires are hot.  You can either discharge that capacitor again, or find a way to stay away from then with the case.  The circuit is SUPPOSED to self-discharge to safety, but YMMV so don't chance it.  Once that it is reassembled, retest it before re-mounting it.
That's it.... Leave me a comment if you'd like me to post some links for sourcing the magnetron later.

BONUS
  After replacing, do NOT toss those magnetrons.  They are not named that way for nothing.  Pry the case apart so you can remove the fins and the tube.  You will find two HUGE POWERFUL magnets.  Remove the fins, and then carefully remove the magnets.  If you've saved the box it was shipped it, or a larger one with foam, STORE your magnets carefully, so stray energy doesn't destroy other things.  Be more careful that you think you need to be, since they can break fingers and pinch painfully.  I have the four I removed, and can use them to pick up nails from roofing or re-find anything ferrous in the yard.
Answer: my microwave was turning, counting down and doing everything except producing heat. l later found out l had misplaced the roller ring during shifting . putting the roller ring back made everything work normally.


A simple collision problem with a not so simple (to me) solution. I could use some help.

Question: I know this is a Physics problem and the Physics is fairly simple, but the equation I need to solve seems a bit more difficult than I anticipated. I'm curious if there is a different approach to solving this problem mathematically and/or a more simple solution.
Suppose I have two point particles, Particle 1 is at the origin $(0,0)$ and Particle 2 is at $(x_0, y_0)$. Particle 1 travels at the speed of light $c$ (for this problem we are ignoring special relativity). Particle 2 travels with a constant velocity $(v_{x_0}, v_{y_0})$. We know the particles will collide at some unknown location $(x, y)$. So our goal is to solve for $x$ and $y$. Below is a picture of the situation.

We can use simple kinematic equations to describe the motion of Particle 2:
$$x = x_0 + v_{x_0}t$$
$$y = y_0 + v_{y_0}t$$
We know that they will collide, which means they must collide at the time it takes Particle 1 to travel to the point $(x,y)$ which is described by:
$$t = \frac{\sqrt{x^2+y^2}}{c}$$
Plugging this into our previous two equations give us the following:
$$x = x_0 + v_{x_0}\frac{\sqrt{x^2+y^2}}{c}$$
$$y = y_0 + v_{y_0}\frac{\sqrt{x^2+y^2}}{c}$$
I plugged the two equations into Wolfram and I ran out of computing time. I am wondering if there is any other way to go about solving this problem. Is my thought process and final equations correct? If anyone can shed some light on my problem I would be very thankful.
Comment: You have equations for $x$ and $y$, plug them into $x^2+y^2=(ct)^2$ and solve the resulting quadratic equation for $t$.
Comment: What is the direction of velocity of the first particle?
Comment: The first particle at the origin, Particle 1, has velocity $c$(speed of light in a vacuum) and it's in the direction of the unknown final position. To me this is a bit odd and is just the nature of the problem. The first particle has to "know" where they will collide before it initializes its direction.
Answer: Instead of trying to compute the collision point directly, compute the collision time (as Rahul commented). Using the distance formula that you used, solve $$(x_0+v_{x_0}t)^2+(y_0+v_{y_0}t)^2 = c^2t^2$$ for $t$, take the least nonnegative solution, and substitute that into the equations of motion of particle 2.
Answer: Since particle 1 is traveling in an unknown direction, your approach is correct.
Otherwise it would just be a linear equation.
I would eliminate the square root of your final equation, as it might confuse Wolfram. It might assume complex variables and then simple rules known from real square root cannot be applied anymore.
You get
$\left(\frac{x - x_0}{v_{x_0}/c}\right)^2  = x^2 + y^2$
$\left(\frac{y - y_0}{v_{y_0}/c}\right)^2  = x^2 + y^2$
which is a system of two quadratic equations in two variables. You solve it by solving one equation for the one variable and plugging the result into another. Perhaps Wolfram will give you the solution when you plug in the two equations above, or you do it by hand.
However, you will get multiple solutions, which you need to check if they are correct. This is because the squaring operation introduces new solutions.
Comment: You were correct to say that square roots caused Wolfram to malfunction in some way. Nonetheless, solving for x and y directly using those equations gives quite complicated equations that are a bit more tedious to compute. Using the method suggested by Raul did the trick! Thanks for the input though; now I know  Wolfram doesn't like square roots!
Answer: Take a loot ak the following picture:

Particle 1 starts in $A=(0.0)$, particle 2 starts in $B=(x_0,y_0)$. Particale 2 travels with velocity $\lvert v \rvert$ in the direction given by $v$. Both particles meet at point $C=(x,y)$, which is unknown.
Note that the the value of $\beta=\angle ABC$ is fixed and can be calculated, it is the angle between the lines trough $A$ and $B$ and the velocity vector $v$. If the time it takes for the particles to meet is $t$, we have
$$\overline{AC}=ct, \quad \overline{BC}=\lvert v\rvert t$$
From this follows by the law of sine
$$\frac{\sin \alpha}{\sin{\beta}} = \frac{\overline{BC}}{\overline{AC}} = \frac{\lvert v\rvert}{c},$$
That means $\sin \alpha$ can be calculated by what is given. Under the assumption that $\lvert v\rvert < c$ (a bit of physics), it can be shown that $\alpha$ must be the smaller (< $90°$) of the 2 values from $[0,180°]$ that has that sine value.
Since we now know 2 interior angle values of the triangle $ABC$, we can calculate the remaining one $\gamma$ at $C$ via $\alpha + \beta + \gamma = 180°$, anf finally apply the law of sine again to calculate $\overline{BC}$:
$$\overline{BC}=\overline{AB}\frac{\sin \alpha}{\sin \gamma}$$ and thus
$$ C = B + \overline{BC}\frac{v}{\lvert v \rvert}.$$


Encrypting SQL Server CE database

Question: How to encrypt and decrypt the SQL Server CE databases present in the Isolated Storage of WP7 app ?
I was able to copy the db from my emulator to the hard disk of my system. Now, How can I need a way to encrypt and decrypt this.
I wanted to decrypt the entire SQL Server CE DB on loading of the WP7 application and encryption of the DB on exit. How can I do this ?
This is my app.xaml.cs code
<code>private void Application_Launching(object sender, LaunchingEventArgs e)
        {
              // Code to Decrypt Database
        }

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
              // Code to Encrypt Database
        }
</code>
Answer: I would rather suggest not to encrypt CE database. XAP is already encrypted (after app gets published in marketplace) so I don't think one can easily explode xap and fetch the database. Other issue in encrypting is that (as of now) you loose the flexibility of editing or viewing data with well known SQL utilities (such as SSMS because the encryption mode is not supported)
So I doubt if encryption of wp database really solves problem on hand.
But if exchanged in development mode or the database is downloaded or uploaded from web, we might need encryption to prevent access to data.

Encrypting SQL Server CE database


Is it possible to query data from Whisper (Graphite DB) from console?

Question: I have configured Graphite to monitor my application metrics. And I configured Zabbix to monitor my servers CPU and other metrics.
Now I want to pass some critical Graphite metrics to Zabbix to add triggers for them.
So I want to do something like
$ whisper get prefix1.prefix2.metricName
> 155

Is it possible?
P.S. I know about Graphite-API project, I don't want to install extra app.
Answer: You can use the whisper-fetch program which is provided in the whisper installation package.
Use it like this:
whisper-fetch /path/to/dot.wsp

Or to get e.g. data from the last 5 minutes:
whisper-fetch --from=$(date +%s -d "-5 min") /path/to/dot.wsp

Defaults will result in output like this:
1482318960  21.187000
1482319020  None
1482319080  21.187000
1482319140  None
1482319200  21.187000

You can change it to json using the --json option.
Comment: Finding files: `find /var/lib/graphite/ -name *.wsp`
Answer: OK! I found it myself: http://graphite.readthedocs.io/en/latest/render_api.html?highlight=rawJson (I can use curl and return csv or json).
Answer was found here custom querying in graphite
Also see: https://github.com/graphite-project/graphite-web/blob/master/docs/render_api.rst
Comment: It would be nice to have a solution not involving a webapp (whether accessed with a browser or curl).


When adding AutoPostBack="true" to DropDownList and clicking on item, it sends me to page "Resource could not be found"

Question: I had trouble getting the value a user selected from a DropDownList. I've figured out that I require a postback to get my values to reset and be able to get reassigned. (I've tried things like ClientIDMode="static" in the page control and doing "var dropDownList= $(<%= ddlNewCaseFiles.ClientID %>).val() ) however nothing seems to work. So I implemented this in my header:

and it seems to be getting the updated values selected. But for some reason when I click on an item it send me to the "Cannot find Resource" page. I'm guessing if I add an Updatepanel to my DropDownList it will probably fix it?(since it is only posting back my dropDownList). But I am having trouble with it.
this is my DropDownlist:

            Select new CaseFile:
        <asp:DropDownList runat="server" ID="ddlCaseFilesNew" DataSourceID="dsCaseFiles"
            DataTextField="Display" DataValueField="FileID"
            OnPreRender="ddl_PreRender" Width="300px" AutoPostBack="true"
            onselectedindexchanged="ddlCaseFilesNew_SelectedIndexChanged"/>

I've tried to implement it here but I'm getting a "UpdatePanel does not have a property name called "dropDownList"". Any help would be great fully appreaciated.:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
        <asp:DropDownList runat="server" ID="ddlCaseFilesNew" DataSourceID="dsCaseFiles"
            DataTextField="Display" DataValueField="FileID" OnPreRender="ddl_PreRender" Width="300px"
            AutoPostBack="true" onselectedindexchanged="ddlCaseFilesNew_SelectedIndexChanged" />
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddlCaseFilesNew" EventName="SelectedIndexChanged" />
        </Triggers>
    </asp:UpdatePanel>

Pre_render as requested:
 protected void ddl_PreRender(object sender, EventArgs e)
{
    DropDownList ddl = (DropDownList)sender;
    try
    {
        if (ddl.Items[0].Value != "-1")
            ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
    }
    catch
    {
        ddl.Items.Insert(0, new ListItem("--Select--", "-1"));
    }

}

Comment: can you show your code for: OnPreRender="ddl_PreRender" ?
Answer: if you wanna have it in the update panel

you should add the  the hidNewCaseFile control inside ContentTemplate  tags

Example :

 in the header

in the body

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

        <ContentTemplate>

            <asp:Label runat="server" ID="hidNewCaseFile" Text="Label"></asp:Label>
            <asp:DropDownList ID="ddlCaseFilesNew" AutoPostBack="true" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem>Uae</asp:ListItem>
        <asp:ListItem>KSA</asp:ListItem>
        <asp:ListItem>Lebanon </asp:ListItem>

    </asp:DropDownList>

        </ContentTemplate>

    </asp:UpdatePanel>

Also make sure that you have  <asp:ScriptManager runat="server"> </asp:ScriptManager >
before you use the update panel
Comment: No You do not need triggers becuase you defined the the DropDownList1_SelectedIndexChanged(object sender, EventArgs e) on the dropdownlist you attached OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"


how to map expression> with automapper

Question: CreateMap
Mapper.CreateMap<Unidade, unidadeDTO>();
Mapper.CreateMap<unidadeDTO, Unidade>();

public ICollection<Unidade> BuscarPorParametos(Expression<Func<Unidade, bool>> parametros)
{
    return Mapper.Map<ICollection<unidadeDTO>, ICollection<Unidade>>(unidadeDeTrabalho.UnidadeDAO.BuscarPorParametros(Mapper.Map<Expression<Func<Unidade, bool>>, Expression<Func<unidadeDTO, bool>>>(parametros)));
}

Automapper exception:

Missing type map configuration or unsupported mapping.
Mapping types: Expression1 -> Expression1
  System.Linq.Expressions.Expression1[[System.Func2[[Unidade, Dominio,
  Version=126.96.36.199, Culture=neutral,
  PublicKeyToken=null],[System.Boolean, mscorlib, Version=18.104.22.168,
  Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib,
  Version=220.127.116.11, Culture=neutral, PublicKeyToken=b77a5c561934e089]] ->
  System.Linq.Expressions.Expression1[[System.Func2[[unidadeDTO,
  Infraestrutura, Version=184.108.40.206, Culture=neutral,
  PublicKeyToken=null],[System.Boolean, mscorlib, Version=126.96.36.199,
  Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib,
  Version=18.104.22.168, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Destination path: Expression`1

Source value:
p => ((p.CodUnidade == 1) AndAlso (p.CodTrabalho == 1))
Comment: I don't think you can use automapper on `Expression`s. You normally use the expressions as part of queries, then automap the results of those queries to different classes.
Comment: Can you show the `CreateMap` statements?
Comment: Mapper.CreateMap();
Mapper.CreateMap();
Comment: OK, so you want to map regular objects. What are you trying to achieve with the second `Mapper.Map` statement? Right now, you're trying to copy an expression to another expression, but you clearly don't intend to do that (and it's impossible).
Comment: alright.
i need mapping filter from repository to dao.
Comment: Please be more specific. How would you achieve your goal without AutoMapper? That would really clarify it.
Answer: When working with Expressions and AutoMapper you need to use the Queryable Extensions namespace.
It uses a different syntax than normal auto-mapper. Normally you would use it in line with your query to get the resultset you want.
//---- Declared elsewhere
Mapper.CreateMap<Unidade, unidadeDTO>();
Mapper.CreateMap<unidadeDTO, Unidade>();
//----

public static IQueryable<unidadeDTO> ConvertToDTO(IQueryable<Unidade> source)
{
    return source.Project().To<unidadeDTO>();
}

Now you can write filters expressions against the new IQueryable and the changes will be propagated back up to the original SQL. This allows you to do things like this
public class OrderLine
{
  public int Id { get; set; }
  public int OrderId { get; set; }
  public Item Item { get; set; }
  public decimal Quantity { get; set; }
}

public class Item
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class OrderLineDTO
{
  public int Id { get; set; }
  public int OrderId { get; set; }
  public string ItemName { get; set; }
  public decimal Quantity { get; set; }
}

public class OrderDAL
{
    static OrderDAL()
    {
        Mapper.CreateMap<OrderLine, OrderLineDTO>()
            .ForMember(dto => dto.ItemName, conf => conf.MapFrom(ol => ol.Item.Name);
    }

    public List<OrderLineDTO> GetLinesForOrder(string itemName)
    {
      using (var context = new orderEntities())
      {
        return context.OrderLines.Project().To<OrderLineDTO>()
               .Where(i => i.ItemName == itemName).ToList();
      }
    }
}

Notice how I am using the property ItemName of the DTO to perform the filtering.

how to map expression> with automapper


Can website with high traffice bring down other websites

Question: I have a rookie question. Suppose we have a website (www.abc.com) on server 1 and a second website www.xyz.com on server 2 and the second website is referencing some files(css or javascript) on server 1. Can high traffic on server 1 slow down server 2?
Comment: Well, it certainly can slow down the apparent performance of server 2 if they share a net pipe. (I don't think there's really any good answer to this question other than to understand exactly what's going on and reason out the effects.)
Comment: If website 2 is google.com, and website 1 is hosted on a godaddy shared hosting account, then yes. (Point is, it depends on the situation).
Answer: Yes, It can slow down other websites which are hosted on same server or hosted on other server.
It can happen due to following few issues:

Hardware : if you used RAM with low capacity
IIS pooling
IIS caching

If you do not properly manage IIS it hampers server performance.
If you used IIS7 onward then IIS can internally manage 2nd and 3rd issue for you.
Answer: Yes, it is possible.  You can read about something related, the slashdot effect at wikipedia, that explains real cases in an informative way.
Comment: Thanks, the links is helpful. I never knew about it.
Answer: Yes. I've seen it happen. In the case I witnessed, server 2 was serving something more complex than just static files, it was a widget that displayed on the server 1's site. That widget in turn, did a DB query on server 2's DB, and the rest is history.
It's certainly less troublesome to server 2, if it's only serving static files, but again the short answer is yes, that the traffic can become a strain on server 2 no matter what is being served, if the traffic is high enough.


has anyone tried wambam no dig fence

Question: I need to replace 3 fence panels and posts and i can't find any contractor, i am guessing because it is a small job. The only contractor i was able to find wants $1500 without staning or hauling away the old fence which is more than i expected.
I found that there is a no dig wambam vinyl fence system. I ordered sample but i am curious if anyone here has any experience with this.
The main reason i am going this route is so that i can avoid digging and mixing cement. Also i couldn't find any pre-made 7ft wooden tranditional panels. 3 panels i have are made of 8ftx2 and one 5.5ft so i need to replace 21.5 linear ft. WamBam happen to have 7ft fence.
Answer: There is no set reason that you have to use cement to set the posts into the holes. In many instances it can be effective to simply dig the post holes, set the post into position and then dribble the dirt back into the hole and tamp it in with a length of 2x2 or 2x4 to pack the soil in place around the post.
In my farming days past we built lots of fences this way. It does not work well initially if the soil is too wet or too fine grained sand.

has anyone tried wambam no dig fence


Logging to a file in Python

Question: I am trying to create a Python program that will just log user input.
Here is the code:
import logging

# logging setup
logger = logging.getLogger("testapp")
hdlr = logging.FileHandler("test.log")
formatter = logging.Formatter("%(asctime)s %(message)s")
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

def main():
    userinput = input("> ")
    logger.debug(userinput)
    logger.info(userinput)
    logger.warning(userinput)
    logger.error(userinput)
    logger.critical(userinput)
    a = input("> ")  # wait for a newline before before closing

main()

When I run the code, the warning, error, and critical message get printed, like they should, but a file is not created and nothing is actually logged.
Edit: This error message shows up:
--- Logging error ---
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 1025, in emit
    msg = self.format(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 869, in format
    return fmt.format(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 611, in format
    s = self.formatMessage(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 580, in formatMessage
    return self._style.format(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 422, in format
    return self._fmt % record.__dict__
KeyError: 'level'
Call stack:
  File "C:/Users/matth/PycharmProjects/arb/main.py", line 32, in <module>
    logger.debug("Starting...")
Message: 'Starting...'
Arguments: ()

Answer: You are using a different object in your main function and in the rest of your code. You need to use the same logger object used above the function. For example:
import logging
logger = logging.getLogger('app')
hdlr = logging.FileHandler('app.log')
formatter = logging.Formatter("%(asctime)s %
(message)s")
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.WARNING)
logger.error('Error logged')

Comment: To be clear, the `logging` module defines a root logger `logging.root`, and `logging.info` (for example) is basically a wrapper around `logging.root.info`. (The function also calls `basicConfig`, which adds a handler to `logging.root` if it doesn't already have one.)
Answer: You need to add:
import logging

logging.basicConfig(filename='example.log',level=logging.DEBUG)

The file 'example.log' will be created.

Logging to a file in Python


How to play with friends that only have the original Diablo 3?

Question: I have Diablo III: Reaper of Souls. My friends only have vanilla Diablo III. How can I play with them (on PS3)?
Comment: Not sure how it works on consoles, but on PC the person not having the expansion needs to open the game and then the person with the expansion can join in. They stop leveling at 60 though, while you continue your path to 70.
Answer: Short answer is you cannot simply because of different versions.  Source
Scroll down to bottom of the replies, blizzard employee explains.


New variable based on multiple ifelse conditions R

Question: I have a dataframe, users_full, in which I would like to create a new variable, party_followers, that has the following categories: AFD, SPD, CDU, FDP, Linke, Multiple, or Other.
I would like to create the categories for the new variable by matching users_full$user_id to the user_id variable of the respective dataframe of followers, e.g., afd_followers, spd_followers, etc.
The problem is that users_full$user_id can be a follower of multiple parties, and I am not sure how to account for this using an ifelse statement.
I tried the following, but it's not working.
mutate(users_full, party_followers = ifelse(user_id == afd_followers$user_id & user_id != cdu_followers$user_id & user_id != spd_followers$user_id & user_id != linke_followers$user_id & user_id != fdp_followers$user_id, "AfD",
                                user_id == cdu_followers$user_id & user_id != afd_followers$user_id & user_id != spd_followers$user_id & user_id != linke_followers$user_id & user_id != fdp_followers$user_id, "CDU",
                                user_id == spd_followers$user_id & user_id != cdu_followers$user_id & user_id != afd_followers$user_id & user_id != linke_followers$user_id & user_id != fdp_followers$user_id, "SPD",
                                user_id == linke_followers$user_id & user_id != cdu_followers$user_id & user_id != afd_followers$user_id & user_id != spd_followers$user_id & user_id != fdp_followers$user_id, "Linke",
                                user_id == fdp_followers$user_id & user_id != cdu_followers$user_id & user_id != afd_followers$user_id & user_id != spd_followers$user_id & user_id != linke_followers$user_id, "FDP",
                                user_id == afd_followers$user_id & cdu_followers$user_id & spd_followers$user_id & linke_followers$user_id & fdp_followers$user_id, "Multiple", "Other"))

Below, I reconstructed samples of the dataframes I am using.
users_full <- data.frame(
user_id = c("3854371132", "883470465498587138", "145216962", "2223089418",
"2861583057", "271413649"))

spd_followers <- data.frame(
user_id = c("145216962", "3864655101", "757305123165069312", "4854498122",
"1201495387", "565422099"))

afd_followers <- data.frame(
user_id = c("3854371132", "883470465498587138", "845969869778685952", "3864655101",
"757305123165069312", "793677341042044928"))

cdu_followers <- data.frame(
user_id = c("3854371132", "145216962", "3864655101", "757305123165069312",
"3207639056", "4854498122"))

linke_followers <- data.frame(
user_id = c("47289872", "1044855103", "565082298",
"956148596042330112", "2490464967", "956147739951329280"))

I would like to end up with the following output:
user_id party_followers
883470465498587000  AfD
3854371132  Multiple
1044855103  Linke
757305123165069000  Multiple
3207639056  SPD
947682953   Other

Comment: Your code is a little confusing. Can you please include your expected output?
Comment: I updated with an example of expected output.
Comment: Your use of `==` does row-wise comparisons, where order matters. I think you mean to be using `%in%`, where order wouldn't matter.
Answer: To be scalable without copy/pasting in case you have additional follower data frames, I would put all the followers in a list, collapse them to a single data frame, and use a merge.
Using data.table:
followers = list(spd = spd_followers, afd = afd_followers, cdu = cdu_followers, linke = linke_followers)
foll = data.table::rbindlist(followers, idcol = "party_followers")

setkey(foll, "user_id")
foll[, user_id := as.character(user_id)]

setDT(users_full, key = "user_id")
users_full[, user_id := as.character(user_id)]

foll[, n := .N, by = user_id]
foll[n > 1, party_followers := "multiple"]
foll = unique(foll)
merge(users_full, foll, all = TRUE)
 #               user_id party_followers  n
 # 1:         1044855103           linke  1
 # 2:         1201495387             spd  1
 # 3:          145216962        multiple  2
 # 4:         2223089418              NA NA
 # 5:         2490464967           linke  1
 # 6:          271413649              NA NA
 # 7:         2861583057              NA NA
 # 8:         3207639056             cdu  1
 ...

I'm not sure what merge behavior you want. Use all = TRUE to include all users in any of the data frames. Use all.x = TRUE to restrict to only the users in users_full, or all = FALSE to do an inner join, only the users that are both in users_full and in at least one of the follower data frames. I left in the n column showing how many networks each user is in - you can remove it if you want.
Comment: @qdread It's a long format, so the number of rows in each `follower` data frame is irrelevant. If there are extraneous columns, they can be easily omitted (or included with the `fill = TRUE` arg in `rbindlist`).
Comment: This is good but I was not sure if the followers list would be collapsible into a data frame, since although each element of the list has the same length in the example, I did not see why that would have to always be the case.
Answer: Here is a functional approach using only base R and which can be easily expanded by adding to the list of followers/vector of party names. In the past I'd have used sapply() but it is advised to use vapply() in functions because the format of its output is more predictable.
# Define function to get party name for each user ID
# by checking membership in each party.
get_party <- function(user_id,
                      id_list = followers_by_party,
                      id_labels = party_names) {
  in_party <- vapply(id_list, function(x) user_id %in% x$user_id, logical(1))
  if (sum(in_party) == 0) return('Other')
  if (sum(in_party) > 1) return('Multiple')
  return(id_labels[in_party])
}

# create list of user IDs by party and vector of name labels.
followers_by_party <- list(spd_followers, afd_followers, cdu_followers, linke_followers)
party_names <- c('SPD','AfD','CDU','Linke')

# apply this function to each of the user IDs
users_full$party_followers <- vapply(users_full$user_id, get_party, character(1))

Comment: Clever solution, though it's too bad it can't be vectorized over `user_id`.
Comment: Yes @Gregor I tried to figure out how to do that but failed :)
Answer: Not using ifelse, just vector comparison from base R. The multiple gets checked last, so it overwrites the places that would have other party names.
spd <- users_full$user_id %in% spd_followers$user_id
afd <- users_full$user_id %in% afd_followers$user_id
cdu <- users_full$user_id %in% cdu_followers$user_id
linke <- users_full$user_id %in% linke_followers$user_id
multiple <- (afd + cdu + spd + linke) > 1
other <- (afd + cdu + spd + linke) == 0

party_followers <- rep(NA, length(spd))
party_followers[spd] <- "SPD"; party_followers[afd] <- "AFD"
party_followers[cdu] <- "CDU"; party_followers[linke] <- "Linke"
party_followers[multiple] <- "Multiple"; party_followers[other] <- "Other"

users_full$party_followers <- party_followers


Why is the converted video file (lower resolution) using CV2 larger than the original file (higher resolution)

Question: i tried to change the resolution of a video file from 854x480 to a lower resolution of 640x480 using cv2 with the motive of reducing size,but while the original file is 3.2MB, the converted file is 8.3MB. I have also maintained the same video format. I'm new to video processing. Why is this happning and how can i modify the following code to get better results?
Thank you in advance!
here is the code i used:
<code>    import cv2
    import numpy as np

    cap = cv2.VideoCapture(r'C:\Users\CSC\Desktop\SmartDesert\1.mp4')

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(r'C:\Users\CSC\Desktop\SmartDesert\1_Output.mp4', fourcc, 25, (640, 480))

    while True:
        ret, frame = cap.read()
        if ret == True:
            b = cv2.resize(frame, (640, 480), fx=0, fy=0, interpolation=cv2.INTER_CUBIC)
            out.write(b)
        else:
            break

    cap.release()
    out.release()
    cv2.destroyAllWindows()
</code>
Comment: The duration time is same for both?
Answer: According to Wikipedia, mp4 is just a digital multimedia container format. It means mp4 provides a method of bundling an audio stream and video stream under one roof, i.e. an .mp4 file. During the bundling process, audio and video undergo compression codecs that ultimately gets converted to an output file.
An .mp4 container supports various video codecs. The one you used to write the video is mp4v. mp4v are raw mpeg-4 video streams, thus this might increase the size of video albeit resizing.
Trying another codec might help. Read this for the various codecs that can be used with .mp4
Cheers!


Angular: Lazy load a child module and inject its main component in the View of the Parent home component

Question: I have a parent module where i'm lazy loading a child module
As you may see , i don't import my child module directly , but i'm loading it lazily under routing file :
Parent Module :
@NgModule({
  imports: [
    CommonModule,
    ParentRoutingModule,
  ],
  exports: [
    ParentRoutingModule
  ],

  declarations: [ParentComponent]
})
export class ParentModule { }

Parent Routing Module :
const parentRoutes: Routes = [
  {path: '', component: ParentHomeComponent},
  {
    path: '',
    loadChildren: () => ChildModule,
    canLoad: [ChildModuleGuard]
  },
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(parentRoutes)
  ],
  declarations: [],
  exports: [
    RouterModule
  ]
})
export class ParentRoutingModule { }

In my main ParentModule component ; the ParentHomeComponent i want to inject the view of my ChildHomeCOmponent , like this :

  Parent-home works!

<app-Child-home></app-Child-home>

but this throws an error telling that the ChildHomeComponent isn't
  part of the ParentModule (as i'm not importing it directly) ;

How to deal with that ??
I want that if the module is loaded , my child home component gets displayed under the parent home component
Suggestions ??
Comment: i don't think that it is possible as the lazy loaded module will be loaded when one of its routes is called and never before, if you need this component in the main module, you have to import it or add it to a shared module
Comment: did u solved this? I have a similiar problem
Answer: This is not how lazy loading works in Angular.
Non-lazy loaded modules cannot access components from lazy loaded modules.


Linux Buffer Overflow Return-to-libc

Question: This question is a follow up with a previous question Previous Question
The previous question was solved by changing the permissions of the executable with execstack. My new problem revolves around another implementation to bypass stack execution protection. This uses return-to-libc and involves executing /bin/sh against the address of system().
I am currently using the following code:
#include <stdio.h>

void func(char *buff){
    char buffer[5];
    strcpy(buffer, buff);
    printf("%s\n", buffer);
}

int main(int argc, char *argv[]){
    func(argv[1]);
    printf("I'm done!\n");
    return 0;
}

My problem occures when I need to overflow the return address of func() to the address 0x00167100. When I perform the buffer overflow the argument I use is $(echo -e "\x00\x71\x16\x00"). The problem however is the least significant \x00 just before \x71 gets removed from my argument. In fact I can use \x00\x00\x00\x00\x00...\x71\x16\x00 and the argument passed in will still be \x71\x16\x00. The end result is the overriden address before some like 0x08001671 when it should really be 0x00167100.
Comment: @OliCharlesworth Why am I loosing those particular bytes.
Answer: strcpy() stops copying at the first null byte.  This means that you must use an address where at least the last three bytes are non-null.
Perhaps you can jump over the first instruction of the target function.
Comment: That was the problem however I have encountered a new problem. There is still the tail `\x00` byte and I have extra code after that byte. Any suggestions on getting around the `stycpy()` null byte problem.
Comment: @Blackninja543: The way to get around it is to ensure that your payload doesn't have any nulls other than as the last byte.

Linux Buffer Overflow Return-to-libc


iSCSI auto startup at boot 14.04

Question: I'm running Trusty Tahr (14.04) server. I've attached an iscsi disk and mounted it, mkfs, etc. works great, if I do it manually.
I'd much prefer to have my box mount the disk at boot so I've modified /etc/iscsi/iscsid.conf by removing the comment hash
node.startup = automatic and commenting out node.startup = manual (note: this isn't the default, but i've tried it both ways and i'm sticking with the automatic as that makes sense)
node.startup = automatic#
# node.startup = manual

fstab looks good. i've git my block id set, _netdev is set, and as I stated earlier, manually, everything works. if I mount the disk, the fstab config leads the mount correctly.
in general use, things look good. (in fact, it's a time machine backup).
My only issue is, why isn't this working at boot? Boot.log shows this info:
* Starting iSCSI initiatior service iscsid                               [ OK ]
iscsiadm: No records found
* Setting up iSCSI targets                                                * Stop
Clearly, an error is evident, but where? Aside from having to issue:
sudo iscsiadm -m node --login
I don't have to intervene.
Just .... need ... that ... last ... piece.
thanks
Answer: It sounds like you don't have any nodes configured in /etc/iscsi/nodes. In fact the nodes directory will be empty if you haven't asked for a list of targets from the iscsi server. So, if that's the case, you'll need to do a target discovery. Try:
iscsiadm -m discovery -t st -p IP-Address-Of-Target
Once this is done, there will be an iqn... directory with a list of possible portals under the nodes dir:
/etc/iscsi/nodes/iqnname/192.168.0.1:servername.iscsiTargetName/default

Edit the file 'default' so node.startup = automatic on any target you want to automatically connect to.
Oh also, check /var/log/syslog to see if iscsi is starting before the network interfaces start.
Comment: as stated in my initial post, it worked except the reboot, hence the targets are listed in the nodes directory. the syslog shows the network being active before the iscsi daemon is initialized. HOWEVER, my mistake was in not realizing that I had to modify the targets default settings as well as the iscsid.conf file. Once I added your suggest of modifying the target's node default file, this now works at boot. Many thanks.

iSCSI auto startup at boot 14.04


Dropping duplicate rows in a Pandas DataFrame based on multiple column values

Question: In a dataframe I need to drop/filter out duplicate rows based the combined columns A and B. In the example DataFrame
    A   B   C   D
0   1   1   3   9
1   1   2   4   8
2   1   3   5   7
3   1   3   4   6
4   1   4   5   5
5   1   4   6   4

rows 2 and 3, and 5 and 6 are duplicates and one of them should be dropped, keeping the row with the lowest value of
2 * C + 3 * D

To do this, I created a new temporary score column, S
df['S'] = 2 * df['C'] + 3 * df['D']

and finally to return the index of the minimum value for S
df.loc[df.groupby(['A', 'B'])['S'].idxmin()]
del ['S']

The result is
    A   B   C   D
0   1   1   3   9
1   1   2   4   8
3   1   3   4   6
5   1   4   6   4

However, is there a more efficient way of doing this, without having to add (and later drop) a new column?
Answer: df.drop_duplicates(subset=['A','B'],inplace=True)
by default, drop_duplicates drops rows (axis=0).
Comment: That will always keep the first row, right? The one to drop depends on columns C and D.
Answer: Efficient solution for larger dataframes
ix = np.argsort(2 * df['C'] + 3 * df['D'])
result = df.iloc[ix].drop_duplicates(['A', 'B'])

timeit analysis
Setup:
60000 rows with 10000 different groups

Results
%%timeit my solution
# 6.75 ms ± 309 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit OP solution
# 595 ms ± 50.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Answer: Here is a way by using sort_values() and duplicated()
df.loc[~df.sort_values('A',key = lambda x: df['C'].mul(2).add(df['D'].mul(3))).duplicated(subset = ['A','B'])]

Output:
   A  B  C  D
0  1  1  3  9
1  1  2  4  8
3  1  3  4  6
5  1  4  6  4


Get the selected text's range with respective to the main div(containing all the text)

Question: My requirement is to get the start and end character index of the text selected by the user with respect to the main div, lets say "content" div. See sample code below.
But when I select the "Rich" word in the web view. Its start and end character index comes respective to the where the "span" tag i.e. 1 and 5, respectively. Whereas it should be 12 and 16 w.r.t "content" div.

          This is out Rich Text Editing View

JavaScript function m using at the moment is
function getHighlightedString()
{
    var text = document.getSelection();
    startIndex = text.anchorOffset;
    endIndex = text.focusOffset;
    selectedText = text.anchorNode.textContent.substr(startIndex, endIndex - text.anchorOffset);
}

Please help me out.
Answer: Here's an answer adapted from this one. The same caveats from that answer apply.
Demo: http://jsfiddle.net/62Bcf/1/
Code:
function getSelectionCharacterOffsetsWithin(element) {
    var startOffset = 0, endOffset = 0;
    if (typeof window.getSelection != "undefined") {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.startContainer, range.startOffset);
        startOffset = preCaretRange.toString().length;
        endOffset = startOffset + range.toString().length;
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        var preCaretTextRange = document.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToStart", textRange);
        startOffset = preCaretTextRange.text.length;
        endOffset = startOffset + textRange.text.length;
    }
    return { start: startOffset, end: endOffset };
}

Comment: @harshitgupta: The reason for that is that all white space in all text nodes is counting towards the total offset. If you want character offsets that ignore unrendered white space, you'll need a more complicated approach, such as my own [Rangy TextRange module](http://code.google.com/p/rangy/wiki/TextRangeModule). A simpler workaround would be to remove the whitespace preceding the start of the text inside your editable element. Also, there was an error in my code which I've just updated.
Comment: @TimDown I have read your 100 answers in 3 days and dude you are awesome. I will work free for you just let me know :P
Comment: thanks for the quick response, @tim. I already tried your answer before. But it does not give the right answer. for the above code, for the "out" respective offsets are 11 and 14 and for "Rich" its is 16 and 20. which is not correct.


Set no. of copies in a System.Windows.Controls.PrintDialog

Question: For what I searched so far, I could not find a way to preset the number of copies in a System.Windows.Controls.PrintDialog, which is the one used in WPF. I cannot fallback or use another one because I need the PrintVisual method that only this class offers (afaik)
Unless there is another way, I'm thinking of doing a for loop and call the dialog.PrintVisual() method for the number of desired copies.I have not tested yet, but I'm quite sure it should work. My question: Is this the correct way of doing it?
Answer: You're looking for dialog.PrintTicket.CopyCount.
Docs.
Comment: Need to add a reference, in the project, to the ReachFramework assembly in order for the Intellisense to recognize .CopyCount


What's the difference --- Point estimate with 95% margin of error and 95% confidence interval

Question: As I understand it, a point estimate with 95% margin of error gives you an interval centered at the point estimator with half length equal to 1.96*the standard error. And if we construct a 95% confidence interval using the same estimator, we will end up with the same interval.
But the book totally lost me when it says:

You may have noticed that the point estimator with its 95% margin of error looks very similar to a 95% confidence interval for the same parameter. This close relationship exists for most of the parameters estimates in this book, but it is not true in general. Sometimes the best point estimator for a parameter does not fall in the middle of the best confidence interval; the best confidence interval may not even be a function of the best point estimator.

Any example illustrating this point?
Answer: The terminology '95% margin of error' should be considered informal.
More precisely, in a symmertical 95% confidence interval (CI) centered on
the point estimate one can call the half-length of a CI the 'margin of
error' and modifier '95%' suggests it's for a 95% CI.
The italicized sentence in your quote has to do with CIs that are
not symmetrical. One example is the CI for the unknown population
standard deviation $\sigma$ of a normal sample.
Theory for an asymmetrical CI for $\sigma.$  The background for finding a 95% CI for $\sigma$ follows. You can read it or skip to the interval itself below.
The sample variance $S^2$ is a point estimate
of $\sigma^2$ and $$\frac{(n-1)S^2}{\sigma^2} \sim \mathsf{Chisq}(df = n-1).$$
This means that one can use software or printed tables of the
chi-squared distribution to find $U$ that cuts off the top 2.5% of the
distribution and $L$ that cuts off the bottom 2.5%.  Thus
$$P\left( L \le \frac{(n-1)S^2}{\sigma^2} \le U \right) = 0.95.$$
After some manipulation of inequalities, we get
$$P\left( \frac{(n-1)S^2}{U} \le \sigma^2 \le  \frac{(n-1)S^2}{L} \right) = 0.95,$$
so that a 95% CI for $\sigma^2$ is of the form
$\left( \frac{(n-1)S^2}{U},\, \frac{(n-1)S^2}{L} \right)$
and $\left(\sqrt{ \frac{(n-1)S^2}{U}},\, \sqrt{\frac{(n-1)S^2}{L}} \right)$
is a 95% CI for $\sigma.$

An asymmetrical CI for $\sigma.$ As a particular example, suppose $n=20$ and $S = 14.9.$ Then the relevant cutoff values
  from chi-squared tables are $L = 8.91$ and $U = 32.85.$ Notice that the chi-squared distribution is not symmetrical and takes only positive values, so
  these values are not the positive and negative of the same value, as with
  $\pm 1.96$ from a normal distribution. [The density function of
  $\mathsf{Chisq(19)},$ along with the cutoff values $L$ and $U,$ is shown below.]

Then a 95% CI for $\sigma$ is $(11.3, 21.8)$. The point estimate of $\sigma$
  is $S = 14.9.$ Notice that 14.9 is within the CI, but it is not at the
  center of the CI (which is about 16.5). So there is no 'margin of error' $M$ of the form
  $14.9 \pm M.$

Computations for this CI from R statistical software are shown below:
qchisq(c(.025,.975), 19)
##  8.906516 32.852327
sqrt(19*14.9^2/qchisq(c(.975,.025),19))
## 11.33131 21.76252

Addendum, prompted by comment. So far, I have been talking about 'probability-symmetric' CIs, of level $1-\alpha,$ in which $\alpha/2$ is cut from each tail of the distribution. The situation can be a little different, if
you allow unequal tail probabilities:
(1) 95% CI for normal $\mu:$ If $\sigma$ is known the usual 95% CI is of the form
$\bar X \pm 1.96 \sigma/\sqrt{n},$ where $\sigma/\sqrt{n}$ is the 'standard error of the mean'. However, any cutoffs $L$ and $U$ with $P(L \le \frac{\bar X - \mu}{\sigma/\sqrt{n}} \le U) = 0.95$ can be used as the basis for a 95% CI: One choice is $L = -1.88$ and $U = 2.05,$ giving rise to the 95% CI
$\left(\bar X - U\frac{\sigma}{\sqrt{n}},\, \bar X - L\frac{\sigma}{\sqrt{n}}\right) = \left(\bar X - 2.04\frac{\sigma}{\sqrt{n}},\,
\bar X + 1.88\frac{\sigma}{\sqrt{n}} \right).$ This is seldom done because
it is a little messier to compute than the standard interval and also
this CI is a little longer than the usual one with $\pm 1.96.$. But it is possible and that's one reason
careful authors say a 95% CI, instead of the 95% CI for $\mu.$
qnorm(c(.03, .98))  # standard normal
## -1.880794  2.053749

(2) 95% CI for normal $\sigma.$ By trial and error, one could find
different tail probabilities to get $L$ and $U$ so that
$P\left( L \le \frac{(n-1)S^2}{\sigma^2} \le U \right) = 0.95.$
and  $|S-\sqrt{(n-1)S^2/U}| =|S-\sqrt{(n-1)S^2/L}|,$ but that would
require unequal tail probabilities. That's not usually done either.
[What is sometimes done is to find by trial and error tail probabilities
adding to 5% that make the shortest CI for $\sigma;$ the probability-symmetric
interval is seldom the very shortest CI possible.]
I'm not criticizing the italicized statement from your book. I'd classify
it as incomplete rather than incorrect. But almost all such statements are
incomplete to some degree. In formulating such a statement, an
author has take into account the mathematical level of expected students,
whether the textbook is applied or theoretical, and whether the statement
is near the beginning, middle, or end of the book. I brought up CIs
that are not probability-symmetric only because you asked a (good) question
with a slightly messy answer.
Comment: okay. That makes sense. Basically when the sample distribution is not symmetric, the confidence interval will not be symmetric.
Comment: Pretty much, but see Addendum.
Comment: Thanks. I actually winded up thinking about what appeared in your addendum myself, which solved another thing that I didn't quite understand in the textbook---"the best CI".


Messed up configuration by uninstalling PhpMyAdmin

Question: I uninstalled PhpMyAdmin by using sudo apt-get purge phpmyadmin.
When phpmyadmin was deleted, the webserver couldn't start.
I get the following error:
    Started apache2
    apache2: Syntax error on line 219 of /etc/apache2/apache2.conf: Could not open
configuration file /etc/apache2/sites-enabled/phpmyadmin.conf: No such file or directory

I don't know how to solve this. I'm afraid phpmyadmin has messed up some things and tainted several configuration files.
I tried to edit the content of the apache2.conf but I dont find anything that has to do with phpmyadmin.
Comment: What is the line 219 referenced in the error message?
Comment: That file hasn't even got 219 lines. But I really get the feeling it has something to do with symbolic links. It's looking for a file that shows up in the terminal when I list files. But when I want to load that file (using PHP to test) it says it doesn't exist.
Comment: the file `/etc/apache2/apache2.conf` should be have line 219. Please add that line to clarify your question.
Answer: I have read your post again. Just remove the symbolic link: sudo rm /etc/apache2/sites-enabled/phpmyadmin.conf.

Edit: /etc/apache2/apache2.conf doesn't have line 219 (for this case) because the complete file which the Apache2 server uses is consisted of the main content of the file and the content of all .conf files, involved with directives like: IncludeOptional mods-enabled/*.conf.

Check for additional phpmyadmin.conf file in /etc/apache2/conf-available/.
If it is there, I think you must do:
sudo a2disconf phpmyadmin
sudo rm /etc/apache2/conf-available/phpmyadmin.conf

or (which is the same):
sudo rm /etc/apache2/conf-enabled/phpmyadmin.conf
sudo rm /etc/apache2/conf-available/phpmyadmin.conf

Comment: The file you name isn't there. Could it be something with symbolic links?
Comment: Is there `/etc/apache2/conf-enabled/phpmyadmin.conf`?
Comment: No /etc/apache2/conf-enabled/phpmyadmin.conf isn't there.
Comment: I have read your post again. What is the result of `ls -la /etc/apache2/sites-enabled/`? It looks like there is a broken symbolic link.
Comment: `total 8
drwxr-xr-x  2 root root 4096 Oct  3 21:12 ./
drwxr-xr-x 18 root root 4096 Oct  3 21:12 ../
lrwxrwxrwx  1 root root   35 Jun  9 08:31 000-default.conf -> ../sites-available/000-default.conf
lrwxrwxrwx  1 root root   34 Jul  1 10:53 001-cloud9.conf -> ../sites-available/001-cloud9.conf
lrwxrwxrwx  1 root root   27 Oct  3 21:12 phpmyadmin.conf -> /etc/phpmyadmin/apache.conf` Readable: http://shorttext.com/826db5b0
Comment: Just remove the symbolic link: `sudo rm /etc/apache2/sites-enabled/phpmyadmin.conf`.
Comment: I will update my comment.