About sub control's response after SetCapture() in parent window

Question: I create a window in a view and create a scrollbar control in that window.
The window has edit mode. In edit mode, it will call SetCapture() and all the mouse event messages are sent to the window. So the other windows in that view will be disabled and have no chance for mouse operation in edit mode.
But it causes the following problem:
- In edit mode, mouse operation in Scrollbar makes no response. Because of SetCapture() to parent window.
So how can I SetCapture() a window but make the sub control respond to mouse operation?
Answer: SetCapture must not be called outside WM_*BUTTONDOWN. Read the documentation!
Comment: From my understanding this answer does not match the MSDN documentation as described here https://msdn.microsoft.com/en-us/library/windows/desktop/ms646262(v=vs.85).aspx.
It sounds like what is done in the example here (https://msdn.microsoft.com/en-us/library/windows/desktop/ms645602(v=vs.85).aspx#drawing_lines) but it is not a constraint of using the function.
Comment: The purpose of the `SetCapture` API is to capture mouse events from a certain window, no matter if the mouse is above the window or not. Constraint or not, if called in a non-`WM_*BUTTONDOWN` handler, the mouse messages will not be captured. MSDN loses. I win.
Comment: I believe that I have observed different behaviour.
Comment: I verified this in an `MFC` dialog project. If you can produce different behavior, it would be interesting to see how. Preferably on `Windows 7` or later.
Comment: In a custom window (non MFC on windows 8) SetCapture called outside of any event handler, all messages captured by the window (observed in Spy++ and in the code).  However this design was then abandoned for reasons similar to described in this question - messages were not forwarded to child windows if not handled by the capturing window.  I agree that the button down case is the common case and it may not be a good idea to try and use SetCapture to achieve other things.


How to intent multiple way point in Google Maps?

Question:
Here is the code that the button link to google maps based on the textview address.
button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view){
                    String address = textViewAddress.getText().toString();
                    String addressb = textViewAddressB.getText().toString();
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q="+address));
                    view.getContext().startActivity(intent);
                }
            });

How can I intent to multiple destinations/points in Google Maps? So If I created another textview address b, I want to show the location address a to address b to address c like the image above. Also possible intent to Waze as well?
Answer: You can refer to this API Documentation.. by using waypoints you may add multiple destinations
Uri gmmIntentUri = Uri.parse("https://www.google.com/maps/dir/?api=1&origin=18.519513,73.868315&destination=18.518496,73.879259&waypoints=18.520561,73.872435|18.519254,73.876614|18.52152,73.877327|18.52019,73.879935&travelmode=driving");
Intent intent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
intent.setPackage("com.google.android.apps.maps");
try {
    startActivity(intent);
} catch (ActivityNotFoundException ex) {
    try {
        Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
        startActivity(unrestrictedIntent);
    } catch (ActivityNotFoundException innerEx) {
        Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
    }
}

Update
You can also check this question


How does CID help in combat when called to be a follower / homie?

Question: The Upgrades - Gang Abilities menu description for the 'HOMIE - C.I.D.' gang ability states that:

C.I.D. can be called into the simulation using your HUB "PHONE" menu.
  The A.I. will help the saints in combat.

However, it seems that aside from having hilarious dialogue with some of the other homies and following me around, it seems that C.I.D. doesn't do anything to help in combat.
Screenshot of C.I.D. just looking at me while I'm being shot at by aliens:

I've searched and found the following posts asking the same thing but they currently have no replies:

Does the C.I.D. help in battle? | saintsrow.com
What does CID do in battle? | steamcommunity.com

What helpful things does CID do when called to be a follower / homie?
Comment: Making you laugh is debatably helpful.
Answer: According to the CID entry on the Saints Row 4 wiki,

As a Homie, CID does nothing to help The Protagonist in any way, he only speaks and has homie conversations, he does not fight in battle but follows the boss around. He is seen using some sort of weapon in cutscenes only.

So CID does not help in combat, and will only follow you around and have hilarious dialogue with your other homies.


JS keeps overwriting my previous "code"

Question: I'm trying to create a browser based OS. To figure a few things out, I wrote the following code. When I run it, the code at the beginning keeps getting left out.

  <TITLE>
   OS ... Loading
  </TITLE>
  <LINK REL="stylesheet" HREF="loader.css" />

Comment: Don't use `document.write`.
Comment: `document.write` is difficult to use at best. It wipes the body of the html and replaces it with the string in the write. So in your case, since you have your script in the body tag, the script will get replaced as soon as the script starts to run.
Comment: The reason people say not to use document.write is due to security, similar to how people say don't use eval. But also it's pretty much "considered" as depreciated.
Answer: The MDN documentation for Document.write() is pretty clear about this:

Note: as document.write writes to the document stream, calling
  document.write on a closed (loaded) document automatically calls
  document.open which will clear the document.

https://developer.mozilla.org/en-US/docs/Web/API/Document/open#Notes
Use DOM manipulation instead
e.g. at it's most basic:

var h = document.createElement("h1");
var t = document.createTextNode("Unicorns!");
h.appendChild(t);
document.body.appendChild(h);
Comment: I know that my problem is in the document.write() what I can't figure out is what to replace it with.
Answer: To expand on @pero's answer

The Element.innerHTML property sets or gets the HTML syntax describing the element's descendants.
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Use Element.innerHTML += to append preformatted html to the element.
Use Element.innerHTML = to replace the preformatted html of the element.
document.body.innerHTML += 'some text'

The Node.textContent property represents the text content of a node and its descendants.
  ...
Differences from innerHTML
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

Use Element.textContent += to append text to the element.
Use Element.textContent = to replace the text of the element.
document.body.textContent += 'some text'

More specific
If you want to append/replace the text/html for a certain element you need to select that element, then use the above methods on that element
For example,
Let's say you have a div,

that you would like to append some text to. Here we select the first div with the class screen (although you should use a unique id instead of a class) and append some text to it.
document.querySelector('.screen').textContent += 'some text'

If you're going to use a unique id you would select it like so
document.getElementById('screen');

Now if you're going to be doing this a whole bunch of times, you should cache the selector so you're not querying the dom every time.
var screen = document.querySelector('.screen');
screen.textContent += 'some ';
screen.textContent += 'text ';
screen.textContent += 'some more text';

A note about innerHTML/textContent vs DOM Manipulation
The above methods are great for quickly appending text or html to an element, no doubt about it, and it performs more quickly than DOM Manipulation.

The most obvious conclusion of these tests is that innerHTML is faster than "real" W3C DOM methods in all browsers. The W3C DOM table methods are slow to very slow, especially in Explorer.
More than once people said that creating elements only once and then cloning them when necessary leads to a dramatic performance improvement. These tests don't show anything of that kind. Although in most browsers cloning is minimally faster than creating, the difference between the two methods is small.
http://www.quirksmode.org/dom/innerhtml.html

But DOM Manipulation has a lot of wonderful features that cannot be easily accomplished by the methods detailed in my answer. For complex operations I would definitely recommend DOM Manipulation.
Comment: one last question what about its interaction with the setTimeout do i use () or is += still the right way to go
Comment: just one last part (I am new to JS and not sure where to look to find answers other than here) I want to place the js script in my `` but not sure how to mke sure that happens with the code you gave me?
Comment: yes that is exactly my intention and I'm not sure how to specify which div to attach it to

JS keeps overwriting my previous "code"


c++ win32 get system volume accelerator

Question: is it possible to detect which keys are used for a system volume accelerator in win32 using c++? For example: if the user presses fn + key up (and this is also the key combination to change the system volume), i would like to detect this event and response to it.
Comment: Related to https://stackoverflow.com/q/22975916/2877364
Answer: This is handled by the machine's BIOS.  It produces a keystroke, VK_VOLUME_DOWN or VK_VOLUME_UP virtual key.  DefWindowProc handling of that WM_KEYDOWN message produces WM_APPCOMMAND, APPCOMMAND_VOLUME_UP/DOWN.  DefWindowProc handling of that message adjusts the volume.
Comment: Actually, `DefWindowProc` handling of that message forwards `WM_APPCOMMAND` to Explorer, and Explorer adjusts the volume. If you want to override the volume buttons in your app, respond to the `WM_APPCOMMAND` message.
Comment: @Raymond - aren't you going too fast?  DefWindowProc handling of WM_APPCOMMAND on a toplevel window invokes the shell hook afaik.  If WM_KEYDOWN handling sends WM_APPCOMMAND straight to Explorer then there's no way to respond to it.
Comment: Yeah, the `WM_APPCOMMAND` goes to Explorer via a shell hook. The point was that it's Explorer that changes the volume, not `DefWindowProc`. The distinction is not significant to this question, but it affects similar questions.
Comment: but the messages WM_APPCOMMAND and WM_KEYDOWN are sent only when the application has focus. How can i detect this keys even if the application doesn't have focus?
Answer: I don't think this is possible generally. The fn-keys are usually handled by the BIOS-SMM-ACPI whatever, and that is not accesible to user programs.
Maybe, if it were translated to the standard multimedia volume-up key, you could get that, but I wouldn't bet on it.
Answer: see this post...
http://www.rohitab.com/discuss/topic/21252-change-volume/
Comment: The OP is asked how to detect keypresses that lead to system volume changes, not how to modify the system volume.

c++ win32 get system volume accelerator


numbers in a 5 digit number

Question: i have a very simple question
i need to know the probability of a 5 digit number to be with the digit 5 only one time
so first digit cant be 0 so i do:
$8\times9\times9\times9\times1$
$8\times9\times9\times1\times9$
$8\times9\times1\times9\times9$
$8\times1\times9\times9\times9$
that is:
$8\times9\times9\times9\times4$
but if the first number is five it's
$1\times9\times9\times9\times9$ and it does not come to:
$8\times9\times9\times9\times5$ because now you can have 0 in the remain digit..
how do i calculate it?
Answer: The total amount of $5$-digit numbers is $9\cdot10\cdot10\cdot10\cdot10=90000$.
The amount of those with $5$ only at index #$1$ is $1\cdot9\cdot9\cdot9\cdot9=6561$.
The amount of those with $5$ only at index #$2$ is $8\cdot1\cdot9\cdot9\cdot9=5832$.
The amount of those with $5$ only at index #$3$ is $8\cdot9\cdot1\cdot9\cdot9=5832$.
The amount of those with $5$ only at index #$4$ is $8\cdot9\cdot9\cdot1\cdot9=5832$.
The amount of those with $5$ only at index #$5$ is $8\cdot9\cdot9\cdot9\cdot1=5832$.
So the probability of a $5$-digit number with only one occurrence of the digit $5$ is:
$$\frac{6561+5832+5832+5832+5832}{90000}=0.3321$$
Answer: First, you are counting the number of five digit numbers that include exactly one five, not computing the probability.  For the probablility you need to divide by the number of five digit numbers, which is $9\cdot 10^4$  Your counts are correct, so the number we want is $8 \cdot 9 \cdot 9 \cdot 9 \cdot 4+1 \cdot 9 \cdot 9 \cdot 9 \cdot 9$  You could just type this into your calculator (you may need to use the memory to hold the first term) or you can write  $8 \cdot 9 \cdot 9 \cdot 9 \cdot 4+1 \cdot 9 \cdot 9 \cdot 9 \cdot 9=(8\cdot 4+1\cdot 9)9^3=41\cdot 729=29889$
Answer: One digit is 5, so there are 4 free ones left. The first digit has 8 possibilities (all digits except 5 and 0), the second, third and fourth all have 9 possibilities (all digits except 5). This makes for $8\times9\times9\times9=5832$ possibilities. However, the 5 could be in any position. There are 5 possible positions for the digit 5.
Four of these do not have the 5 as the first digit. One does, for a total of $4\times5832+9^4=29889$ possible numbers.
The total amount of possible 5 digit numbers without a leading zero is $9\times10^4$. The chance is therefore $\frac{29889}{9\times10^4}=0.3321$
Answer: If the first number is 5 then it's $1\times9\times9\times9\times9$.
If not then it's $8\times1\times9\times9\times9$ or $8\times9\times1\times9\times9$... which is $4\times8\times1\times9\times9\times9$.
So the number of cases is $4\times8\times1\times9\times9\times9+1\times9\times9\times9\times9=29889$
Answer: Since the first digit canot be a zero, the probability that the first digit is a 5 is given by:$$\frac{1}{9}$$And the probability that the remaining four digits of this number are not 5's is given by:$$\left(\frac{9}{10}\right)^4$$So the probability that the first digit is a 5 and the remaining digits are not 5's is given by:$$\frac{1}{9}\times\left(\frac{9}{10}\right)^4$$Next we consider the digit 5 appearing as the second digit of the number. The probability that the second digit is a 5 is given by:$$\frac{1}{10}$$The probability that the first digit of this number is not a 5 (remember it cannot be a zero either) is given by:$$\frac{8}{10}$$The probability that the remaining three digits of this number are not 5's is given by:$$\left(\frac{9}{10}\right)^3$$Therefore, the probability that the second digit of a 5 digit number is a 5 is given by:$$\frac{1}{10}\times\frac{8}{10}\times\left(\frac{9}{10}\right)^3$$Hopefully you can complete the caculation from here...
Answer: In combinatorics:
There are (9^^4 )× 1 = 6561
+
(9^^3) × (8/9) = 648
= 7209 ways to have  5 in on  and only one column
10^^4 × 9
= 90000 ways to order five significant digit numbers
.: there is  a probability  of 7209 / 90000
= .00801 probability of having a five in a 5 digit number
Comment: This is not correct.  First your equalities are not.  It is not true that $9^4=6561+(9^3 \times 8/9)$, nor that that sum equals $648$, nor that that equals $7209$.  Second, you don't explain where $9^3 \times (8/9)$ comes from
Comment: Ross Millikan well I was pretty close. .. :)  What do you think of my revision posted yesterday?
Answer: Mr Milican is in part correct. I will  do  some recalculation.
Firstly if 5 is in the first  column then  there is the instance of  1 possible  number with  the probability of being  5 at exactly  1.  Now we have four digits that must not be 5 in any digit. There are 9 possibilities of digits  not  being  5 in each of these digits.  Hence 9 ^^ 4  is indeed the  cimbinatoric  number of permutations of any non 5 digit combination that can be made in any instace.
= 6561 combinatiins
Secondly if the first digit is not a 0 or a 5 then there are 8 possible other digits that the first and highest  magnitude digit may  be.  In that case  there are  4 possibilities of a 5 being in one and only  one  digit of the 4 lowest  magnitudes.  And  there 3 digits where it must not  be  a 5. In each of these magnitudes there  are  9 possible digits such that in a combinatoric computation the total number  of combinations is( (9^^3) × 4  ) × 8 =
23328
The sum total of possibilities  is
23328 + 6561
= 29888
And since there are 9 × (10^^4)
= 90000 possible 5 digit  numbers
The probability  a 5 digit  number has 5 in one and only one digit is
29889 / 90000
= 0.3321
Fin
Comment: You have a typo in the sum total line, the last digit should be a 9.  It is fixed later.  I don't know why you say I am in part correct.  Please explain or delete that line.
Comment: Thank you you are correct sir.

numbers in a 5 digit number


How to tell if my system is "multiarch"?

Question: Per the LTS Enablement Stack wiki, "to install the newer HWE kernel derived from 15.10 (Wily)" there is a different set of packages to install depending on whether a system is multiarch or not.
How do I tell if my system is multiarch or not?
The wiki is "hinty", saying "you may find you need" to do this.
Comment: Usually means you run a 64bit OS, but also use packages that are 32bit. Run `uname -m` to check what kind of OS you have.  `x86_64` - 64bit, and `i686` - 32bit. Here's more info on multiarch https://wiki.ubuntu.com/MultiarchSpec.
Comment: There will be nothing bad if you use the command for multiarch.
Comment: I'm not willing to break my system or install un-needed packages by taking these "chances", hence my question.
Comment: Thanks! I'm confident that I have 64 bit Trusty installed.  It's the part about using 32 bit packages that I need to check on, but don't know how to.
Comment: If you don't know whether or not you need 32bit packages, chances you great that you don't.
Answer: dpkg supports installing packages for other non-native architectures using a system called multiarch. It was introduced in Ubuntu 11.04, so any later release should have it.
You can use dpkg --print-foreign-architectures command to find the added foreign architectures on multiarch e.g.:
% dpkg --print-foreign-architectures
i386

To find the native architecture, use dpkg --print-architecture e.g.:
% dpkg --print-architecture
amd64

Alternately, you can also read the file /var/lib/dpkg/arch to get a list of added architectures (first one is native, although you can remove it):
% cat /var/lib/dpkg/arch
amd64
i386

Comment: Thanks! Exactly what I needed, and shows that I do need the "multiarch" packages.  Much appreciated.
Comment: the file /var/lib/dpkg/arch may only exist is at least one foreign architecture is installed


Wix: Environment doesn't get removed from environment variable if INSTALLFOLDER is changed from default

Question: we have an installer that adds INSTALLFOLDER to the PSModulePath environment variable. We do this with Permanent="no" so it gets removed during uninstall. However, if the user chooses to install not into the default directory of the installer (which is "c:\Program Files (x86)\ourcompany\ourproduct"), removal of the path from the environment variable doesn't happen. What are we doing wrong?
This is the component's code:
<code><Component Id="cmpAddPathToEnvVarPsModulePath" Guid="{someguid}">
                <Environment Id="PSModulePath" Name="PSModulePath" Value="[INSTALLFOLDER]" Permanent="no" Part="last" Action="set" System="yes" />
                <RegistryKey Root='HKCU' Key='SOFTWARE\ourcompany' >
                    <RegistryKey Key='ourproduct' >
                        <RegistryValue Name='PSModulePathCreated'  Type='integer' Value='1'  KeyPath='yes'></RegistryValue>
                    </RegistryKey>
                </RegistryKey>
            </Component>
</code>
Any help appreciated,
--
Stefan
Answer: During a default installation and uninstallation the INSTALLFOLDER value is the same. During a custom installation the INSTALLFOLDER value is changed, but  during the uninstall INSTALLFOLDER reverts back to the default path. In order to clear the INSTALLFOLDER value from the PSModulePath environment variable you'll have to write the INSTALLFOLDER value into the registry and then read it in during uninstalls so that uninstalls know how to remove that custom path from PSModulePath.
Comment: That sounds reasonable. How would I go about changing the INSTALLFOLDER property during uninstall? Schedule a CA right at the start of the uninstall sequence to read the stored value from the registry and change it from there using MsiSetProperty? Would that work? Is there an easier way? Anyway, thanks for answering.
Comment: Yes, that would work. Or, you could do it entirely in wix following wix's "Remember Property" pattern - https://robmensching.com/blog/posts/2010/5/2/the-wix-toolsets-remember-property-pattern/
Comment: I tried with the remember property pattern and scheduled a CA of type 'immediate' after AppSearch that sets the value of 'INSTALLFOLDER' to the remembered value of the 'INSTALLFOLDER' property used during install. I conditioned it to REMOVE~="ALL". However, this works only if I uninstall using msiexec -x. If I use msiexe -i and select "uninstall" from the GUI, this doesn't work. To make this work I must condition for REMOVE~="ALL" OR REMOVE~="DefaultFeature" because in the latter case REMOVE is assigned the value of my one and only feature named "DefaultFeature".
Comment: Shouldn't REMOVE~="ALL" be the canonical condition for execution during uninstall only? I wonder what's wrong here with my installer.
Comment: Your findings are correct. Uninstalling from ARP vs uninstalling with UI results in two different REMOVE values ("ALL" vs "Feature1,Feature2,..."). So, either condition on REMOVE~="ALL" OR REMOVE~="DefaultFeature" -or- if there is a feature if your MSI that 'must' always be installed you could condition on &CoreFeature=2 so that only when that core feature is removed does your custom action execute.


How can I make a TNT arrow in Minecraft Bedrock?

Question: If I put this command in a command block:
execute at @e[type=arrow] ~ ~ ~ summon tnt ~ ~ ~

it says

"Syntax error: unexpected "~":at "pe=arrow >>~<< ~ ~ summo"

What's wrong?
Answer: I think you are mixing new Java syntax with old Bedrock one, try:
execute @e[type=arrow] ~ ~ ~ summon tnt ~ ~ ~

or
execute as @e[type=arrow] at @s summon tnt ~ ~ ~

Answer:
the 2 is there so the arrow doesn't shoot the tnt then disappear
execute as @e[type=arrow] at @e[type=arrow] run summon tnt ~ ~2 ~


Neither Windows 7 or Ubuntu will boot after installing 16.04. Any suggestions on how to fix my mistakes?

Question: I previously had 12.x LTS installed, and decided to upgrade. After uninstalling it, I made myself a LiveUSB to install with.
My plan was to install Ubuntu onto a large external hard drive, and run it from there.
However, when I tried to install, I kept receiving an alignment error. I used fdisk to create some properly aligned partitions, and Ubuntu then let me go through with the install.
When I restarted my PC, instead of getting the expected OS selection screen, I get grub's rescue console.
I'll admit I'm out of my depth. Right now, I'm just wondering what I can do to get things booting correctly. Any ideas what I did I wrong, or how to set things right?
EDIT: My Windows install was under legacy BIOS, and I accidently installed Ubuntu under UEFI. My guess is that's where I went wrong. Still open to advice on how to fix this.
Answer: I had a system with a mix of UEFI and MSR installs. Big mess.
You can have either UEFI or MBR (aka UEFI Legacy), never both.
It is possible to convert the drive to either using Windows Repair CD's 'diskpart' command. Use diskpart in the console and type help, its documented good enough to get you through. Thats the princpile use:
<code>diskpart
> list disk
> select disk 0
> ICanNotRememberCommand MBR
</code>
It erases your disk, though. You need to copy all partitions and you will need to run Windows Repair through all stages to get it back. When it does not detect your Windows installation, install Linux onto another partition and put grub into the MBR. After that windows repair showed me the partition and the automatic install ran 3 cycles and I got windows back to run.
Its a very bad situation. To avoid to be ever in such a situation again I made the rule:

all systems with system disk <2GB NEVER use UEFI, always use Uefi Legacy.
all system with system disk >2GB only use UEFI.

Hope it helps,
CatMan
PS: When you try to take images with Clonezilla, it will not work when it finds a mismatch between MBR and GPT. I guess you will get this. In that case Clonezilla suugests the use of a 'sgdrive' command. I had nothing valuable to loose, so I tried it and it worked find, but it could have deleted the data on the drive as well. I did not try other backup tools.
Comment: Thanks for helping to clear thing up. After giving my manufacturer's repair disk a try, and forcing Ubuntu to install in legacy, I was finally able to get to the OS selection screen. I'll just have to chalk this up to a learning experience.
Comment: Glad it got you a bit further.


What's wrong with my table saw?

Question: (I asked Should I sharpen or replace my table saw blade? and got a good answer.  (Paraphrased: sharpen $100 blades, replace $30 blades.)  But, as it turns out, I was suffering from superstitious behavior, attributing the problem to the last thing I did rather than finding the root cause.  A brand new blade bogs down ripping 1/2" poplar so the blade is not the problem.)
I have a Craftsman table saw (model 113.298031) which recently started bogging down and stalling while ripping soft woods (1x4 pine, 1/2x3 poplar).  I cleaned the blade to no effect and put in a brand new combination blade also to no effect.  I now wonder if the belt or motor are to blame.
The motor mount allows the motor to be pivoted to tighten the belt but is at the furthest point from the blade so there is no room to tighten it by adjusting the position.  The belt is a series of links that look like leather.  It seems I could take the belt off, remove a link, and put it back together as a quick and cheap way to prove if the belt is the problem.  If that works, does it mean the belt is so stretched out (and weakened) that it needs to be replaced or does that solve my problem?
Comment: There is a definite sound difference between the two. If the motor stalls the frequency gets a lot lower as it tries to regain speed. When the belt slips the sound is much higher pitched.
Comment: does the motor stall or does the belt slip?
Comment: Hard to tell while standing in front of the table.
Answer: If there is no more room for adjustment of the motor to tighten the belt then the belt is too long.  If you have a link belt remove a link. This can give the impression of the saw bogging down when actually the belt is just slipping.
Comment: One link out and it cuts like new.  The motor is still nearly at the farthest position from the blade so I may take another link out later.  Thanks.
Answer: Good idea to check the belt....best may be to buy a new one.
Also make sure that the fence is 100% parallel with the blade. If it is off it can cause the ripped piece to bind between the fence and the blade and cause the problem that you are seeing. If not parallel the fence and/or blade+motor will need adjustment.

What's wrong with my table saw?


Is there is difference in proving Arg(zw)=Arg(z)+Arg(w) and arg(zw)=arg(z)+arg(w)?

Question: I am trying to prove/disprove $\operatorname{Arg}(zw)=\operatorname{Arg}(z)+\operatorname{Arg}(w)$. Apparently $\operatorname{Arg}(zw)=\operatorname{Arg}(z)+\operatorname{Arg}(w)+2k\pi$ where $k=0,1,\text{ or }-1$, but I have no idea why. I keep on finding that answer online. I am very lost on how to prove this statement, any help would be great. Thank you.
Comment: Consider $z=w=e^{i\frac{3\pi}{4} $. Then the sum of arguments is too large to be the principal argument of a complex number. You get the other cases in a similar way.
Comment: The function Arg is not additive but it is additive modulo $2\pi$ and it is always ranged in $(-\pi,\pi]$. whereas  arg is a $2\pi-$ modulo of Arg and therefore it is addive
Answer: Let's say we have two complex numbers $\text{z}_1$ and $\text{z}_2$ we can write:

$$\text{z}_1=\left|\text{z}_1\right|\cdot\exp\left(\left(\arg\left(\text{z}_1\right)+2\pi\cdot\text{k}_1\right)\cdot i\right)\tag1$$

Where $0\le\arg\left(\text{z}_1\right)<2\pi$ and $\text{k}_1\in\mathbb{Z}$

$$\text{z}_2=\left|\text{z}_2\right|\cdot\exp\left(\left(\arg\left(\text{z}_2\right)+2\pi\cdot\text{k}_2\right)\cdot i\right)\tag1$$

Where $0\le\arg\left(\text{z}_2\right)<2\pi$ and $\text{k}_2\in\mathbb{Z}$
So, we get:
$$\text{z}_1\cdot\text{z}_2=\left|\text{z}_1\right|\cdot\exp\left(\left(\arg\left(\text{z}_1\right)+2\pi\cdot\text{k}_1\right)\cdot i\right)\cdot\left|\text{z}_2\right|\cdot\exp\left(\left(\arg\left(\text{z}_2\right)+2\pi\cdot\text{k}_2\right)\cdot i\right)=$$
$$\left|\text{z}_1\right|\cdot\left|\text{z}_2\right|\cdot\exp\left(\left(\arg\left(\text{z}_1\right)+2\pi\cdot\text{k}_1\right)\cdot i+\left(\arg\left(\text{z}_2\right)+2\pi\cdot\text{k}_2\right)\cdot i\right)=$$
$$\left|\text{z}_1\right|\cdot\left|\text{z}_2\right|\cdot\exp\left(2\pi\cdot\left(\arg\left(\text{z}_1\right)+\arg\left(\text{z}_2\right)+\text{k}_1+\text{k}_2\right)\cdot i\right)\tag3$$
Answer: It can be shown in many ways. The simplest is to consider the exponential form of complex numbers $$z=\rho e^{i\theta}$$
with $|z|=\rho$ and $Arg(z)=\theta$
Answer: Denote $z=r_1\cdot e^{i\theta_1}$, $z=r_2\cdot e^{i\theta_2}$.
Then $zw=r_1\cdot e^{i\theta_1}\cdot r_2\cdot e^{i\theta_2}=r_1r_2e^{i(\theta_2+\theta_2)}$, and since the argument of a complex number $re^{i\theta}$ is $\theta$, we receive that $Arg(z)+Arg(w)=\theta_1+\theta_2=Arg(zw)$ up to $\pm 2\pi$.
Answer: "but I have no idea why" ...  Because exponential is periodic with period $2 \pi i$ over the complex plane. This is a picture from a Mathcad worksheet, but try this with your calculator:


In jQuery, how can I monitor a dynamically populated element (AJAX), without basing it on an event?

Question: I have the following markup on page load:
<select name="sel_billing_address"></select>

After page load that select is then populated by some AJAX to be something along the lines of:
<select name="sel_billing_address">
  <option value="1">hi</option>
  <option value="2">there</option>
  <option value="3" selected="selected">sally</option>
</select>

I need to grab the selected option from this list.  Normally it's just a simple case of:
jQuery('select[name=sel_billing_address] option:selected');

but because it's loaded dynamically, I need to monitor it using .live() - or by some other means.  If I monitor it using live('change') then it works great - but I need the values when the select box might not have been changed.
.live('load') seems like the obvious choice, but that only works when loading the element - the select element itself is loaded on page load, at which point it's empty.  I have also tried doing .live('load') on the OPTION rather than the SELECT, but that doesn't seem to be available either.
It's also worth noting that I cannot change the markup, how the page loads elements, and I can't plug into the callback parameter of the script that originally changes the select - everything is external.
Any help is greatly appreciated.
Comment: can you not do it in the callback (success:) function from the ajax function?
Comment: Unfortunately not, no.  I forgot to mention that.  I don't have access to any of the code that is already on the page, including markup or any of the scripts already loaded.  This is a plug-in in every sense.
Answer: check out the livequery plugin. It has the ability to work the same way as the .live() method but unlike live, isn't limited to just being bound to events
Comment: @loxaxx, thank you! I have the same problem as the asker, and the `livequery` is so great.
Comment: The link is no longer valid, livequery the direct link to the github repo is here: https://github.com/brandonaaron/livequery
Answer: You could look into (Global) Ajax Events. This may give you a way to sneak into the ajax callback that you don't have direct access to.
// Use the Global Ajax Event "ajaxComplete"
$('select[name=sel_billing_address]').bind('ajaxComplete', function () {
    // Check to see if select has any option elements yet
    if ($(this).find('option').length > 0) {
        // Unbind the ajax event
        $(this).unbind('ajaxComplete');

        // Do your stuff
        // Here...
    }
});

If you check out the jquery page I linked to you can see that "ajaxComplete" occurs after any "complete".
EDIT: Yes... this is still using an event, but I think it will resolve your issue.


Cannot deserialize Json from CouchDB

Question: i´m struggling with deserializing the Json i get.
It  looks like this:
{
    "seq": "13-g1AAAACLeJz",
    "id": "c32b670-37899h8c545",
    "changes": [
        {
            "rev": "9-68joc97b73df883a"
        }
    ]
}
{
    "seq": "15-g1AAAACLeJzLYWB-w",
    "id": "f73huvh3-of38j8fh",
    "changes": [
        {
            "rev": "4-10516b0f3"
        }
    ],
    "deleted": true
}
{
    "seq": "16-g1AAAACL4eJzL",
    "id": "M.Mustermann",
    "changes": [
        {
            "rev": "388-e6d350281"
        }
    ],
    "deleted": true
}
{
    "seq": "17-g1AAAACLr43_Q",
    "id": "f8h83hf-34f8h",
    "changes": [
        {
            "rev": "4-773re8f44e"
        }
    ],
    "deleted": true
}
{
    "seq": "18-g1AAwe_g",
    "id": "ewf/34r",
    "changes": [
        {
            "rev": "9-wehch87ewc"
        }
    ],
    "deleted": true
}
{
    "last_seq": "21-g1AA8wd998rAQ",
    "pending": 0
}

My Models:
public class Root    {
        public List<Result> results { get; set; }
        public string last_seq { get; set; }
        public int pending { get; set; }
    }

    public class Result
    {
        public string seq { get; set; }
        public string id { get; set; }
        public List<Change> changes { get; set; }
        public bool? deleted { get; set; }
    }

    public class Change
    {
        public string rev { get; set; }
    }

I tried all the solutions i found but nothing works, i still get the following exception:
Newtonsoft.Json.JsonReaderException: Additional text encountered after finished reading JSON content: {. Path '', line 2, position 0.
at Newtonsoft.Json.JsonTextReader.Read()
What i tried:
dynamic array = JsonConvert.DeserializeObject<Root>(json);

Root jsonObject = JsonConvert.DeserializeObject<Root>(json);

var jsonObject = JsonConvert.DeserializeObject<List<Root>>(json);

Comment: That isn't valid JSON, it looks like a series of JSON documents stuck together.
Comment: I think it is gonna be hard to deserialize that json without changing it. You've got a list of results which is not formatted as an array into your json and isn't comma separated. And it is followed by another object which isn't named and is different from the previous nodes.
Answer: What you have is a series of JSON documents all stuck together. Also to make things even more awkward, the last one is different from the rest. So you need to parse them all manually and do some checking to see what kind of object you have. You can make use of the JsonReader.SupportMultipleContent property. For example, something like this:
//Somewhere to keep the parsed results
var results = new List<Result>();
Root root = null;

var serializer = new JsonSerializer();

using (var stringReader = new StringReader(Json))
using (var jsonReader = new JsonTextReader(stringReader))
{
    //Make sure the JsonReader knows we have multiple documents
    jsonReader.SupportMultipleContent = true;

    while (jsonReader.Read())
    {
        //Read in the next document
        var nextObject = JObject.ReadFrom(jsonReader);

        //Determine if we are on the last item or not
        if(nextObject["last_seq"] != null)
        {
            root = nextObject.ToObject<Root>();
        }
        else
        {
            results.Add(nextObject.ToObject<Result>());
        }
    }
}

//Store the results in the root object since this is how your classes have been structured
if(root != null)
{
    root.results = results;
}

Comment: Thanks a lot, this made my day. I now have data to work with.
Answer: If you can ask for a change of the json you receive, the Json bellow should work.
If you can't, you will have to parse it yourself I think.
"results" : [{
"seq": "13-g1AAAACLeJz",
"id": "c32b670-37899h8c545",
"changes": [
    {
        "rev": "9-68joc97b73df883a"
    }
]
},
{
    "seq": "15-g1AAAACLeJzLYWB-w",
    "id": "f73huvh3-of38j8fh",
    "changes": [
        {
            "rev": "4-10516b0f3"
        }
    ],
    "deleted": true
},
{
    "seq": "16-g1AAAACL4eJzL",
    "id": "M.Mustermann",
    "changes": [
        {
            "rev": "388-e6d350281"
        }
    ],
    "deleted": true
},
{
    "seq": "17-g1AAAACLr43_Q",
    "id": "f8h83hf-34f8h",
    "changes": [
        {
            "rev": "4-773re8f44e"
        }
    ],
    "deleted": true
},
{
    "seq": "18-g1AAwe_g",
    "id": "ewf/34r",
    "changes": [
        {
            "rev": "9-wehch87ewc"
        }
    ],
    "deleted": true
}],
"last": {
    "last_seq": "21-g1AA8wd998rAQ",
    "pending": 0
}

Cannot deserialize Json from CouchDB


How to escape from zombie grab?

Question: How to escape from zombie grab before a QTE prompt appears on-screen?
Answer: Wiggling the left stick horizontally seems to
guarantee a quick escape. If I do nothing I will always die no matter how healthy my character is.
There's also unlockable skill moves that provide an alternative method for escaping:
Answer: There should be a button prompt to mash a random face button.
Comment: There was a tutorial screen explaining that a button prompt only appears when being grabbed by several zombies at once.

How to escape from zombie grab?


How many points per heart?

Question: Does anyone know how many points you need to get to the next heart? I kinda want to try and calculate how many times I need to give gifts to people for the next heart.
Answer: According to the Wiki:

Each heart is 250 friendship points.

You can gain friendship points by:

talking to villagers (+10 if the villager is in the middle of a special animation, like exercising or using a camera, otherwise +20; can only score once per day)
Completing a delivery quest for them (+150);
giving them a gift they like (see Gifts)
making certain choices in their heart events.

You can lose friendship points by:

not talking to a villager (-2/day);
giving them a gift they dislike (see Gifts);
hitting them with the slingshot;
rummaging through a trash can when they're nearby (-25, except Linus who doesn't mind).

How many points per heart?


View need restarting the tkinter app

Question: I have made tkinter app along with sqlite3 with many frames in it. I have made several tables. I can add items to the table without any flaws. However, I need to close and reopen the app to view the added changes in the database. Is there any solution for that?
Comment: Please give us an example. However the solution may be either use tkinter `update()` or use multithreading to avoid window frozing.
Comment: If you use a function to place everything inside of a frame then you can simple `destroy()` the frame and then rerun that function to pull everything again. Should be simple enough. Can you provide an example code of what you are doing?
Answer: Yes, the solution is to write your code in such a way that you can reload the data. There's no special trick to doing that, but it doesn't happen for free. All widgets have a method for modifying their data. You simply need to detect when a change occurs (or give the user a "refresh" button), and then reload the data.

View need restarting the tkinter app


ERROR: syntax error at or near "declare" LINE 5: declare @b_result bit ^

Question: This is a working function in SQL Server 2014 Express
CREATE FUNCTION [dbo].[Func_Account_FollowingCustomer]
    (@AccountNumber NVARCHAR(20))
RETURNS BIT
AS
BEGIN
    DECLARE @bResult BIT

    IF (SELECT COUNT(AccountNumber) FROM dbo.Account AS A
        WHERE DetailByAccountObject = 1
          AND AccountObjectType = 1
          AND AccountNumber = @AccountNumber) > 0
        SET @bResult = 1
    ELSE
        SET @bResult = 0

    RETURN @bResult
END

I try to convert to PostgreSQL 14, I have
CREATE FUNCTION public.func_account_following_customer(IN account_number character varying)
    RETURNS bit
    LANGUAGE 'sql'

declare @b_result bit
begin
if(select count(account_number) from account as a where detail_by_account_object = 1 and account_object_type = 1 and account_number = @account_number) > 0
    set @b_result = 1
else
    set @b_result = 0
return @b_result;
end;

ALTER FUNCTION public.func_account_following_customer(character varying)
    OWNER TO postgres;

Error

ERROR: syntax error at or near "declare" LINE 5: declare @b_result bit ^

How to fix it?
Comment: This kind of thing isn't standardised or portable; you can't just change keywords to lower-case and expect it to work in a completely different DBMS.
Answer: language sql can't use variables or procedural elements (like IF), you need language plpgsql - but the syntax for variable names is different and the assignment  is not done using set
The function body is a string constant, typically specified using dollar quoting.
If you want to return true/false flags, use boolean instead of bits.
Parameters or variables are referenced using @ but simply with their name.
But you don't need procedural code for such a simple SQL query that just returns true/false.
CREATE FUNCTION public.func_account_following_customer(IN p_account_number character varying)
    RETURNS boolean
    LANGUAGE sql
as
$$
  select count(*) > 0
  from account as a
  where detail_by_account_object = 1
    and account_object_type = 1
    and account_number = p_account_number;
$$
;

As a PL/pgSQL function this would be:
CREATE FUNCTION public.func_account_following_customer(IN p_account_number character varying)
    RETURNS boolean
    LANGUAGE plpgsql
as
$$
declare
  l_result boolean;
begin
  if (select count(*)
      from account as a
      where detail_by_account_object = 1
        and account_object_type = 1
        and account_number = p_account_number) > 0
  then
    l_result := true;
  else
    l_result := false;
  end if;
  return l_result;
end;
$$
;

Comment: Can you create function via pgAdmin's GUI? I use GUI for create function, but cannot output SQL script like you.
Comment: I don't use pgAdmin - but you can run any SQL statement you want, through the "Query tool". You need to store the source code of that function somewhere in git anyway, so sooner or later you need the full CREATE FUNCTION statement anyway. So why not start with it directly.
Comment: When you have time and tool, please guide me via pgAdmin GUI. I want use GUI for official syntax generated by tool. https://user-images.githubusercontent.com/1328316/174634350-86b71e51-d1ec-4187-97ca-044de8a2dde8.mp4


Molecular level Fallout 4 bug - only showing one piece

Question: I've played this game with 4 different characters that go up to level 85+ and i just ran into a unique problem.
When im in workshop mode in Sanctuary trying to build the molecular beam i only have one piece of the machine available to build.  STABLIZED REFLECTOR PLATFORM. The other pieces simply aren't there in the special section. I have the artillery piece, robot workbench, and then the stablized reflector platform. That's all.
So weird and so frustrating.
I disabled all the mods and went back to the Glowing Sea mission and worked my way back to molecular level and the problem persists.
Comment: Have you actually built the platform yet? What is your current objective? Based on what you've written, it doesn't actually look like anything is wrong.
Answer: You need to build the base first, then the quest will update and you'll have to go back and talk to your assisting NPC to get the ability to build the other pieces.


How can I view FPS in Skyrim?

Question: I want to be able to see the FPS I'm running at, as it feels a bit low.
I've tried tdt in the console to no avail.
Comment: tdt definitely doesn't work for me either... might have been something that worked in beta?
Comment: tdt doesnt work for me either..
Comment: You can use the steam FPS counter (settings>In-game). If you don't own Skyrim on steam, you can add it as a non-steam game and the FPS counter will show up.
Answer: Install a tool like FRAPS (free, but limited to 30 seconds of screen recording) or RivaTuner (free) and you will be able to see the FPS of any game.
FRAPS can be used for showing your FPS, as well as recording your gameplay, but that will require you to buy the full version.
Comment: From what I've heard, wouldn't those slow Skyrim down? Especially FRAPS.
Comment: @TheCommunistDuck: FRAPS only slows down the game when you are recording a video. Counting the amounts of frames per second and writing 2 numbers on the screen will not have any influence.
Answer: http://www.nexusmods.com/skyrim/mods/24239
A self-described simple, bare-bones FPS counter. Does exactly what it says on the tin. I use it, I like it.
Has a couple extra features, too. There's a key to toggle it, a key to change the corner it appears in, and even a key to change the priority of the Skyrim process. Everything configurable through the INI.
It's an SKSE plugin, but apparently there's another way to use it if you don't want SKSE.

How can I view FPS in Skyrim?


No detection of Windows 7 installed already

Question: When I am trying to boot my PC with Ubuntu via bootable USB, it says it doesn't detect any OS installed and asks to install it on whole hard disk. I want to install it along side my Windows 7 OS.
Boot info here.
Answer: choose manual option, and then you can choose the partiton on which you want to install.
Or simply use wubi.exe to install easily like software installation inside windows.
Answer: You have overlapping partitions.

Backup your documents
via Gparted, delete the sda3, sda5, sda6, sda7 partitions
retry the Ubuntu installation


Background-image for entire Ionic (4) Page not overlapping header and footer

Question: I am migrating my Ionic 3 project to Ionic 4 and stumbled upon a problem with a page-specific background image which worked perfectly in Ionic 3 but not in Ionic 4.
The page has a image which should cover the full page, the page however has a ion-header and ion-footer component as well.
In my Ionic 3 the html looked as following:
<ion-header [ngClass]="'no-shadow'">

  <ion-navbar transparent>
    <ion-buttons start>
      <button ion-button icon-only menuToggle>
        <ion-icon name="menu"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>

</ion-header>

<ion-content>

  <ion-row class="logo-row" *ngIf="isKeyboardHidden">
    <ion-col col-8 offset-2 padding text-center>

    </ion-col>
  </ion-row>

  <form #f="ngForm" (ngSubmit)="onSubmit()">
    <ion-row>
      <ion-col>

      </ion-col>
    </ion-row>
    <ion-list no-lines class="form-inputs">
      <ion-item>
        <ion-label icon-only>
          <ion-icon name="person"></ion-icon>
        </ion-label>
        <ion-input
          type="text"
          name="username"
          [(ngModel)]="account.username"
          [placeholder]="'USERNAME' | translate"
          required></ion-input>
      </ion-item>
      <ion-item>
        <ion-label icon-only>
          <ion-icon name="unlock"></ion-icon>
        </ion-label>
        <ion-input
          type="password"
          name="password"
          [(ngModel)]="account.password"
          [placeholder]="'PASSWORD' | translate"
          required></ion-input>
      </ion-item>
    </ion-list>
    <ion-row>
      <ion-col col-10 offset-1>
        <button
          ion-button
          block
          [disabled]="!f.valid || isLoading">
          {{'LOGIN' | translate}}
        </button>
      </ion-col>
    </ion-row>
  </form>
</ion-content>

<ion-footer *ngIf="isKeyboardHidden">
  <ion-row>
    <ion-col text-center>

          <a class="default-text"
             Some Footer Text

    </ion-col>
  </ion-row>
</ion-footer>

With the scss:
page-login {
  .content {
    background: url('../assets/img/background.png') no-repeat;
    background-size: cover;

    #logo {
      padding-top: 5rem;
    }

    form {
      position: absolute;
      bottom: 0;
      width: 100%;

      .logo-row {
        margin-bottom: 40%;
      }

      .form-inputs {

        .label-ios {
          width: 60px;
          max-width: 60px;
        }
      }
    }
  }
}

The result:

In Ionic 4 the header and footer behave differently, for some reason I have to make the ion-tool bar transparent in the scss, and move both the ion-header and ion-footer within the ion-content to make the image overlap both, the scss:
ion-toolbar {
  --background: transparent;
  //--ion-toolbar-text-color: white;
  //--ion-color-base: transparent !important;
}

ion-content {

  --background: url('../../../assets/img/background.png') no-repeat center/cover fixed;
  --background-size: cover;

  #logo {
    padding-top: 5rem;
  }

  form {
    --position: absolute;
    --bottom: 0;
    --width: 100%;

   // rest of scss..
  }
}

The html:
<ion-content>
  <ion-header no-border [ngClass]="'no-shadow'">
    <ion-toolbar slot="fixed">
      <ion-buttons slot="start">
        <ion-menu-toggle>
          <ion-button>
            <ion-icon slot="icon-only" name="menu"></ion-icon>
          </ion-button>
        </ion-menu-toggle>
      </ion-buttons>
    </ion-toolbar>
  </ion-header>

  <ion-row class="logo-row" *ngIf="isKeyboardHidden">
    <ion-col size="8" offset="2" class="ion-padding ion-text-center">

    </ion-col>
  </ion-row>

  <form #f="ngForm" (ngSubmit)="onSubmit()">
    <ion-row>
      <ion-col>

      </ion-col>
    </ion-row>
    <ion-list no-lines class="form-inputs">
      <ion-item>
        <ion-label>
          <ion-icon slot="icon-only" name="person"></ion-icon>
        </ion-label>
        <ion-input
          type="text"
          name="username"
          [(ngModel)]="account.username"
          [placeholder]="'USERNAME' | translate"
          required></ion-input>
      </ion-item>
      <ion-item>
        <ion-label>
          <ion-icon slot="icon-only" name="unlock"></ion-icon>
        </ion-label>
        <ion-input
          type="password"
          name="password"
          [(ngModel)]="account.password"
          [placeholder]="'PASSWORD' | translate"
          required></ion-input>
      </ion-item>
    </ion-list>
    <ion-row>
      <ion-col size="10"  offset="1">
        <ion-button
          block
          [disabled]="!f.valid || isLoading">
          {{'LOGIN' | translate}}
        </ion-button>
      </ion-col>
    </ion-row>
  </form>

  <ion-footer transparent *ngIf="isKeyboardHidden">
    <ion-row>
      <ion-col class="ion-text-center">

          {{'DEVELOPED_BY' | translate}}

            Some Text

      </ion-col>
    </ion-row>
  </ion-footer>
</ion-content>

This does not seem to make sense to me, there must be a way to move the ion-header and ion-footer outside of the ion-content in the html, with keeping the image overlapping both?
If I move both back out, the result looks as following, and thus wrong:

UPDATE
The proposed answer by @Sergey Rudenko works to some extend, the background image is displayed correctly but the disadvantage is that the position: absolute on the footer does not pushes the form element above the footer, instead the form element is positioned above / over the footer:
Comment: problem is your are using ion-header inside your ion-content element. take them out and everything will be fixed. Same as the answer blow.
Answer: Sorry if I am not fully understanding your context, but can't you do something like this:
Template:
<ion-header style="position: absolute; left: 0; top: 0; right: 0" no-border>
    <ion-toolbar>
        <ion-title>
            Ionic 4 template
        </ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>

</ion-content>

<ion-footer style="position: absolute; left: 0; bottom: 0; right: 0" no-border>
  <ion-toolbar>
    <ion-button expand="block">Hit Me</ion-button>
  </ion-toolbar>
</ion-footer>

SCSS:
ion-toolbar {
  --background: transparent;
  --ion-color-base: transparent !important;
}

ion-content {
  --background: url('https://via.placeholder.com/150') no-repeat center/cover fixed;
  --background-size: cover;
}

ion-header, ion-footer {
  border: 0px !important;
  border-bottom-color: transparent !important;
  background-image: none !important;
  border-bottom: none !important;
}

Depending on your use case maybe not using "absolute" but "fixed" position etc?
Comment: The disadvantage of this solution is that the form element is displayed over the footer element when using `position: absolute;` on the footer. See my updated post for more details.
Comment: Hey @Nicolas yes this adds a nuance. But you could place form inside footer in this case or just use css to deliniate that. But agree its not as clean as it was.


Javascript get city name from google autocomplete or from lat and lng

Question: I find a way to get correct city name from google autocomplete or from lat and lng. Now I use this code:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
for (var i = 0; i < place.address_components.length; i++) {
  for (var j = 0; j < place.address_components[i].types.length; j++) {
        if (place.address_components[i].types[j] == "locality") {$("#city").val(place.address_components[i].long_name);
         }

Now I use a type "locality" for city name, but sometimes for other addresses it may be "administrative_area_level_1", "administrative_area_level_2", "administrative_area_level_3" ..etc.
How can I get CORRECT city name from address?
Thanks for help.
For "Lenina, Minks, Belarus" I have such result:
 {
  "results" : [
  {
     "address_components" : [
        {
           "long_name" : "vulica Lienina",
           "short_name" : "vulica Lienina",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Minsk",
           "short_name" : "Minsk",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Belarus",
           "short_name" : "BY",
           "types" : [ "country", "political" ]
        }
     ],
     "formatted_address" : "vulica Lienina, Minsk, Belarus",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 53.9049197,
              "lng" : 27.5804421
           },
           "southwest" : {
              "lat" : 53.8868641,
              "lng" : 27.553896
           }
        },
        "location" : {
           "lat" : 53.8958051,
           "lng" : 27.5659861
        },
        "location_type" : "GEOMETRIC_CENTER",
        "viewport" : {
           "northeast" : {
              "lat" : 53.9049197,
              "lng" : 27.5804421
           },
           "southwest" : {
              "lat" : 53.8868641,
              "lng" : 27.553896
           }
        }
     },
     "place_id" : "ChIJL_x0NsTP20YRE6LICTM5v2I",
     "types" : [ "route" ]
  },
  {
     "address_components" : [
        {
           "long_name" : "Lenina",
           "short_name" : "Lenina",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Slucki rajon",
           "short_name" : "Slucki rajon",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "Minskaja voblasć",
           "short_name" : "Minskaja voblasć",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "Belarus",
           "short_name" : "BY",
           "types" : [ "country", "political" ]
        }
     ],
     "formatted_address" : "Lenina, Belarus",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 53.0604058,
              "lng" : 27.2418881
           },
           "southwest" : {
              "lat" : 53.0405422,
              "lng" : 27.2215462
           }
        },
        "location" : {
           "lat" : 53.0546355,
           "lng" : 27.229549
        },
        "location_type" : "APPROXIMATE",
        "viewport" : {
           "northeast" : {
              "lat" : 53.0604058,
              "lng" : 27.2418881
           },
           "southwest" : {
              "lat" : 53.0405422,
              "lng" : 27.2215462
           }
        }
     },
     "place_id" : "ChIJNTp2Gl6t2UYRI1cE6L4oVh8",
     "types" : [ "locality", "political" ]
  }
 ],
"status" : "OK"
}

Result has two address_components...
Answer: Here's how I extract the city name : (Working example with a geocoding results sample)

let results = [
  {
     "address_components" : [
        {
           "long_name" : "vulica Lienina",
           "short_name" : "vulica Lienina",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Minsk",
           "short_name" : "Minsk",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Belarus",
           "short_name" : "BY",
           "types" : [ "country", "political" ]
        }
     ],
     "formatted_address" : "vulica Lienina, Minsk, Belarus",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 53.9049197,
              "lng" : 27.5804421
           },
           "southwest" : {
              "lat" : 53.8868641,
              "lng" : 27.553896
           }
        },
        "location" : {
           "lat" : 53.8958051,
           "lng" : 27.5659861
        },
        "location_type" : "GEOMETRIC_CENTER",
        "viewport" : {
           "northeast" : {
              "lat" : 53.9049197,
              "lng" : 27.5804421
           },
           "southwest" : {
              "lat" : 53.8868641,
              "lng" : 27.553896
           }
        }
     },
     "place_id" : "ChIJL_x0NsTP20YRE6LICTM5v2I",
     "types" : [ "route" ]
  },
  {
     "address_components" : [
        {
           "long_name" : "Lenina",
           "short_name" : "Lenina",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Slucki rajon",
           "short_name" : "Slucki rajon",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "Minskaja voblasć",
           "short_name" : "Minskaja voblasć",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "Belarus",
           "short_name" : "BY",
           "types" : [ "country", "political" ]
        }
     ],
     "formatted_address" : "Lenina, Belarus",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 53.0604058,
              "lng" : 27.2418881
           },
           "southwest" : {
              "lat" : 53.0405422,
              "lng" : 27.2215462
           }
        },
        "location" : {
           "lat" : 53.0546355,
           "lng" : 27.229549
        },
        "location_type" : "APPROXIMATE",
        "viewport" : {
           "northeast" : {
              "lat" : 53.0604058,
              "lng" : 27.2418881
           },
           "southwest" : {
              "lat" : 53.0405422,
              "lng" : 27.2215462
           }
        }
     },
     "place_id" : "ChIJNTp2Gl6t2UYRI1cE6L4oVh8",
     "types" : [ "locality", "political" ]
  }
 ]

let matches = results[0].address_components.filter(address_component =>
   ["locality", "colloquial_area"].some(word => ~address_component.types.indexOf(word)))

if (!matches || !matches.length) {
  console.log("Could not resolve city name.")
} else {
  console.log("Found city : ", matches[0].short_name) // Prints : Minsk
}
Comment: So you also use locality type for city?
Yes, sometimes it works, but for example, for address "Lenina, Minsk, Belarus" it shows city name like "Lenina" but must show Minsk.
Comment: Could you add to your original question a sample of the results you can't exploit (like I did, a full results JSON) ?
Comment: I added json result to my post. And found that there are two address_components in the result . How can I use only firts address_components ?
Comment: I have just replaced my results with yours, and it outputs correctly "Minsk".
Comment: It is link to json: http://maps.googleapis.com/maps/api/geocode/json?address=Lenina+Minsk+Belarus&sensor=true&language=en
` var place = autocomplete.getPlace();
                let matches = place.address_components.filter(address_component =>
                        ["locality", "colloquial_area"].some(word => ~address_component.types.indexOf(word)));

                if (!matches  || !matches.length) {
                    return console.log("Could not resolve city name")
                }
                let foundCity = matches[0].short_name;` =locality from second address_components
Comment: Yes, I know, I saw your json, and I updated my answer with your json, and it works, as you can see. My code outputs : "Minsk". Now what's wrong?
Comment: I have error: result[0] is undefined
I get result as: `var result = autocomplete.getPlace();`
Comment: Adapt my answer to your results structure, then. `result[0] is undefined` means it's not an array, very well, just use `results`, I don't know, just look at your structure.


UINavigationController showing wrong navigationItem after calling pushViewController

Question: I have a table view that displays a new view when one of its items is pressed. The problem is the new view's navigationItem property isn't being displayed. Instead, the previous view's (the table view) navigation item appears to be displayed (the table view's navigation bar animates in unchanged).
Here is the press handler that pushes the new view:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  NSLog(@"--- showing asset picker");
  ELCAssetTablePicker *picker = [[ELCAssetTablePicker alloc] initWithNibName:@"ELCAssetTablePicker" bundle: nil];
    picker.parent = self;

  picker.assetGroup = [self.assetGroups objectAtIndex:indexPath.row];
  //[picker.assetGroup setAssetsFilter:[ALAssetsFilter allPhotos]];
  [self.navigationController pushViewController:picker animated:YES];

  [picker release];
}

And here is the viewDidLoad method of the view being pushed (ELCAssetTablePicker) where the title and buttons of self.navigationItem are updated:
- (void)viewDidLoad
{
  [super viewDidLoad];
  [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
  [self.tableView setAllowsSelection:NO];

  NSMutableArray *tempArray = [[NSMutableArray alloc] init];
  self.elcAssets = tempArray;
  [tempArray release];
  UINavigationItem* navigationItem = self.navigationItem;

  UIBarButtonItem *doneButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneAction:)] autorelease];

  [navigationItem addBackBarButtonItemWithTitle:@"Back" forController:self];
  [navigationItem addRightBarButtonItem:doneButtonItem];
  [navigationItem setTitle:@"Loading..."];

  [self performSelectorInBackground:@selector(preparePhotos) withObject:nil];
}

Why isn't the navigation bar being updated when a new view is pushed to the UINavigationController?
Comment: Wow. I didn't know anyone used MRC any more. Brave.
Comment: @rmaddy It's an old project that I've been tasked with doing a little upkeep on. If it were up to me, I wouldn't be using Objective-C at all.
Comment: Did you find any solution. I'm facing this exact weird bug for one of my VC in swift.
Answer: Make navigationItem global. Its reference is getting killed I guess. Why don't use simple self.navigationItem.
- (void)viewDidLoad
{
  [super viewDidLoad];
  [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
  [self.tableView setAllowsSelection:NO];

  NSMutableArray *tempArray = [[NSMutableArray alloc] init];
  self.elcAssets = tempArray;
  [tempArray release];

  UIBarButtonItem *doneButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneAction:)] autorelease];

  [self.navigationItem addBackBarButtonItemWithTitle:@"Back" forController:self];
  [self.navigationItem addRightBarButtonItem:doneButtonItem];
  [self.navigationItem setTitle:@"Loading..."];

  [self performSelectorInBackground:@selector(preparePhotos) withObject:nil];
}

Comment: I am using `self.navigationItem`: `UINavigationItem* navigationItem = self.navigationItem;` The only reason I created a local variable is to make it easier to access in the debugger.


Make CRUD for a table with a composite in yii

Question: So i have a many to many relation between two tables which are "Item" and "Tier" and i have an intermediate table "Item_Tier" which both of there Fks acting as Pks which will make the key a composite key.
Now i am trying to make a simple CRUD for the intermediate table and i know that Yii has a limitation that it cant create the CRUD for tables with composite keys. I have fond the extension Giix which advertises that it does support the CRUD for composite keys.
Now i have followed it installation process and I can see that it is added to my Gii because I can see the Giix crud and model generator. I have create the model with both Giix and gii to make sure it has no effect and it still gives me the error that it can not create the CRUD because of the Composite id.
How can i fix this please?
Answer: I think that you may not need CRUD operations for many_many connection tables.
You have the Item and Tier CActiveRecords for the two tables.
You can specify these relations in them:
<code>// Item
public function relations(){
    return array(
        ...
        'tiers'=>array(self::MANY_MANY,'Tier', 'Item_Tier(item_id, tier_id)'),
        ...
    );
}
// Tier
public function relations(){
    return array(
        ...
        'items'=>array(self::MANY_MANY,'Item', 'Item_Tier(tier_id, item_id)'),
        ...
    );
}
</code>
So now you can read the items for a tier, and the tiers for an item.
Then you can create an addItem($item) function in the Tier class (or an addTier($tier) in the item class, similar to this)
Add connection:
<code>// Tier class
public function addItem(Item $item){
    // check if item is saved. You may check if the current tier object is saved, similarly if($this->isNewRecord){...}
    if($item->isNewRecord){
        // item object is not saved into the db yet, cannot assign
        // you can try to save it here, or throw an exception, or just return false and handle where you call this method
        return false;
    }
    $exists = Yii::app()->db->createCommand
        ->from('Item_Tier')
        ->where('item_id=:iid AND tier_id=:tid',array(':iid'=>$item->id,':tid'=>$this->id))
        ->queryRow();
    if($exists !== FALSE){
        // this item is already added to this tier
        return true;
    }
    $affectedRows = Yii::app()->db->createCommand->insert('Item_Tier',array('item_id'=>$item->id,'tier_id'=>$this->id));
    return $affectedRows > 0;
}
</code>
Now you can also assign items to tiers, and tiers to items (if you implement a similary method in the Item class)
Delete connection:
<code>// Tier class
public function deleteItem(Item $item){
    // check if item is saved. You may check if the current tier object is saved, similarly if($this->isNewRecord){...}
    if($item->isNewRecord){
        // item object is not saved into the db yet, cannot assign
        // you can try to save it here, or throw an exception, or just return false and handle where you call this method
        return false;
    }
    $affectedRows = Yii::app()->db->createCommand->delete('Item_Tier','item_id=:iid AND tier_id=:tid',array(':iid'=>$item->id,':tid'=>$this->id));
    return $affectedRows > 0;
}
</code>
And an update is equivalent of deleting a connection and adding a new connection.
This way you don't have to create a new AR class for the connection table with crud operations.
Hope this helps!
Comment: THis is execrtly what i did after playing with it for an hour or so. Thank you for the detailed guide.


How do I perform a backup of sudoers file?

Question: After reading the following two posts:
Trying to install an openVPN GUI messed up sudoers
Standards accounts are able to get root access using sudo without password request
I would like to learn how to perform a backup of /etc/sudoers file so that I can restore it in the event of a mess-up after installing a non-Ubuntu-package-ready software.
Any help would be much appreciated.
Answer: To backup:
sudo cp /etc/sudoers /etc/sudoers.backup

To restore:
sudo rm -rfv /etc/sudoers && sudo mv /etc/sudoers.backup /etc/sudoers

Comment: +1 can't believe you are first to answer in 6 years. There is also the directory `/etc/sudoers.d` to backup.
Answer: If /etc/sudoers is going to be a problem you probably should just keep all of /etc in version control since they're just some text files. Check this out:

Is there an application to manage config files in the /etc folder with version control software?
Comment: Thanks for your reply but I am still clueless after reading the page referenced by your URL. I do not know what "version control" and "git" mean. I am new to Ubuntu and yes, I am not an IT guy. I just wish to have a simple method of backing up /etc/sudoers file.


Draw random bitmap in the onDraw method

Question: Firstly I am adding my cards to a list like that:
<code>    private void initCards() {
    for (int i = 0; i < 20; i++) {
    Bitmap tempBitmap = BitmapFactory.decodeResource(myContext.getResources(),R.drawable.ic_launcher);
    scaledCardW = (int) (screenW/10);
    scaledCardH = (int) (scaledCardW*1.28);
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(tempBitmap,scaledCardW, scaledCardH, false);
    deck.add(scaledBitmap);

    }
</code>
But when it came to on draw method,my program is transforming a thing like an animation.
    My onDraw method is here:
<code>    protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

    int left=newInteger.nextInt(screenW);
    int right=newInteger.nextInt(screenH);

    for(int i=0 ; i<k ;i++){
        canvas.drawBitmap(deck.get(i), left, right, null);
    }

}
</code>
These bitmaps must have random location and if I change the k from our main Activity different numbers of bitmaps must be drawen.Because of that,ı cannot remove the invalite() function.
Can anybody help me?Unfortunately,another topics about this problem are not providing my request.
Answer: Your bitmaps keep moving because you are randomizing their position every time you draw. Try moving these lines:
<code>left = newInteger.nextInt(screenW);
right = newInteger.nextInt(screenH);
</code>
into the same function that changes the value of k.

Draw random bitmap in the onDraw method


NSMutableString is not working for HTML Text

Question: Code is working fine..all the HTML tags also implemented but when i set attributes like font and color the HTML string convert into normal string..
NSString * htmlString = [NSString stringWithFormat:@"
%@
",_strAchievementMsg];

NSDictionary *attrDict = @{ NSFontAttributeName : [UIFont fontWithName:HelveticaNeue size:11.0f],
NSForegroundColorAttributeName :[UIColor colorWithRed:105.0f/255.0f green:115.0f/255.0f blue:144.0f/255.0f alpha:1.0f]
                                           };
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
[attrStr addAttributes:attrDict range:NSMakeRange(0,attrStr.length)];
_strAchievementAttributed = attrStr;

Answer: ya i had the same problem for some reason HTML NSAttributedString does not work with attributes but you can set the font and color using the html string like this:
NSString * htmlString = [NSString stringWithFormat:@"
%@
",_strAchievementMsg];

Comment: ha ha, this is Jugaad
Answer: You have to update all the ranges in the NSMutableAttributedString with updated font and color values.
Use this modified code:
NSString * htmlString = [NSString stringWithFormat:@"
%@
",_strAchievementMsg];

NSDictionary *attrDict = @{ NSFontAttributeName : [UIFont fontWithName:HelveticaNeue size:11.0f],
                            NSForegroundColorAttributeName :[UIColor colorWithRed:105.0f/255.0f green:115.0f/255.0f blue:144.0f/255.0f alpha:1.0f]
                            };
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

NSMutableAttributedString * updatedAttrStr = [[NSMutableAttributedString alloc] initWithAttributedString:attrStr];

[attrStr enumerateAttributesInRange:NSMakeRange(0, attrStr.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
    [updatedAttrStr addAttributes:attrDict range:range];
}];
_strAchievementAttributed = updatedAttrStr;


Convert a dataframe column into a list of object

Question: I am using pandas to read a CSV which contains a phone_number field (string), however, I need to convert this field into the below JSON format
[{'phone_number':'+01 373643222'}] and put it under a new column name called phone_numbers, how can I do that?
Searched online but the examples I found are converting the all the columns into JSON by using to_json() which is apparently cannot solve my case.
Below is an example
import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'],
                   'phone_number': ['+1 569-483-2388', '+1 555-555-1212', '+1 432-867-5309']})

Comment: please create an example for your question, check [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)
Comment: tolist() should do the job. Check answer here:
https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column
Comment: `[df["phone_number"].to_json()]` will convert the Series to json in a list
Comment: it is not working by doing `df['phone_numbers'] = [df["phone_number"].to_json()]`
Comment: do you need: `df['phone_numbers']=[f'phone_number:{i}' for i in df['phone_number']]` or `df['phone_numbers']=[f'[phone_number:{i}]' for i in df['phone_number']]`  ?
Answer: use map function like this
df["phone_numbers"] = df["phone_number"].map(lambda x: [{"phone_number": x}] )

display(df)


making debug code and release code equal in visual studio 2012 express

Question: I'm a beginner with visual studio 2012 express and applications development in general. Right now I have release code that is spot on to what I want the app to do and output.  When I change the selector to debug, I get output that is about two iterations back, and which does not match the code I'm seeing in the editor screen. How do I make the debug code equal to the release code in the IDE?
Comment: There shouldn't be any difference in the codebase between the two configurations.  Perhaps you have some conditionally compiled code?
Answer: One source of distinction between Release and Debug builds is any code that using the #DEBUG directive. This will only exist in the debug version. Another less obvious source of distinction is the solution build configuration:

Right-click on the Solution and click Properties.
Go to Configuration Properties --> Configuration.
Toggle between Debug and Release on the Configuration drop-down box at the top left, and look for any differences in Platform or the Build check box.

One other thing you could try is a rebuild - right-click on Solution and click Rebuild.
Comment: Checking the configuration properties, there seems to be no difference at that level. Changing the configurations in the toolbar doesn't change the code in the editor window, but when I run the debugger, the debug code being compiled is different than the release code being shown in the editor window. Rebuild makes no difference, the same behavior is exhibited.
Answer: After doing some research and some by-guess-by-golly work, it seems that selecting the debug configuration and then under the build menu selecting clean solution.  Then build the solution again and voila, the right code is used and the two configurations once again track. Thank you to all for your inputs.


How to inherit methods and then add something to them?

Question: class uni_person {
    public:
    string f_name;   // 1
    string s_name;   // 2
    int age;         // 3
    string institute;// 5
    string uni;      // 6
    string p_number; // 7

    void addSmth() {
        int x;
        cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
        cin >> x;
        switch (x) {
            case 1: cin >> f_name; break;
            case 2: cin >> s_name; break;
            case 3: cin >> age; break;
            case 5: cin >> institute; break;
            case 6: cin >> uni; break;
            case 7: cin >> p_number; break;
            default: cout << "Error" << endl; break;
        }
    }
};

class Student: public uni_person {
    public:
    int course;
    int group;

    void addSmth() {
        int x;
        cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
        cin >> x;
        switch (x) {
            case 4: cin >> course; break;
            case 8: cin >> group; break;
        }
    }
};

So I have a problem, I'm currently learning OOP in c++ and Ive came to this problem... How do to make class inherit other classes method and add something new to it without rewriting it? Is there a special function for it or what?
I rewritten addSmth() and want to add some more behavior to addSmth().
Comment: The easiest way would be to add a call to `uni_person::addSmth()` to the `Student`s `addSmth()`.
Comment: You can't add to a switch case like that, closest you can get is to use an array of functions and index them with `x` instead of switching on it.
Comment: If you separate the input code into another funtion, you can call `uni_person::addSmth` from `Student::addSmth` if x is neither 4 nor 8.
Also, you should probably mark the `Student::addSmth()` function `override` and `uni_person::addSmth()` `virtual`
Comment: The best way is to move user interaction out of these classes completely.
Comment: Declare `addSmthh()` as a `virtual` function of `uni_person`.   Then override it in class `Student` (rather than, since it is currently not `virtual`, hiding it as you are).    From there, the implementation of `Student::addSmth()` can call `uni_person::addSmth()`.
Answer: First you should separate the user interaction from the actual logic. If you have that you can call the Base function from the Derived function explicitly:
Also you should probably mark the base functions virtual and the derived functions override.
virtual void uni_person::promptAddSmth()
{
    cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
    int x;
    cin >> x;
    addSmth(x);
}

virtual void uni_person::addSmth(int x)
{
    switch (x) {
    case 1: cin >> f_name; break;
    case 2: cin >> s_name; break;
    case 3: cin >> age; break;
    case 5: cin >> institute; break;
    case 6: cin >> uni; break;
    case 7: cin >> p_number; break;
    default: cout << "Error" << endl; break;
    }
}

void Student::promptAddSmth() override
{
    cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
    int x;
    cin >> x;
    addSmth(x);
}

void Student::addSmth(int x) override
{
    switch(x) {
    case 4: cin >> course; break;
    case 8: cin >> group; break;
    default: uni_person::addSmth(x); break;
    }
}

Answer: There is no way to add some more behavior to a method which does not expect in in C++. But you can design your method for addition from the beginnig:
class uni_person
{
public:
    string f_name;   // 1
    string s_name;   // 2
    int age;         // 3
    string institute;// 5
    string uni;      // 6
    string p_number; // 7

    void addSmth()
    {
        int x;
        cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
        cin >> x;
        switch (x) {
            case 1: cin >> f_name; break;
            case 2: cin >> s_name; break;
            case 3: cin >> age; break;
            case 5: cin >> institute; break;
            case 6: cin >> uni; break;
            case 7: cin >> p_number; break;
            default: cout << "Error" << endl; break;
        }

        // Call additional code. Does nothing by default.
        appendix();
    }

protected:

    virtual void appendix() {}
};

class Student: public uni_person
{
public:
    int course;
    int group;

private:
    void appendix() override
    {
        // Code from your Student::addSmth().
        // Will be called at the end of uni_person::addSmth().

        int x;
        cout << "What do you want to add about the student ?\n1: first name\n2: second name\n3: age\n4: course\n5: institute\n6: university\n7: phone number\n8: group\n";
        cin >> x;
        switch (x) {
            case 4:case 4: cin >> course; break;
            case 8: cin >> group; break;
        }
    }
};

Another child class might add some other behavior, which will be called correctly due to virtuality.
Also please mind other participants' advice about you design and code style.


How can I click on image inside dynamically generated Oracle MAF List Item?

Question: I am creating list view dynamically by using code below:
<amx:listView var="row" value="#{bindings.allMeetingsAsOrganizer.collectionModel}"
                  fetchSize="#{bindings.allMeetingsAsOrganizer.rangeSize}"
                  selectedRowKeys="#{bindings.allMeetingsAsOrganizer.collectionModel.selectedRow}"
                  selectionListener="#{bindings.allMeetingsAsOrganizer.collectionModel.makeCurrent}"
                  showMoreStrategy="autoScroll" bufferStrategy="viewport" id="panel1">
      <amx:listItem id="li1"  showLinkIcon="false"  actionListener="#{viewScope.browseMeetingsBean.onMeetingSelect}" action="toDisplayMeeting">
            <amx:tableLayout width="100%" id="tl3" cellSpacing="5">
                <amx:rowLayout id="rl1">
                    <amx:cellFormat width="40px" halign="center" id="cf2">
                        <amx:image source="images/outlook.png" id="i3" inlineStyle="height:38px;"/>
                    </amx:cellFormat>
                    <amx:cellFormat width="100%" height="43px" id="cf5">
                        <amx:outputText value="#{row.subject}" id="ot2" inlineStyle="font-size:large;margin:5px;"/>
                        <amx:outputText value="#{row.meeting_location}" id="ot3"
                                        inlineStyle="font-size:medium; margin:5px;"/>
                        <amx:outputText value="#{row.start_date_time}" id="ot7"
                                        inlineStyle="color:Teal; font-size:small;margin:5px;"/>
                        <amx:outputText value="Attendees : #{row.attendees_count_internal}/#{row.attendees_count_external}" id="ot4"
                                        inlineStyle="color:Teal; font-size:small;margin:5px;"/>
                    </amx:cellFormat>
                     <amx:cellFormat width="40px" halign="center" id="cf1">
                        <amx:image source="images/confirm.png" id="i1" inlineStyle="height:28px;"/>
                    </amx:cellFormat>
                </amx:rowLayout>
            </amx:tableLayout>
      </amx:listItem>
</amx:listView>

As you can see there is already an action listener on list item, then how can I perform any action by clicking on image inside list item?
which is :
<amx:cellFormat width="40px" halign="center" id="cf1">
 <amx:image source="images/confirm.png" id="i1" inlineStyle="height:28px;"/>

Answer: Surround your amx:image tag with an amx:commandLink tag, on the amx:commandLink tag you can define your actionListener for the image.


Should I use fileName or filePath to describe a fully qualified file name in .NET?

Question: I have a method to read a file, the parameter should be the fully qualified file name.
The code I have uses fileName, filePath, or path randomly.

void ReadSomeFile(String fileName);
  void ReadSomeFile(String filePath);
  void ReadSomeFile(String path);

The .net method "File.Exists(string path)" uses path, but "FileDialog.FileName" uses fileName.
Which name do you suggest to use?
Comment: I think filePath makes it clear that you want the complete path where as FileName can be confusing as in whether you need just the name or the full path.
Answer: I, personally, would use filePath, as it's the most explicit.
That being said, whatever you choose, I would make sure that your documentation explicitly states that you require the fully qualified file name with path, if that is required by your method.
Answer: Alternatively you could consider using class to store your paths and follow unit pattern, so that you will always know what part of path your object is storing, or you can fetch from it properties like fullPath, filename, directoryPath, etc..
Somethig like this:
public class PathStorage
{
    private string path;
    private PathTypeEnum pathType;

    public PathStorage(string path, PathTypeEnum pathType)
    {
       this.path = path;
       this.pathType = pathType;
    }

    public string GetFullPath() {
    ...
    }

    public string GetFilename() {
    ...
    }
}

or even better combine that with state design pattern.
Comment: The thing is that this question is rather generic, not .net specific (although it's marked as that) and properties would make it c# specific which IMHO it is not. Enum definition is missing, because it is just solution idea, not a complete solution. Agreed on upper case for enum, my bad here. Also in real code you would like to avoid adding enum suffix to type name.
Comment: Your class is badly written. `GetFullPath` and `GetFilename` should be properties(dropping `Get` of course). Your enum definition is missing, and the enum name should be upper case.
Answer: Usually filePath is the full path to the file, e.g. C:\tmp\foo.txt, while fileName is just the name of the file plus extension, in this case foo.txt.
Answer: I would have to agree about filePath being a safer option. Should you ever reuse the class in a different library or application, it can help insure the path to the file remains steady.


How to annotate rounded, aspect-fill image in PDFView (swift PDFKit)

Question: I am working on annotate an image to an existing PDFView.
This is my current state:

And below is my desired state:

In one sentence, I want to achieve:

a rounded corder of my image annotation
image should also maintain the original aspect ratio
I have tried and searched many sources but none of them works.

Below is my current code:
class PDFImageAnnotation: PDFAnnotation {

var image: UIImage?

convenience init(_ image: UIImage?, bounds: CGRect, properties: [AnyHashable : Any]?) {
    self.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp, withProperties: properties)
    self.image = image
}

override func draw(with box: PDFDisplayBox, in context: CGContext) {
    super.draw(with: box, in: context)

    // Drawing the image within the annotation's bounds.
    guard let cgImage = image?.cgImage else { return }
    context.draw(cgImage, in: bounds)
}

}
Implementation in ViewDidLoad:
if let image = pet.picture?.getImage() {
        let imageAnnotation = PDFImageAnnotation(image, bounds: CGRect(x: 80, y: 1100, width: 300, height: 300), properties: nil)
        pdfView.currentPage?.addAnnotation(imageAnnotation)
    }

Any suggestion would be helpful because I'm at a dead end right now, thank you so much!
Answer: Ok I figured it out, it turns out I should first clip the image to rounded format then annotate that to the PDF, using this extension: https://stackoverflow.com/a/64981764/11079192


Installing Plotmtv

Question: I'd like to install plotmtv. For this reason I used simply the command
sudo apt-get install plotmtv

but I get an error message saying that the package is missing, it is not available or it is inside another source.
What can I do?
Thanks
Comment: If the answer below helped you, don't forget to click the grey **☑** at the left of its text, which means [Yes, this answer is valid](http://askubuntu.com/help/accepted-answer)!  **;-)**
Answer: plotmtv isn't in the repositories since Intrepid. But you could use a deb package. I was able to successfully install it in Vivid.

64-bit
cd;
wget https://launchpad.net/~hkroeger/+archive/ubuntu/engineeringoss/+files/plotmtv_1.4.1-R10%7E8527892_amd64.deb
sudo dpkg -i plotmtv_1.4.1-R10\~8527892_amd64.deb

32-bit
cd;
wget https://launchpad.net/~hkroeger/+archive/ubuntu/engineeringoss/+files/plotmtv_1.4.1-R10%7E8527892_i386.deb
sudo dpkg -i plotmtv_1.4.1-R10\~8527892_i386.deb

Check the installation
apt-cache policy plotmtv
plotmtv:
      Installed: 1.4.1-R10~8527892
      Candidate: 1.4.1-R10~8527892
      Version table:
     *** 1.4.1-R10~8527892 0
            100 /var/lib/dpkg/status

Installing Plotmtv


I can login using su in other accounts, but not using login screen

Question: When I try to login to my administrative account using Ubuntu's login screen, I cannot. However, I can access other accounts and log in to them. Additionally, I can login to my account using su command in one of the standard accounts by Terminal.
For instance, I've logged in to someone's account and I'm questioning from there. Now, I can open Terminal, run su machitgarha, enter the right password and login to my account. However, with that true password, there is no chance for logging in to my account using login screen.
Could someone help me please? Any ideas?
Thanks!
Answer: Problem solved! I didn't think it was as just simple as it! I changed my password from Settings app (User settings), and now I can log in to my account. However, I guess because I moved some files and directories (including .profile, .config and .cache) somewhere as a backup (e.g., .profile.back), my desktop screen returned to its default state.


what type of math is this?

Question: I am a total newbie to the world of math and was interesting in learning.  I just finished my degree(non-math) and am going to study a few math books to see if it interests me to apply for something more quantitative but I want to study something interesting with interesting problems that won't bore me.
I thought about it, and thought of the type of problems that intrest me.  One is predicting the future and the other is predicting the past.  Here's a problem that I think would be cool. Say you have a list
<code>calories 89, 34, 67, 43, 54, 232, 623
</code>
and someone tells you that someone had a total of "6553" calories in a day.  What type of math would try to figure this out? Is it algebra? (by the way to get this question all I did was take each value above and multiple first one by 1, second one by two, etc.up to 7.)
Comment: I'm not sure what you're asking. What are you trying to figure out exactly? How many calories someone is likely to have in a day given a list of how many calories they've had per day recently? That sounds to me like statistics.
Comment: Never mind - Arturo cleared it up for me, and I concur with him that this is number theory.
Answer: To cast the problem a little more clearly, you have a number of "weights", $w_1,\ldots,w_n$, in this case:
\begin{align*}
w_1 &= 89\\
w_2 &= 34\\
w_3 &= 67\\
w_4 &= 43\\
w_5 &= 54\\
w_6 &= 232\\
w_7 &= 623,
\end{align*}
and a "target total" $T$, in this case $T=6553$. You want to find nonnegative integers $a_1,\ldots,a_n$ such that
$$a_1w_1 + \cdots + a_nw_n = T.$$
In its broadest sense, this is an example of what is called a Diophantine equation (an equation in which we require the solutions to be nonnegative integers, or more generally rational numbers). They are studied in the branch of mathematics called Number theory.
Comment: @Lostsoul: Elementary number theory is both beautiful, classical, and full of interesting stuff without needing too much background. It's a great gateway to "bigger and better" things (leads to both complex analysis and to abstract algebra). Advanced techniques would require more background, but one can go pretty far regardless.
Comment: @Lostsould: Although Diophantine equations, *in general* can be pretty hard (Fermat's Last Theorem is an example of a Diophantine equation, for instance), this particular kind of problem (a "linear diophantine equation") is generally straightforward (in a practical sense). There are well-known, good algorithms for solving them (or showing no solution exists). But even a small tweak can make the problem very hard; see for example the closely related knapsack problem (http://en.wikipedia.org/wiki/Knapsack_problem) and postage stamp problem (http://en.wikipedia.org/wiki/Postage_stamp_problem)
Comment: @Lostsoul: There are problems that are very hard to solve *practically*. For example, factoring a big number is easy in principle (just try dividing all the primes up to $\sqrt{n}$ to see if it has a factor, then lather, rinse, and repeat), but for large numbers it can be so computationally expensive that you wouldn't be able to carry out to procedure before the sun burns out. Other problems admit too many possible solutions that they don't let you get much information. Not so much a limitation of number theory, but rather of what one wants to actually be able to do.
Comment: Sorry I should have marked this resolved a while ago.  I have been a bit busy and am just starting to venture into this project, I have done a little reading and I can't thank you enough for introducing me to this, Arturo.  I have a book on the knapsack problem and will eventually look at the diophantine equation.  Thank you so much Arturo(I will def be more active and bugging you all with questions as I dig into the material).
Comment: thank you so much, Arturo. I'm wondering in number theory would a question like this be solvable? is it practical or abstract theory?
Comment: Thank you so much for your quick answers Arturo.  One last question.  Do you think its feasible for someone to learn number theory directly? or should they learn something else..My math isn't amazing but I do have a computer background and worked in investment management(not crazy number crunching but I think I'm a quick learner). If there's a better way to get into number theory then what would you suggest that is?
Comment: @Lostsoul: Also, I think I misinterpreted your second question in the first comment. Number theory has turned out to have amazing practical applications that nobody even suspected as recently as 100 years ago. For example, it is a key component of internet security.
Comment: Wow thank you so much Arturo. You sold me!  It seems very valuable to reverse engineer.  Couldn't it be used to figure out what  competitors are doing if you have their production numbers. Or if a company reports they earned XX amount of money a year, this seems like it could break down how many of each of their products they sold? This is truly amazing. I wonder why I finished a computer degree and just finished a business degree and never heard of this before.
Comment: @Lostsoul: Note that even a simple problem like the one you give *could* have more than one solution. So there may only be limited amounts of information you could derive from knowing the totals.
Comment: @Arturo Thanks..are the limitions of number theory really great?  It seems so interesting and so powerful yet I wonder why it doesn't appear to wide spread.  I used to work at an investment management firm and I can see many ways this could be applied to assisting research analyst and companies make better predictions by understanding the past better.  I really hope I can apply it to real world problems, but if not it still seems so interesting to learn from.
Comment: I'm sorry i don't want to keep on bugging you on this site, but your great answers are making me think and creating other questions.  Do you think the emergence of cloud computing and more powerful cpu power solving the the big problems to make them more practical? I mean if you look at google's systems they process billions and billions amounts of data every time we search within a mili seconds..does number theory get better with a larger richer data set or does it complicate the results?
Comment: @Lostsoul: Parallelizing (using several computers working together) only goes so far. It does push the need for larger problems (RSA keeps producing bigger and bigger primes for their security systems). For most of these problems, whether one can solve them in a practical way is a question of the size of the problem; so far as we know, the difficulty grows exponentially (or sub-exponentially) with the size of the problem. Our computing capacity has no hope of keeping up. Even accepting Moore's law, we can double the size of the problem in a lot less than 2 years.
Answer: For your question you need to find positive integer solutions to  $89a +34b +67c +43d+ 54d +232d+ 623e=6553$, $\{a,...,e\}$ are the number of items you eat of each to get 6553 calories. Problems like this where you need to find integer solutions are called linear Diophantine equations. But you can treat them as puzzles and try to use some hit and trial methods/computations. Sometimes, though not always, Wolfram alpha might help.

what type of math is this?