Dual Boot / Grub 2 issues (Ubuntu/Windows)

Question: TLDR Version:
Problems with Grub2. Boots straight into Grub terminal. I get some "failure reading sector errors" (details below). I've tried running boot repair several times, with a few different options checked at this point (details below), but I can't get it to work. Dual boot situation, was able to access Windows when problem started, but now selecting Windows brings me to a Grub terminal as well.
http://paste.ubuntu.com/8298591

Full Details:
I've got some issues going on with my Grub installation. I'll detail what's going on first, and then I'll try and give the background of what's been going on.
Yesterday evening, my Ubuntu froze up on me and I had to perform a hard/manual shutdown of the computer. When I went to reboot, it wasn't allowing me to boot into my Grub screen (I believe at the time I was getting the Grub terminal, but I'm not 100% certain at this point anymore). Anyways, this isn't the first time this has happened (more on that later), so I went ahead and ran the Boot Repair tool. I had a few problems with it last time, but I figured I'd try again anyways.
First attempt, I got the notice that my PC was in Legacy mode but I disregarded it, and proceeded to run the repair anyways in default mode. No luck.
Second attempt, I got my computer out of Legacy mode, booted into Ubuntu through the EFI (on a flash drive), and ran the repair again. Default mode. It booted into the Grub menu and it looked like it would work. I selected Ubuntu, and I get a bunch of errors:
error: failure reading sector 0x74706da0 from 'hd2'.
error: failure reading sector 0x74706d00 from 'hd2'.
error: failure reading sector 0x0 from 'hd2'.
error: failure reading sector 0x74706da0 from 'hd2'.
error: failure reading sector 0x74706d00 from 'hd2'.
error: failure reading sector 0x0 from 'hd2'.
error: no such device: 4c536822-6b4d-4c08-88e3-2694bc7cd0be.

After that, it takes me to the Grub prompt where I just get the standard:
Grub>

Interesting to me, I have 2 options in the EFI/BIOS for Linux (not including the USB option), and a Windows option as well. It does not matter at all which option I take (less the USB), I always end up at the Grub terminal - even if I select Windows.
I've tried the backup and rename Windows EFI option as well (sort of blindly, primarily because it was one I could simply set back if it didn't change anything). It didn't change a thing. FWIW, at one point this evening, I was still able to boot into Windows while Linux was unavailable.
The history of this problem is that it just did a similar thing just over a week ago. I fixed it with the boot repair tool, with the default settings. However, when I did fix it, I wasn't able to boot into Linux with the EFI. I had to go through in Legacy mode, which I suspect was a problem that I created. I think I probably booted into Legacy mode and ran the repair from there, but I'm not quite certain at this point. Both times I've had these problems it came after a unplanned hard shutdown - power once & frozen OS the second time.
Here's a boot repair log that I just generated with the most recent changes represented.
http://paste.ubuntu.com/8298591/
My initial thought with all of the disk access errors would tell me that I might have a disk problem, and particularly since I had a similar issue just about a week ago. However, I'm fairly certain I've got an issue with the actual EFI on HD1 right now, due to the fact that I can't even get into Windows - and with my limited knowledge of EFIs, I don't really think that can be tied to each other... but I don't know - hopefully someone can tell me! :)
Thanks for reading and thanks in advance for any help you might be able to provide.
Kind regards.
Comment: I'm getting an error when I run Boot Repair, and I'm just cautiously playing with some settings. The most recent report is here:

http://paste2.org/UwNYFghK ----

I checked use the standard EFI file this time, and that's all I changed from default. I'll update as soon as I reboot.
Comment: The above attempt looked promising at first - Grub2 came up this time, but when I attempted to select Linux/Ubuntu it error'd out. I got a failure to read sector error again, press any key to exit, which brought me back to the screen, and so on. Ultimately, it froze again, had to hard reset, and now I'm back to where I was before the last "repair".
Comment: What is always import is information of the disk partitions, especially that of the ESP partition.
Answer: After a hard shutdown you often have to make repairs. With Windows is it chkdsk, but with Linux and ext formats it is fsck,
From liveDVD/Flash so everything is unmounted,swap off if necessary, change example shown with partition sdb1 to your partition(s)
e2fsck is used to check the ext2/ext3/ext4 family of file systems. -p trys fixes where response not required
sudo e2fsck -C0 -p -f -v /dev/sdb1

if errors: -y auto answers yes for fixes needing response, also see man e2fsck
sudo e2fsck -f -y -v /dev/sdb1

You may need to run both on sdb1, sdb3 & sdb5.
Comment: Thanks for the suggestion. I'm familiar with chkdsk, but new enough to Linux that I had no idea where to go with that.

Anyways, I went ahead and ran fsck, but it did not find any errors, so unfortunately it's not that simple. I'll play with it more this evening & if I get anywhere, I'll update with whatever I happen to find / try.
Comment: You also have an UEFI install on sda and a BIOS install on sdb. I now prefer gpt partitioning on any drive that will not ever have Windows installed in BIOS mode. Ubuntu can boot from gpt partitioned drive with BIOS or UEFI. Then you could convert later. See also this thread on mixed UEFI/BIOS boot. http://askubuntu.com/questions/522363/computer-boots-to-grub-command-line/522996?noredirect=1#comment711954_522996


Angular JS Data table - Alphanumeric sorting

Question: I'm currently using angular-datatables and I'm not able to sort the rows correctly. I have an alphanumeric field to be sorted as follows:
1
2
3
4a
4b
11
13a
13b.

But when I use datatable sorting, it sorts in the following manner:
1
11
13a
13b
2
3
4a.

I tried using the natural sort plug-in for datatables but still getting the same output. How can I sort alphanumeric values in datatables using angularjs?
Comment: From the official close reasons: _Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself_.
Answer: That is the alphanumerical order what you are getting, JavaScript sort function it's comparing the values (text) letter by letter, so 11 > 2 because the first letter were compared and the 1 is grater than the 2.
So if you want another order I think you have to write your own algorithm (function).


Is there a way to reduce or eliminate the damage taken from rocket jumps?

Question: I'm relatively new to Team Fortress 2 and currently play as Soldier, which is new to me. Normally I play Heavy, Medic or Scout. I'm playing Soldier, as I need it for a mission for the Gunmettle Campaign.
Due to this, I'm curious how to to the rocket jump right. I normally get damage using the rocket jump which makes it just possible to use it 2-3 times until the next one will kill me. Is there a way to reduce the damage of the rocket jump?
Comment: If you want to practice rocket jumping, jump maps are good.  Open the server browser and add `jump_` to the map field and you should see at least a couple jump servers.  They vary in difficulty, so it might take joining a couple to get one you can do.
Comment: Your proximity to the explosion matters to some extent. You take more damage shooting directly at your feet than if you shoot slightly behind you. The location of the explosion also changes your trajectory, so you don't always have a choice about where you shoot.
Answer: Since you're new to the game a good source of information is the official wiki.
On the Jumping page there are many good informations about Rocket Jumps:

you have a 40% resistance when rocket jumping against your rockets that don't damage any other enemy. This is important, since any enemy nearby hit by the blast makes you get full damage from the rocket
the Gunboats give you a 60% damage reduction. The "no enemies around" restriction still applies
Crouch-jumping and shot timing have a great impact on the height and length of your jumps
You can train your rocket-jumping skills with the Rocket Jumper. It completely removes the damage from the rockets, including the self-damage. Pay attention to fall damage though, since it can still kill you.

What you're seeing when you see others happily jumping around may be a combination of all the reasons above. Properly performing rocket jumps always requires skill and the self-damage has always been part of the move, not only in TF2, but in most modern shooters.
Comment: +1 - I completely forgot about the Gunboats :) (Although I still reckon the B.A.S.E Jumper is better for the soldier contract 'kills while rocket jumping' haha) :)
Comment: One additional thing you can do to take less damage is *avoid fall damage*.  The Base Jumper is ideal for this, but eliminates the Gunboats as an option to avoid self-damage, and if you then equip the rocket jumper, you only have your melee weapon as a damage option (Market Garden Time?), but you can still avoid fall damage by simply jumping to higher ground and avoiding big falls, and as long as you land the kill before your feet touch the ground, it'll still count towards your contract.
Comment: Thanks @Kappei, your answer is really helpful. The Answer of Robotnik is great too. I will let this question open for some hours and then let the community decide which one is the best one, as both answer are really great! Thanks anyway Kappei!
Answer: You can use the Rocket Jumper to practice rocket jumping without dealing self-damage, however, it also does not deal damage to enemy players at all, making it next to useless for the Soldier Gunmettle Contract Advanced/Bonus Objectives.
I wouldn't worry too much about self-damage. The Soldier has the second-highest Health (after the heavy) at 200HP, so he can take a bit of self-punishment. It also helps to know where health-packs spawn on the map, (and potentially to team up with a Quick-Fix wielding Medic)
I generally prefer other classes, however it only took about 30 mins of practice to get the hang of Rocket Jumping for me. I followed the tutorial here when practicing:

As for completing the contract, here's what I suggest:
Maps: Capture-point with open-air points, or Payload maps. The new CP_Powerhouse's middle point is great for Soldier-spam.

Primary: Liberty Launcher.
The increased clip size and blast damage makes clearing objectives/capture points from midair a lot simpler. You'll get a lot more airborne kills clearing these out, especially as the enemy takes damage from your teammates' fire as well, which makes up for the -25% damage.
Secondary: B.A.S.E. Jumper
The Advanced part of the Soldier's Contract requires rocket jump kills, and more time spent in the air = more chances at scoring the kills. Paired with the Liberty Launcher, you should have no problem scoring airtime-kills. (I'm usually more of a fan of the Buff Banner for the Team support aspect, but you can't go past the added air-time this will give you)
Tertiary: Market Gardner or Equalizer
The Market Gardener deals crits whilst Rocket Jumping, Whereas the Equaliser deals more damage, the more you are injured. The Equaliser is better all-around, but the Market Gardener is also viable.
Comment: Thanks for this really helpful answer! It helped me a lot! :-) The answer of Kappei is a bit more complete, but the video was really good too. I will let this answer open for some hours and let the community, decide which is more complete, as it is a bit hard for me to say which of your both answers is the better one. :-) Thanks anyway Robitnik!
Answer: An answer I haven't seen posted is that there are different types of rocket jumps.

Straight up: Shoot a rocket straight at your feet. This gives lots of height, and lots of fall damage if you come down.
45 degree: Shoot a rocket at an angle towards the ground behind you. This is the typical rocket jump. It gives you good distance, but probably fall damage as well. You might use this jump for jumping onto a group of enemies. You'll have less vertical movement/damage the further out you hit the rocket, so this can give similar (but worse) results to a wall jump.
Wall: Instead of shooting your rocket at the ground you shoot it at a wall. This gives you the absolute minium damage and vertical travel. It can be tricky to learn, but this is the best jump for getting around the map.

When jumping for speed, the main goal is to reduce the vertical height of the jump. This gives you more distance, and more importantly, doesn't cause you fall damage.
The gunboats and rocket jumper are nice, but it's totally possible to take only ~30 damage if you use the right type of jump for the situation.
A few other tips:

Use the increased mobility that rocket jumps give you to gather health packs as you go
Practice! An hour spent on an empty server practicing rocket jumps will really improve your ability.
Go at it with the rocket jumps when rolling out with a medic. The only class that can beat a rocket jumping soldier to mid is a sticky jumping demo.
Always crouch when rocket jumping (timing wise, I jump, crouch and fire at the same time, but that can be varied), you get less damage and more speed.
Binding crouch to a better key than ctrl can make jumping easier. I have it bound to right mouse button for solider
Answer: As far as I know, there's a weapon which eliminates the damage but it doesn't do as much damage to enemies as well. Unfortunately, with the others you damage yourself - and this cannot be eliminated.
Comment: This answer doesn't really offer much that isn't provided by the other answers.  It was quickly-posted, but seems to have little research behind it, and little advice to offer other than 'switch weapons', without any indication as to which weapons to switch to, and only a vague idea why.
Comment: But I see that others (even with the normal bazooka) run and use it quite 3-4 times to jump over the map and they are still at a fair health. Not full but not near to death. Is there a trick they are using?
Comment: I personally didn't play Soldier often but i recommend to look for some videos, trying to explain how to proper rocket jump!
Comment: @Ionic - there are many factors - as stated in another answer, that soldier could have been equipped with the Gunboats, which would take his secondary slot. It's possible he had been under the health boost of a medic, or simply spacing in a manner that would deal little damage while still offering push force.


Ubuntu 20.04 freezes after ~1 hour

Question: My Ubuntu completly freezes after about 1 hour of usage. This happens when I'm doing basic stuff on Ubuntu (editing files etc.) but also when I'm gaming. What exactly hapens is that first everything starts lagging (games lag, music lag, mouse moves choppy) and after about 10 seconds everything freezes (no music anymore, cursor doesn't move). I've to reboot my pc to get it fixed. Everytime I reboot the same freezing issue starts again after about 1 hour.
My system specs:

I7-8700K

MSI RX5700XT

MSI Z370 Gaming Plus

32GB Ram 3200MHz

I'm running Ubuntu 20.04.1 LTS. My video driver version is: 20.45-1164792 (according to dpkg -l amdgpu-pro )
I'm currently still running Windows as my main OS but planning to go to Linux in the future. I've no issues in Windows.
Thanks in advance
Edit: I'm getting constantly the error:
<code> 23.12.20 00:36 gnome-shell [3595:3595:1223/003633.411413:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglGetMscRateANGLE: glXGetMscRateOML failed.
</code>
I've currently updated the amd drivers. But that didn't solve the issue Here is a link to the journal file link
Comment: @KGIII When working normally KSystemlog is constantly spitting out this: 23.12.20 00:36 gnome-shell [3595:3595:1223/003633.411413:ERROR:gl_surface_egl.cc(773)] EGL Driver message (Error) eglGetMscRateANGLE: glXGetMscRateOML failed. But after a quick google it looks like to be a bug in the amd driver. I'll try to see if there is a newer version
Comment: Have you looked in the logs for reasons? A great GUI tool to do so is ksystemlog - `sudo apt install ksystemlog`.
Comment: `journalctl -b -1` might help after it crashed.... It will show the kernel logs of the previous boot - since i assume you had to restart after that crash
Comment: @kanehekili it opens the log but it is more than 1000 lines long, is it possible to do a tail of it?
Comment: I know nothing about AMD graphics drivers - but I'd edit your post to add that so that more people can see it and there are plenty of folks here who know more about it than I do. That's quite likely the reason you're getting the crashes.
Comment: Thank you for mentioning to edit the post. I've installed a slightly newer driver from the amd site, I don't see the error anymore in KSystemlog and hope the issue is solved with doing this. I'll try to confirm tomarrow if this solved the issue. Thank you for your help
Comment: Just use that command with `journalctl -b -1 | pastebin` and add that link to to your question. But it seems to be an AMD problem.. That is unknown terrain, since AMD did not help the Linux community for a long time. (It got better though ;-)). What does `lspci` say?
Comment: For some reason the pastebin doesn't work for me, I tried it with pastebin but gave me an error that the command pastebin wasn't found. Afterwards I installed `pastebinit` and did the command with `pastebinit` but now I'm getting the error: `Failed to contact the server: HTTP Error 502: Bad Gateway`. `03:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Navi 10 [Radeon RX 5600 OEM/5600 XT / 5700/5700 XT] (rev c1)
03:00.1 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] Navi 10 HDMI Audio` That's the output of `lspci` from my gpu
Comment: I managed to get a pastebin link. I've created 2: one fore the journal: [link](https://paste.ubuntu.com/p/Ft3kdTCxtx/) and one for `lspci`: [link](https://paste.ubuntu.com/p/GWh9bf8Jjh/)
Comment: I just tested it and it freezed again after ~1 hour. I had Ksystemlog open and it showed something that my input was running behind and something that pulseaudio was overrunning or so, both where warnings. These warnings showed up when the freezes was alread ongoing
Answer: After comming accidently up in the system monitor, I saw that there was a background program using about 16gb of memory, and keeps using more over time. This program is for my sound controller, I closed it and now and it didn't crash anymore. Thanks @Kanehkili and @KGIII for helping.

Ubuntu 20.04 freezes after ~1 hour


How can I disable one switch in a three-way circuit?

Question: I replaced a ceiling fan with a regular light a while back that originally had 2 switches that worked it. When I was done only one switch worked. I was okay with this because I didn't use the other switch anyway. Well yesterday I removed the switch (the non used one) to put a blank plate on the wall. (To get rid of the switched that were of no use). So I capped off all wires from the switch, but now I can't use the original switch I'd been using. (It makes sense that I cause disruption in the way things connected it just didn't occur to me that it would happen). What can I do to make connection behind this plate without putting a switch back in, if anything?
The red and the black at the bottom are the hot, nothing on the others. There are three sets of wires, any help would be appreciative. They can be labeled as A B and C.
I replaced a ceiling fan with a regular light a while back that originally had 2 switches that worked it. When I was done only one switch worked, I was okay with this because I didn't use the other switch anyway. Well yesterday I removed the switch (the non used one) to put a blank plate on the wall. (To get rid of the switched that were of no use). So I capped off all wires from the switch, but now I can't use the original switch I'd been using. (It makes sense that I cause disruption in the way things connected it just didn't occur to me that it would happen). What can I do to make connection behind this plate without putting a switch back in, if anything?
The red and the black at the bottom are the hot, nothing on the others. There are three sets of wires, any help would be appreciative. They can be labeled as A B and C.
Comment: Can you post photos of the wiring involved?
Comment: This is not a general question.  This is particular to the wiring of that circuit.  With good photos or a wiring diagram an absolute answer is possible.  Without it, no answer is possible other than, "Undo whatever you did that broke the circuit."
Comment: Hello, and welcome to Home Improvement. You should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: @feetwet My answer may or may not be complete/best, but there are definitely answers possible here. Would it be better if the switch removal could simply be "undone"? Yes. But that might actually be harder than simply figuring out the remaining wires and the other switch.
Answer: To know for sure, we need to see pictures of the wiring and switches. But I'll make an educated guess:
Common (Shared) Hot
The two switches shared a common hot wire. One hot in, two switched hots out. There are three ways to connect one hot to two switches:

Two switches built together with a common hot
This is the easy way - essentially two switches in the space of one. I know you didn't have this, because if you did then there would be no way to remove one switch without removing the other switch. But listing it for completeness.

Pigtail Hots
This is the preferred method because it avoids the problem you found. The hot wire comes in to the box and is connected to two short wires, pigtails. Each pigtail connects to one of the switches.

Daisy Chain Hots
Hot wire comes in and connects to switch # 1. Another wire connects from switch # 1 to switch # 2. The two connections on switch # 1 could be two wires under one screw (not usually recommended, but often done anyway) or one wire under a screw and one wire in a backstab connection. If you disconnect all wires from switch # 1, then there is no longer any hot wire for switch # 2.

You need to look at the wires going to the remaining switch. You should have one wire going out of the box to the light and one wire going out of the box back towards the circuit breaker. What I suspect you will find is that one of the wires actually has the other end loose, but capped, in the box. That is your formerly-hot wire. The hard part is figuring out which wire from the removed switch is the hot wire. The easiest way to figure this out is a non-contact voltage tester:

With the breaker on, use the tester to identify the hot wire. Turn the breaker off and then connect that wire to the switch instead of the loose/capped wire.
Comment: You are right, I just can't believe I brought this on myself by my own stupidity! I think my son-in-law has a friend that is an electrician so I might get a "friends & family" discount...... (fingers crossed)
Comment: I will need to get the voltage tester tool. In the meantime, I am just wanting to make the connection without having switches. I wanted to put a plain face plate over the wiring. I don't need to have switches because they didn't work anyway, but they must have made some sort of electrical connection.
Comment: Most likely the original configuration was to have one switch for the fan itself and one switch for an attached light. Many fans don't have lights, and many newer fans that have lights control everything with a remote control so that the switch (just one switch) turns power to everything on/off but isn't even needed since you can do everything with the remote.
Comment: Is there a way to make the wires connect for the power without using a switch. Where I can just have it capped off or something behind the solid switch plate?
Comment: Yes. If you figure out which wires *should* be on the switch and then just wire nut them together, you can then take out the switch. But then the light will be always on. Is that what you want?
Comment: I am just now getting back to my issue, back to school is always a crazy time. Anyway, I do not want my light to stay on. I took a picture, but it makes no sense to me.... how do I get the picture up here?
Comment: @Diana Click "Edit" below the question and one of the icons above the text box should be a box with "mountains" for uploading pictures. If you can't get that to work, just upload the picture to imgur.com and put the link in the question and someone will turn it into an embedded picture.
Comment: thank you. I added the photo. And unfortunately of course I do not know what wiring I took what switches off. I'm an idiot, I know :-)  I know better, I should always pay attention to how I take things apart. But I didn't think it would cause the disruption. I have tried multiple things with new switches I bought just to see if I could get my kitchen light come on again.  Any help you can provide is appreciated.
Comment: "that originally had 2 switches that worked it" do you mean two switches right next to each other with one switch operating the fan and the other switch operating the light. Or do you mean one switch on one wall and the other switch on another wall.
Comment: One switch on one wall and the other switch on the other wall.
Comment: It seems like I'm going to have to call an electrician, I just can't afford one. I tried to do the more simple jobs myself, but this turned out to be a "not"  simple job.  Only because of my stupidity in the beginning.
Comment: I certainly understand "can't afford one". But there are times when that is really the only option - I do a lot of my own electrical but sometimes it is too much for me to attempt myself. Same with water. And **always** when it comes to gas. Everyone has to know their limits.


A counterexample to the epsilon-delta criterion for Absolute Continuity of Measures

Question: Let $p>0$, and let $\mu$ be a Borel measure on $[0,\infty)$ defined by $\mu(E)=\int_Ex^pd\lambda$ where $\lambda$ denotes Lebesgue measure.  Show that $\mu$ is absolutely continuous with respect to $\lambda$, but $\mu$ does not meet the epsilon-delta criterion for absolute continuity, namely for every $\epsilon>0$ there's a $\delta>0$ such that $\mu(E)<\epsilon$ whenever $\lambda(E)<\delta$.
I've managed to prove that $\mu$ is absolutely continuous with respect to $\lambda$, but I'm not sure how to approach the second part.  I basically need to find a sequence of sets $E_n$ (in $B([1,\infty)$) such that $\lambda(E_n)\rightarrow 0$ but $\int_{E_n}x^pd\lambda$ does not go to zero.  But I can't even think of such a sequence in the case where $p=1$, let alone the general case.
Comment: The nastiness is occurring because the interval is unbounded.
Answer: Hopefully the case $p=1$ will help:
$$\lambda([a,b])= b-a$$
and
$$
\mu([a,b]) = \frac{1}{2}(b^2-a^2) = \frac{1}{2}(b-a)(b+a)
$$
Taking, for example, $a=3^n$ and $b=3^n+\frac{1}{2^n}$ will give you sets $E_n$ which you can show the desired properties of.
Comment: Thanks, the $p=1$ is clear.  But how do you generalize it, given that you can't factor in the general case?
Comment: Are you sure? E.g. $5^3 -4^3 = y^2-x^2$ for certain $y,x$. I haven't fully worked it out but it might work just as well, although you'd have to think of a different inequality.
Comment: I'm thinking of the case when $p$ is not an integer.
Comment: It doesn't have to be. Think about how to write $x^p$ as a square.no integer assumption needed.
Answer: The issue is more or less that $x^{p+1}$ is not a uniformly continuous function: it grows faster and faster as $x \to \infty$, which means that $\mu(I)$ can be large even when $\lambda(I)$ is small if $I$ is located far to the right.
Being more precise, consider $\delta>0$ arbitrary and then try computing $\mu([\delta^{-1/p},\delta^{-1/p}+\delta])$.


html textarea how to apply styles on content within the textarea

Question: I know that this topic has been discussed since I can see traces on the web. The consense seems to be that it is impossible. But I know on at least one product (TinyMCE) which manages to do it. Note: I do not want to use TinyMCE to do it.
I want to add some icons to the text content of the textarea element. It would be great if one could click on the icons as well.
Maybe somebody here already looked into TinyMCE and knows how they do it. Is this done using Javascript? Or is this some browser specific browser mechanism like spell check?
Answer: From my understanding libraries like this use a contentEditable div.  This allows for textarea-like editing as well as html elements.
Answer: TinyMCE hides the textarea and replaces it in the document with an iframe whose content is editable (using either the designMode property of the iframe's document or the contentEditable property of the iframe's  element). I believe the textarea is still kept in the document and its value updated as the user edits content in the editable iframe so that the HTML produced by TinyMCE is submitted as though it had been entered into the textarea.


Creating a clustered index on this heap?

Question: So I am curious to know if it is worth creating a clustered index on a heap table that has about 30M rows of data. Before now, it wasn't going to be used in any application that we have but now we are creating an app to query that table.
The reason why I ask if it is worth it is because the application we are creating is basically doing this type of query.
SELECT *
FROM [table];

I am leaving the * in to represent that we are basically pulling all fields.
So my question is, is it worth creating a clustered index on a table that does not have one even though we are going to be selecting all fields and rows for our application?
Thanks for any info/advice.
Comment: Hang on... you're always going to ask for all 30M rows, every time..?
Comment: You're saying SQL (= query language), but I assume that you really mean **SQL Server** - right? Please use the `sql-server` tag to make this clear! And please also specify the **version** (2005, 2008, 2012) you're using!
Comment: Selecting 30 million rows from a heap table for application use is possibly the worst thing that you can be doing. There is a lot of considerations for how to handle that much data. This question would be best suited for [dba.se]
Comment: I wouldn't want an app to retrieve all 30 mio rows to the client. What are you doing with the data, display it to the user?
Answer: No it is not worth it. If you are going to run a select without a where clause, a clustered index will just add more data to the Page files, depending on what you choose for your index(It all really depends on your data). Creating a larger scan of the table.  A Heap table is the actual better performance wise in many situations(if you are just getting all rows from a table and not using joins/wheres/filter clauses of some sort), because it is stored in less page files.
Having a clustered index, when it isnt used will also bear some overhead in updating/creating stats on a table and doing inserts (page splits)
So if you arent going to use the index, and aren't going to filter on your table you are better off without the index


While installing Ubuntu on a Mac, should I install it under EFI or BIOS?

Question: While installing Ubuntu on a Mac, should I install it under EFI or BIOS?
I'm using rEFInd, trying to install Ubuntu 15.10
Comment: UEFI: older version, but instructions should help. Do not use refit, but use rEFInd. http://askubuntu.com/questions/580202/refit-refind-grub2-what-is-the-right-way-for-ubuntu-14-10-on-a-mac
Comment: Possible duplicate of [Install Ubuntu on Intel Mac](http://askubuntu.com/questions/16604/install-ubuntu-on-intel-mac)
Comment: Dual- or single-boot?
Comment: Dual-boot with OS X El Captain.
Comment: Things have changed ***A LOT*** since 2010, the date of the question that's being referred to as a duplicate. Referring to that question and its equally-outdated answer is doing a disservice to Alex (and anybody else who might read this question).
Comment: To clarify: The question to which oldfred refers is from 2015 and contains still-relevant information in its answers. The one to which David Foerster refers is from 2010 and is outdated.
Answer: Most of the installation process is identical for EFI-mode versus BIOS-mode installations. They differ in three ways:

When booting the installer in BIOS mode, you can boot either 32- or 64-bit versions of Ubuntu, at least if you've got a 64-bit CPU. In EFI mode, you can install only 64-bit versions of Ubuntu, and that only if you've got a 64-bit EFI (which most Macs do). If you have a rare Mac with a 32-bit EFI, things get complicated.
If you install in EFI mode, the installer will set your EFI System Partition (ESP) to be mounted automatically at /boot/efi. If you install in BIOS mode, this won't happen. This detail can be changed manually after installation.
The installer will install a boot loader to match its own boot mode. (An exception is if you launch into "try before installing" mode, open a Terminal, and type synaptic -b. In this case, no boot loader will be installed.)

IMO, installing a 32-bit OS on a 64-bit CPU seldom makes sense these days. One notable exception is some fairly early Intel-based Macs, which have 32-bit EFIs. Thus, the first point is unimportant for most users. As noted earlier, an exception is if you've got one of the rare Macs with a 32-bit EFI (from roughly the first year of Intel-based Mac production).
The second point is easy to change, and so doesn't bear much consideration, provided you understand how to edit /etc/fstab. If you don't understand this topic, see this page.
The boot loader issue is the big one. To launch a BIOS-mode boot loader, Macs require that your disk use an MBR partition table or a GPT with a hybrid MBR. OS X is normally installed to GPT, which means that if you're dual-booting, you'll need a hybrid MBR to dual-boot with a BIOS-mode boot loader. Please read the link earlier in this paragraph. It describes hybrid MBRs in more detail, including why they're so DANGEROUS. For this reason alone, I strongly advise against using a BIOS-mode install of Ubuntu if you're dual-booting with OS X.
If Ubuntu is to be the only OS on the computer, though, you can use a straight-up MBR (with no GPT) and install in BIOS mode. This is likely to work better than an EFI-mode installation, but it will limit your options if you subsequently decide you want to dual-boot after all. It will also make it harder to update the computer's firmware, should that ever be necessary.
Getting back to dual-booting, if you install Ubuntu directly in EFI mode, it will try to install an EFI-mode version of GRUB. This may work fine, and may enable you to dual-boot with OS X by using GRUB's boot menu. This configuration will bypass rEFInd (unless you re-install it). I've seen reports of this configuration not working, though; the system will boot straight to either OS X or Ubuntu, making it difficult to boot the other OS.
If you want to keep using rEFInd, the safest approach is:

Launch the Ubuntu installer in its "try before installing" mode. It doesn't matter if you do this in BIOS mode or in EFI mode, except for the comment about whether your ESP will be mounted automatically when you're done.
Open a Terminal window.
Type ubiquity -b. This will launch the Ubuntu installer. The -b option tells it to not install GRUB.
Install Ubuntu regularly. Be sure to use ext4fs, not another filesystem. (If you really want to use another filesystem, you can, but that complicates matters slightly. Post back with details if you need further advice on this point.)
When you're done, reboot. rEFInd should appear (if it's already installed) or the computer will boot straight to OS X (if rEFInd is not already installed).
In OS X, (re-)install rEFInd. This step exists solely to ensure that the EFI filesystem driver for ext4fs is installed. You could instead install that driver manually yourself. (You could also manually install another EFI filesystem driver, if that was necessary.)

The result of this procedure is that, when you reboot, rEFInd should come up and give you the option of booting either OS X or Ubuntu. One caveat is that the Ubuntu option will require some tweaking if you use a separate /boot partition. You can boot on a one-time basis by hitting F2 or Insert twice, rather than Enter, once the Ubuntu option is selected. You can then add ro root=/dev/whatever, where /dev/whatever identifies your root (/) filesystem. Once you've booted Ubuntu, run the mkrlconf script that comes with rEFInd. This will generate a file called /boot/refind_linux.conf, which will obviate the need to make these changes.
Comment: My mac did have a 64 bit EFI, as its
Comment: recent, but I have a old mac that is 32bit efi.


Ubuntu 14.04 LTS wired internet extremely slow

Question: My wired internet is running extremely slow after installing Ubuntu 14.04 on my desktop. my normal internet speed (Windows) using speedtest.net is around 25 mbps, Ubuntu is pulling in 0.5 mbps tops.
I've found lots of issues with the 'Realtek RTL8111 Ethernet Interface' I've got, they all say to change the drivers to r8168 (which I've done) or change the IPv6 to ignore (also done) but my internet is still running extremely slow. I've tried everything I've been able to find online and rebooted multiple times along the way but all to no avail. I don't have much experience with Linux, but am eager to learn.
What do I need to do to fix this problem?
Comment: I would probably try getting a live ISO from a different Linux distribution and testing it to see if it's either an Ubuntu-specific issue or a Linux-specific issue. For example, you could try out Sabayon and see if it has the same problem while in the live environment.
Comment: I have used the Gigabyte GA-990FXA-UD3 motherboard which has a Realtek 8111E NIC. There were just way too many problems with the ethernet and the solution I ended up going with was a PCI LAN port.
Comment: possible duplicate of [Slow wired internet connection on Realtek RTL8168-8111 (Rev 6)](http://askubuntu.com/questions/71252/slow-wired-internet-connection-on-realtek-rtl8168-8111-rev-6)
Comment: another page you don't even have to scroll down to know there's no accepted (==working) answer :) [whoever messed up 14.04 network testing -- freak you hard]
Answer:
Disconnect from Internet
Open your Terminal and execute the line:
sudo tee /proc/sys/net/ipv6/conf/all/disable_ipv6 <<<"1"

Connect to the Internet again, and see if the problem still exists.
Comment: @Arin the above command was simply writing a 1 to the file, you can reset it to a 0 by using this command: `sudo tee /proc/sys/net/ipv6/conf/all/disable_ipv6 <<<"0"`
Comment: How do we reverse this?
Answer: Fix the bug in Debian Avahi-daemon
The slow WiFi in Ubuntu problem could also be related to a bug in Avahi-daemon of Debian. Ubuntu and many other Linux distribution are based on Ubuntu so this bug propagates to several Linux distributions. To fix this bug, you have to edit the nsswitch configuration file. Open a terminal and use the following command:
sudo gedit /etc/nsswitch.conf

This will open the configuration file in gedit so that you could edit it easily in GUI. In here, look for the following line:
hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4

If you find this file, replace it with the following line:
hosts: files dns

Save it, close it, restart your computer. It should fix the slow wireless connection problem for you. If it doesn't check the other solution.
Works for me. Hope same does for you :) If it dosen't , try other solutions , from here http://itsfoss.com/speed-up-slow-wifi-connection-ubuntu/


MFMessageComposeViewController setting the UINavigationItem titleView

Question: I'm having a problem overriding the title view of MFMessageComposeViewController's navigation item. Here is the code:
MFMessageComposeViewController *messageViewController = [[MFMessageComposeViewController alloc] init];
messageViewController.body=@"SMS Body";
CGRect frame = CGRectMake(0, 0, 100.0, 45.0);
UILabel *label = [[UILabel alloc] initWithFrame:frame];
label.text=@"Title";
messageViewController.navigationItem.titleView=label;
[label release];
[self.navigationController presentModalViewController:messageViewController animated:YES];
[messageViewController release];

I have also tried:
    messageViewController.navigationController.navigationItem.titleView=label;
I should also point out that this is for iOS 4, in iOS 5 I use the new setTitleTextAttributes method which works great.
Thoughts?
Comment: Thanks @rickharrison that worked, as long as I do it after presentModalViewcontroller:
Answer: I believe this semi-hack should produce the desired effect. Since we know that MFMessageComposeViewController is a subclass of UINavigationController, the view that you are actually seeing must be managed by a private controller class. You should be able to modify that controllers navigation item in order to achieve what you want.
messageViewController.topViewController.navigationItem.titleView = label;

In my testing, this only worked with the titleView. If you just try to set the title, it will work for a couple seconds, but then gets overriden back to the title of the email. As with any other sort of UIKit hacks, this could stop working at any time, and it may only work on particular OS versions.


Static vs non-static prepared statment in SQLite C API

Question: I am working on a terminal app in C and SQL for tagging files. The file/tag relationships are saved in an SQLite 3 database. Up until now I've been using statically allocated prepared statements, which are reset and bound on every call to the wrapper functions. Recently I was testing for memory leaks etc with valgrind, and it was complaining a lot because obviously the static sqlite3_stmt in the wrappers are not freed upon program termination. This also causes the database to not be closed properly (because of non-finalized statements).
The original reason for doing this is performance. I read in the C interface intro that reusing prepared statements is very good for performance.

Using sqlite3_reset() on an existing prepared statement rather than creating a new prepared statement avoids unnecessary calls to sqlite3_prepare(). In many SQL statements, the time needed to run sqlite3_prepare() equals or exceeds the time needed by sqlite3_step(). So avoiding calls to sqlite3_prepare() can result in a significant performance improvement.

Here's some code to show what I'm doing:
int tag_file(const char *file, const char *tag)
{
    static sqlite3_stmt *sql_prep = NULL;
    static const char *sql_str = "INSERT OR IGNORE INTO Tag VALUES (?, ?);";

    // Prepare if null, else reset
    prepare_or_reset(&sql_prep, sql_str);

    if (sqlite3_bind_text(sql_prep, 1, file, -1, SQLITE_STATIC) != SQLITE_OK ||
        sqlite3_bind_text(sql_prep, 2, tag, -1, SQLITE_STATIC) != SQLITE_OK)
        return ERROR;

    if (sqlite3_step(sql_prep) != SQLITE_DONE)
        return ERROR;

    return SUCCESS;
}

What I tried, which will satisfy valgrind, but completely misses the performance gain of reusing the prepared statement is to make sql_prep non-static and calling sqlite3_finalize(sql_prep) at the end of the function, but I guess this is worse performance wise. Can I prepare the statement just once without a memory leak in an elegant way?
Another thing I started worrying about was memory consumption. In the future I am planning to create a GUI for this app, which would keep all this in memory much longer. The performance gain could potentially be bigger, but that statement would just be sitting there on the heap from the first call to exit. Is this a fair space-time tradoff?
Edit: Would it be ugly/weird to keep all "static" prepared statements in a global array, which I can free atexit?.
Answer:
You must finalize all statements before closing the database.
This is not possible if the statements are not known outside of functions such as tag_file.
You should have a global list of statements, and let the prepare_or_reset function add the statement to that list dynamically.
Prepared statements are tiny; there is no comparison to all the stuff allocated by GUI libraries. It is very likely that you will not even notice their memory usage.
However, prepared statements do not give much of a speed improvement if you do not execute them so often that the preparing time is noticeable. So it probably does not matter either way. ☺
Answer: You are mentioning two issues.

The first one is essentially how to manage your prepared statement.
Here it seem appropriate to re-design your int tag_file(const char *file, const char *tag) function a little bit.
Either you maintain the stmt one level higher and pass it to the function each time. Then you can clean up at the very end of the program.
Another way could be to define your function's semantics in a way that you give it special sentinel functions (maybe just (NULL, NULL)) which make the function free the statement.
The second issue is the question of heap size. As long as you don't have hundreds or thousands of prepared stmts, I think you can have it all the time as it will probably only cost about some few bytes.


Unable to install package "dplyr" in R (Stuck while compiling)

Question: I ran into the issue of R being stuck while installing packages.
<code>-DBOOST_NO_INT64_T -DBOOST_NO_INTEGRAL_INT64_T -DBOOST_NO_LONG_LONG -fpic  -g -O2 -fstack-protector >--param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -g  -c distinct.cpp -o distinct.o

g++ -I/usr/share/R/include -DNDEBUG -I../inst/include -DCOMPILING_DPLYR  -I"/usr/lib/R/site-library/Rcpp/include" -I"/usr/lib/R/site-library/BH/include"  -DBOOST_NO_INT64_T -DBOOST_NO_INTEGRAL_INT64_T -DBOOST_NO_LONG_LONG -fpic  -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security >-D_FORTIFY_SOURCE=2 -g  -c dplyr.cpp -o dplyr.o

^C/usr/lib/R/etc/Makeconf:141: recipe for target 'dplyr.o' failed
make: *** [dplyr.o] Interrupt
ERROR: compilation failed for package 'dplyr'
* removing '/usr/lib/R/site-library/dplyr'

The downloaded source packages are in

'/tmp/Rtmp72KGCW/downloaded_packages'

Warning message:

In install.packages("dplyr") :

  installation of package 'dplyr' had non-zero exit status
</code>
How can I install packages with/for R?
Ubuntu 16.04 LTS on a cloud server
Comment: *"stuck"* - it looks like you are Ctrl-C'ing out of the process? just be patient, the final build step appears to take a LOOONG time (not sure why)
Comment: @steeldriver I tried the same steps on two different VPSs I set up recently and looks like the other one went through the compiling no problem. Will give it another shot...
Answer: If you're using an AWS t2.micro instance, the problem is that it doesn't have enough memory. You can upgrade the instance type under actions in the EC2 Management Console.
Comment: Thanks, had the same problem and upgrading the instance helped.


How to sum a value of rows when searching for specific text

Question: Please see the screenshot, but it's like this:
<code>Column A    Column B
User 1      20
User 2      30
User 3      20
User 4      10
User 1      40
User 3      40
User 1      10
User 4      20
User 2      30
User 1      20
User 4      50
User 4      20
User 2      10
</code>
This is a simple list, and the actual list is spread across 27 worksheets. But I would like the equation to be on each worksheet.
How do I search Column A for a value of "1" and SUM up the values for Column B. SO I should have a result of 90 for User 1, 70 for User 2, 60 for User 3 and 100 for User 4.
Any help would be appreciated....
Comment: look into [sumif](http://office.microsoft.com/en-us/excel-help/sumif-HP005209292.aspx)
Comment: But will this allow me to search with an "*" in the field? SO I can look for "1".  i tried this earlier, and it just wouldn't work for me :-(
Comment: `=SUMIF(A:A,"*1*",B:B)`
Comment: That did the trick, I was adding in a load of other characters like ' and =, so darn simple! Thanks again.
Answer: This would be for cell C2 (just drag downwards):
<code>=SUMIF(A:A,A2,B:B)
</code>
MS Office Help
edit: Had a little mistake there, sorry. Now it should work.
Comment: THanks for that. Had a response from Simco as well. Just got it working, thank you!


How to assign sample_weights in sklearn.cluster DBSCAN?

Question: I'm using DBSCAN to find clusters of pixel values of an RGB image.
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
where, X is an N x 3 matrix. Each row of X contains RGB triplets.
Now, I want to assign weights to pixel values as a function of distance from the center of the image.
And this is the function I'm using:
score =  1 / (1 + math.exp(-a * distance)) # a = 0.001
I compute weight_matrix filled with score as above
Next I did this:
db = DBSCAN(eps=0.3, min_samples=10).fit(X,y=None, sample_weight=weight_matrix)
where, length of the weight_matrix array is equal to the number of rows in X.
But I get the following error:
TypeError: fit() got an unexpected keyword argument 'y'
So I tried doing it like this:
db = DBSCAN(eps=0.3, min_samples=10).fit(X, sample_weight=weight_matrix)
Now I get this error:
TypeError: fit() got an unexpected keyword argument 'sample_weight'
I think I'm passing the arguments incorrectly, but couldn't be sure. My scikit-learn version is 0.14.0.
Comment: Taking a look here: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html#sklearn.cluster.DBSCAN it seems fine. One thing I wonder is what `weight_matrix` is for you. You say that it should have the same number of `rows` as `X`, but it `weight_matrix` should be an array of `length` equal to the number of rows in `X`. Also check the version that you have, it may not be the latest.
Comment: Maybe you have an old version installed?
Comment: @ZWiki: Thanks for theinfo on size of ``weight_matrix`` array. I've edited the post.
Answer: It seems that you are using scikit-learn v <= 0.15, as this is the last version where DBSCAN had fit of form
fit(X)

since 0.16 it is
fit(X, y=None, sample_weight=None)

Simply update your scikit-learn to 0.16 or 0.17.X
Comment: Then ask a separate question showing what exactly is happening, what do you mean by crushes
Comment: When the DBSCAN().fit() method is called. It says "Killed" and exits.


Is it any use combining Sorcerer's Shoes and void staff?

Question: While doing my different builds for my AP heroes, I've noticed existing builds on the net sometimes (often) combine Sorcerer's Shoes and void staff, and I don't really understand why.
When calculating enemy's effective magic resist, magic resist reduction and penetration is calculated in the following order :

Percentage magic resist reduction
Flat magic resist reduction
Flat magic penetration
Percentage magic penetration

Meaning that if you buy both item, Sorcerer's Shoes only give you 12 penetration if you have void staff. It even goes down to (a little more then) ten if you took the Archaic Knowledge mastery.
Another thing reducing usefulness of void staff is if the Archaic Knowledge mastery. Percentage magic penetration doesn't cumulate, both penetration are calculated one after another: meaning 40% (Void Staff) + 15% (Archaic Knowledge) penetration only gives a total 49% (and not 55%)
So question comes, is it still a useful purchase ? Problem is there aren't many items that reduce or penetrate magic resistance (Abyssal Scepter, Malady, Haunting Guise, Sorcerer's Shoes and Void Staff).
Several options come up :

Purchase both items (and more if needed)
Concentrate on flat penetration and magic resistance reduction
Don't take flat penetration (too concentrate on CD reduction or more AP) and buy void staff
Try to compensate with runes the lack of penetration I may have if I don't take void staff
Ask for teammates to take hero with spells that reduce magic resistance
Anything else

I usually abandon void staff and work with Abyssal Scepter + Sorcerer's Shoes, but I'm starting to feel it may not be the best option.
Answer: For the most part I consider Void Staff to be an item worth considering only if my main targets (AP/AD carries, maybe even the support in rare cases) are stacking magic resist. Generally speaking you should just get Sorceres Shoes and then focus on building AP or other things... HOWEVER:
Some heroes are very much dependent on spell penetration - you can spot these generally from horrible scalings but high base damage. Brand comes to mind - when I play Brand I always rush Sorceres Shoes and Abyssal Scepter. From here on it depends a bit, but I generally always aim for Deathfire Grasp (mana regen, cooldown reduction + more damage) and then get a Void Staff. Brand is simply so dependent on penetrating through magic resist (his passive scales with spell penetration, but not AP) that you have to prioritize that over building tons of AP - especially when you consider that his scalings aren't that great.
I would say for most AP carries you will want the void staff if you're playing against a proper team as their AD/AP carries will get some magic resist at some point if you're doing your job right. However it should not be your immediate item to go for - especially as it is worth more the higher magic resist your opponents have (and they shouldn't have that much early on).
Comment: Thing is, usually, as an AP hero, I aim for the carries. AP carries don't have much more than `Banshee's Veil` usually, giving them 50 MR. With just Shoes + scepter, they go -40 MR, which is way enough. So combining with again a `void staff` will help you take down the 150 MR tank, but won't make much of a difference for the rest will it ? I fell like if I plan to take take void staff, I should take other boots (like `Ionian Boots of Lucidity` for CD reduction). What do you think ?
Comment: I think the answer depends on what you need to do functionally. If you build consists of Sorcerer's shoes and Abyssal Scepter early you certainly don't then need to rush to a Void Staff. Since the staff is % penetration it makes more sense to get it later if you are having trouble taking down enemies. That being said if you are having trouble taking them down why would you sell the Sorcerer's Shoes? I would agree with kastermester generally and consider void staff a "final build" item unless you are having a phenominal game and dont need to build other items for survival.
Comment: @Dalshim - first off remember that there is not one single way to build a single champion. You need to look at every game on its own, see which champions and which builds your opponents build and all that. With that said - AP/AD carries on the other team should get way more than 50MR. The veil itself is about that if I recall correct - but don't forget that there's base MR, maybe buffs/auras from the support - and possibly they run MR glyphs as well. Also while you want to focus carries it's not always possible. The other team might have an Irelia focusing you or etc.
Comment: In general - look at what is going on in the game and run with your builds from there. Most champions and builds depend heavily on one or two core items which you need and from that point on you need to analyze what is happening and progress your build from there.


Team Foundation Server 2018 User is missing contact information of Exchange

Question: We are trying to setup a TFS 2018 Update3.2 as ticketing system based on CMMI. I tried several things and begin to understand how everything works, except one very important thing.
We want to use the notifications and the emails are send correctly to 2 of 4 users. 1 user has no email, so that's ok, but me (my own account), don't gets any emails. I tried to set my email address by hand in the field: My Profile -> Preferred email. But that doesn't work either.
When I open a group with all users and click on them, I get to see the initials of my name and my full name. When I click on one of the working accounts, there are also contact informations (an email address and the possibility to start a sip chat.
So I looked into our Exchange (seems to make sense), but I don't have found any differences between my settings and those of the working accounts. I am also searching here now for more than an hour, so I don't think that the service still has to update.
Anyone an idea where I could look? How do I get my email address from the AD to the TFS? Or maybe how can I force a synchronization? Or delete all cache items and reload everything by it?
EDIT:
I killed the cache directory (the GUID-directory inside) and then everything got relaoded and now I get emails too.
Comment: Does your AD profile have an email address in it?
Comment: Yes, it does. I added the solution in an edit.
Answer: If you clear the cache, the problem is solved.


Get absolute coordinates for rotation of Inkscape SVG elements

Question: I am using wxPython to prototype some display interfaces for a project that will eventually become an embedded design.  Since we are iterating with a graphics designer, it is much easier to let them work in a WYSIWYG editor like Inkscape than constantly rewrite 2D graphics drawing calls.  For elements that need animation or dynamic text, the SVG elements are easily identifiable by ID so that they can be programatically updated before rendering.  The rendering flow looks like this:
Inkscape SVG as XML --> Python modification of XML --> Drawing onto wxPython buffered canvas using Cairo and pyRSVG

I'd like to animate a pivoting needle around a fixed axis for a gauge.  To define a needle, the graphics designer draws the graphical "needle" and a "needle_axis" element which is a small circle.  Then, I thought I could set the transform property using the desired angle and the center coordinates of the "needle_axis."  However, since the relative positions could have been affected because of other transforms, determining the absolute location of the rotation axis is non-trivial.
I cannot seem to find a Python library for determining absolute coordinates of an element, and it feels like reinventing the wheel to try an implement the part of the SVG spec. necessary to calculate it.  The rsvg API mentions rsvg_handle_get_dimensions_sub and arsvg_handle_get_position_sub functions to get the dimensions and positions of elements, but I can't find an API for pyRSVG.
Is there a better way to find the rotation axis than manually calculating it?  An example Inkscape SVG file and test snippet are available as a gist.
Comment: Trying to do something similar, found a Python Extension library function `simpletransform.py` - but it's in the Deprecated folder of my installed InkScape, and couldn't be imported (without a lot of work).
Answer: If I understood correctly, you have the needle's coordinates and the rotation axis coordinates, and you want to programatically change the needle's "angle" and then change the needle's shape in the SVG file accordingly?
I think this is a really bad idea: making changes to the SVG, saving and then rendering the "new SVG" will take too much ressources and is exactly why such a simple task seems complicated.
Instead, parse your SVG once (using lxml for instance, it's a piece of cake to extract coordinates just by doing some XPATH queries) and build your shapes into a model (a Needle class for instance, with the paths and center) and then simply rotate that needle using Cairo transforms. They already provide a rotate function that will do what you're looking for!
Comment: Could you provide more detail on how to extract the coordinates?  I actually started doing something along those lines but realized I'd have to re-implement all of the SVG specification with regards to transformations and absolute/relative coordinates.  I'm actually getting "good enough" framerates by just modifying the SVG XML between frames.  This avoids this file I/O which helps but still seems dirty since it involves pyRSVG reparsing the entire tree every frame.
Comment: It is true that you could have some issues if your SVG software doesn't "apply" transformations on the coordinates and leaves them as SVG transformations intead. But I think that you can force the opposite behavior on Inkscape. Then you'll "just" have to build a Cairo path (http://www.cairographics.org/manual/cairo-Paths.html) from the SVG path. Not **that** hard but you'll still have to read the SVG specs about paths: http://www.w3schools.com/svg/svg_path.asp
Comment: You can force Inkscape to export without using relative coordinates, but I have not found an option to prevent using transforms under all situations.  I agree that it would be better to get the SVG data into Cairo paths or some object responsible for generating the Cairo paths, but will leave the question open since I don't think there should have to be "roll-your-own" translation code for everybody who needs this functionality.


Can't find my bug: Group flat data in Advanced Datagrid wont work

Question: I've got an ArrayCollection which is properly displayed in this Advanced Datagrid:
<code> <mx:AdvancedDataGrid id="drawingDataDG"
 editable="true" sortableColumns="true"
 headerWordWrap="true"
 sortExpertMode="true"
 rowCount="8" y="10" right="10" left="10"
  dataProvider="{model.drawingsData}">
    <mx:columns>
         <mx:AdvancedDataGridColumn
      headerText="Approved in Week"
      dataField="ApprovedInWeek"
      editable="false"
      visible="true"  />
     <mx:AdvancedDataGridColumn
      headerText="DRAWING_PK"
      dataField="DRAWING_PK"
      editable="false"
      visible="false"  />
     <mx:AdvancedDataGridColumn
      headerText="Drawing No"
      dataField="DRAWING_NO"
      editable="false"
      visible="true"/>
     <mx:AdvancedDataGridColumn
      headerText="Drawing Index"
      dataField="DRAWING_INDEX"
      editable="false"
      visible="true"/>
   </mx:columns>
</code>
`
According to this explanation link text I've implemented a GroupingCollection. But it just doesn't work!
<code><mx:AdvancedDataGrid id="drawingDataDG"
     editable="true" sortableColumns="true"
     headerWordWrap="true"
     sortExpertMode="true"
     rowCount="8" y="10" right="10" left="10"
            initialize="gc.refresh();">
        <mx:dataProvider>
            <mx:GroupingCollection id="gc" source="{model.drawingsData}">
                    <mx:Grouping>
                        <mx:GroupingField name="ApprovedInWeek"/>
                    </mx:Grouping>
            </mx:GroupingCollection>
        </mx:dataProvider>
        <mx:columns>
             <mx:AdvancedDataGridColumn
          headerText="Approved in Week"
          dataField="ApprovedInWeek"
          editable="false"
          visible="true"  />
         <mx:AdvancedDataGridColumn
          headerText="DRAWING_PK"
          dataField="DRAWING_PK"
          editable="false"
          visible="false"  />
         <mx:AdvancedDataGridColumn
          headerText="Drawing No"
          dataField="DRAWING_NO"
          editable="false"
          visible="true"/>
         <mx:AdvancedDataGridColumn
          headerText="Drawing Index"
          dataField="DRAWING_INDEX"
          editable="false"
          visible="true"/>
        </mx:columns>
 </mx:AdvancedDataGrid>
</code>
Please let me know what additional details you may need?
Answer: You have to pass the AdvancedDataGrid an instance of the HierarchicalData class as its dataProvider in order for it to recognize your GroupingCollections
Answer: Finally I was able to implement grouping according to this blog: Summarizing Grouped Data With Flex 3 AdvancedDataGrid Thanks Robusto for guiding!


What is the average number of glowstone per chunk?

Question: On the wiki it only states that "...it generates in crystalline clusters on the underside of ceilings or overhangs." No numbers are to be found.
Answer: After the 1.16 nether update, some areas of ceiling in the nether are no longer netherrack (soul sand valley and basalt delta), and glowstone blobs only spawn on those. After doing some quick experimenting, there are would be around 1.8 glowstone blocks, each 5.5 away if all the glowstone was spread evenly (this is not actually how it is unfortunately). For actual spawning sizes and frequencies, there are about 29 glowstone blocks every 88 blocks. Please note that this does not account for the areas where it cannot spawn. For every chunk, there will be just about five blocks.
Comment: Note: during the time while I was recording information, there were a few outliers: they were small blobs that were about 10 blocks apart and about 15 blocks each in size. In these clusters, there would be 2 to 3 blobs. I counted these as outliers and left them out.
Comment: Sorry if the answer is worded poorly, I wrote it in a hurry.


Filling gaps between bricks in pool deck

Question: I am repairing the deck around my pool. Some bricks were loose, so I removed them, ground off old mortar and glued them back. Now I need to fill the gaps between the bricks with mortar, similar to how it's done in the top left corner of the photo:

How do I do it in such a way that the mortar:
1. does not fall through;
2. lays level with the brick all around;
3. does not smudge on the bricks?
I was thinking of attaching a painters tape to the bottom to support mortar and make it flat with the brick on the bottom. And then maybe using a painters tape to prevent smudges on the bricks.
Or is there a better way?
What type of mortar is appropriate for this job?
And another question.. How do I attach the corner pieces reliably? I don't want them to be only supported by mortar.
Answer: Painters tape will not be the best way to keep the mortar from falling through the bottom. if fact it has been my experience that painters take barely sticks to brick and concrete. It would be better to take a longer piece of wood from each side of the corner that you clamp to the underside of the brick coping. C clamps or similar adjustable clamps would work for this. Place the clamps away from the corner so that they do not interfere with your mortar project.
It would actually be ideal if you could arrange these pieces of wood such that they were mitered in the corner to aid in dealing with the corner pieces. The wood pieces could even have a curved molding installed that came up half way around the nose of the coping bricks. Something like this:

For placing the mortar between the bricks you may want to look into tools used by the tuck-pointing trade. There is a funnel shaped bag with a narrow spout that you can fill with wet mortar and then squeeze it out through the spout. Works very much similar to the gazing bag that a cake decorator would use. They are also called grout bags. Picture source is from a video that shows using a bag.

Picture Source
Cleaning up the mortar off the bricks is pretty easy if you use a damp cloth and wipe up any smear that gets on the bricks. I suspect that once you get a little practice with the tuckpointer's bag that there should be very little mortar to clean up.
Dealing with the corner pieces will be tricky. I might suggest bonding the two pieces to a piece of metal so that they are more of a unit and then bond that to the base with the construction adhesive. you could also consider looping some wire through a hole in the metal piece and then pulling the wire back along the bottom of the angle cut between the bricks where it would be embedded into the mortar.


Comparing files using vector space model

Question: I have to create a demo using vector space model in Python based on the following problem:

We have a set of texts in different files.
Compare texts on the basis of word density.
You have to create a script to compare texts in the files and find out :

(I).  Which files have similar texts
(ii). Put similar files in a group  [ for example:    GROUP_1(  FILE25, FILE65 ) ]

Note:   One file may be added to multiple groups
I mean one text can be similar to more than one group
I currently have the following code:
<code>      import filecmp
      files = ['F1.txt', 'F2.txt', 'F3.txt', 'F4.txt', 'F5.txt']
      comparisons = {}
      for itm in range(len(files)):
         try:
             res = filecmp.cmp(files[itm], files[itm+1])
             comparisons[str(files[itm]) + ' vs ' + str(files[itm+1])] = res
             except:
             pass
         try:
             res = filecmp.cmp(files[itm], files[itm+2])
             comparisons[str(files[itm]) + ' vs ' + str(files[itm+2])] = res
            except:
            pass
         try:
             res = filecmp.cmp(files[itm], files[itm+3])
             comparisons[str(files[itm]) + ' vs ' + str(files[itm+3])] = res
            except:
            pass
         try:
             res = filecmp.cmp(files[itm], files[itm+4])
             comparisons[str(files[itm]) + ' vs ' + str(files[itm+4])] = res
            except:
            pass
  print(comparisons)
</code>
This gives:
<code>{'F1.txt vs F2.txt': True, 'F1.txt vs F5.txt': False, 'F2.txt vs F4.txt': True,
'F3.txt vs F4.txt': False, 'F1.txt vs F4.txt': True, 'F2.txt vs F3.txt': False,
'F2.txt vs F5.txt': False, 'F1.txt vs F3.txt': False, 'F3.txt vs F5.txt': False,
'F4.txt vs F5.txt': False}
</code>
How can I resolve this issue?
Answer:
Apply CountVectorizer ..  you will get the vector now
Apply euclidian distance or cosine similarity on two vectors to compare

For above two steps  there are readymade functions in sklearn. just explore the library
Alternatively you can simply use fuzzywuzzy to. It compares using EditDistance (Rather than vector space), but the results are good in many cases.


Getting ImportError: cannot import name 'soft_unicode' from 'markupsafe' for a conda environment while running `jupyter notebook`

Question:
My conda env was working fine till today when I activated it, it showed an Import error when I ran Jupyter Notebook command.

Tried this stackoverflow,

Reinstalling markupsafe didn't work

Thought of removing whole conda env and recreating with required libs

Didn't work

Looked at this stackoverflow:

Didn't seem to be the problem I've encountered.

I'd appreciate any help. Thank you
Answer: Try downgrading to an earlier version, if you are testing
pip install markupsafe==2.0.1

Downgrade to:
pip install markupsafe==2.0.0

Answer: FWIW I got this error after a fresh install and downgrading markupsafe did not fix it, however instead upgrading jinja2 from 2.10.1 to 3.1.2 seemed to do the trick.
First undo the downgrade if you tried that.
 pip install -U markupsafe

Then bump jinja2
 pip install -U jinja2

Answer: The root cause with your question may stem from a dependency management conflict between two software ecosystems. According to the error message, your markupsafe was installed using pip at the path /home/azriel-ubuntu-wsl/.local/python3.8/dist-packages/markupsafe/. The jinja2 that depends on it was installed using apt at the path /usr/lib/python3/dist-packages/jinja2. The versions of the two are not compatible. In fact, there is a version of markupsafe in the system that jinja2 correctly depends on, but the Python interpreter prioritizes the markupsafe installed by pip, leading to this issue. There are typically two solutions to this problem: (1) Use pip to uninstall markupsafe, and then reinstall it using apt, or uninstall jinja2 using apt and reinstall it using pip. (2) Use Python's imp module to customize the path and import the markupsafe from the apt path before importing jinja2. An example is as follows:
import imp
path = ['/usr/lib/python3/dist-packages']
fp, pathname, description = imp.find_module('markupsafe', path)
imp.load_module("markupsafe", fp, pathname, description)

Hope my diagnosis is helpful to you!


Why is the set $\{1,\sqrt {2}\}$ linearly independent over $\mathbb Q$ but not over $\mathbb R$?

Question:
Why is the set $\{1,\sqrt {2}\}$ linearly independent over $\mathbb Q$ but linearly dependent over $\mathbb R$?

I have only come across these types of questions with vectors, how would you go about showing this?
Comment: Can you solve $a \cdot 1 + b \cdot \sqrt{2} = 0$ if $a, b \in \mathbb{Q}$? Can you solve it if $a, b \in \mathbb{R}$? This is the difference.
Comment: Because $\sqrt 2$ is real but not rational.
Comment: Over $\mathbb{R}$ you can write $\sqrt{2}\cdot\mathbf{1}-1\cdot\mathbf{\sqrt{2}}=\mathbf{0}$ where the bold part are the vectors and the non-bold the scalars.
Comment: A field is a vector space over any subfield, so this *is* a "question with vectors."
Answer: That is because $\sqrt 2$ is irrational: if $1$ and $\sqrt 2$ were linearly dependent, $\sqrt 2$ would be  rational.
On the other hand, $\mathbf R$  has dimension $1$ over itself, so any two real numbers are linearly dependent.
Comment: $\mathbb{R}$ over $\mathbb{R}$ have dimension $1$, but $\mathbb{R}$ over $\mathbb{Q}$ have dimention $\mathfrak{c}$.


Fourier transform involving a dirac delta function

Question: I know that $\int \delta(x-a)f(x) dx =f(a) $ , the fundamental defining property of the delta function. How does this change if we no longer consider $x-a$ but $a^2 -x^2$, such that the integral is now
$\int_{-\infty}^{\infty} \delta(a^2 -x^2)f(x) dx$?
Thank you for any help in advance
Comment: is that  what you mean or there is something different?i have tried to answer this question
Answer: you can look on this formula

now you can apply sum formula and you should get
$f(a)/(|2*a|)+f(-a)/|2*a|$
also imagine that $(a-x)=-(x-a)$
Comment: @user1887919 to make sure  about answer,it is correct right?because i have not seen this in the books,that why not to accept maybe wrong answer,is it correct?
Comment: does this hold if f(x) is complex? I'm considering fourier transforms so suppose f(x)=(1/x^2)*e^(-ibx) where b is a constant, would your method still apply?
Comment: where did you find this problem?
Comment: It's just hypothetical... trying to get my head around Fourier transforms so just making up different questions
Comment: http://mathoverflow.net/questions/154341/fourier-transform-of-delta-fucntion  please see this,i dont know also exactly,i ahev combined your question and my answer,let us wait please ok?
Comment: i am also interested,mine is also hypothetical answer,just you can upvote to get  reputation 3400
Comment: they are crazy,every time i posting questions there,i am fighting with them
Comment: http://mathoverflow.net/questions/154346/modified-delta-function-and-its-feature there it is
Comment: Thanks a lot! I'd be really interested to know the answer been tearing my hair out for hours!
Comment: yes but they are mad persons,they are dowvoting why i dont know
Comment: i have reposted question http://mathoverflow.net/questions/154347/generalized-functions-and-their-fourier-trasnform
Comment: @user1887919 please repost question ok?
Comment: http://math.stackexchange.com/questions/635904/check-answer-on-given-qesution
Comment: @user1887919  please look there http://math.stackexchange.com/questions/635904/check-answer-on-given-question/635958#635958


Linq to entities - Query elements where List property has at least an element that matches other element in an in memory list

Question: A bit of a context for the problem:
I have an entity (Person) in my database that has a one to many relationship with another (Phone).
    public class Person
    {
        [Key]
        public int Id { get; set; }
        .
        .
        .
        [ForeignKey("PersonId")]
        public virtual List<Phone> Phones { get; set; }
    }

    public class Phone
    {
        [Key]
        public int Id { get; set; }
        .
        .
        .
        public string PhoneNumber { get; set; }

        public int PersonId { get; set; }

        public virtual Person Person { get; set; }
    }

Secondly I'm receiving a filter that includes a list of strings.
The Problem:
I'm trying to get from the DB all the Persons that have at least a PhoneNumber that matches (by like) any of the filter's phone numbers.
So far I've tryed this:
var query = _dbContext.Person
                .Include(x => x.PhoneNumbers)
                .AsNoTracking();
                .Where(x => x.Phones
                             .Any(y => filter.Phones
                                             .Any(z => y.PhoneNumber.Contains(z))));

This query throws an error:
The LINQ expression {my expression here} could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
Thanks you!
Comment: You cannot use with EF Core LINQ operators over in-memory collections, except `Contains` method. `filter.Phones.Any` is not translatable. Only dynamic predicate building can help in such situation.
Answer: If you use a standardized format for your recorded phone numbers (I.e. strip all separators and include a standard area code etc.) then you can format your search list of phone numbers to conform to the format and use:
.Where(x => x.Phones.Any(y => filter.Phones.Contains(y.PhoneNumber)));

The issue is that you cannot apply a Linq2Entity Any against the in-memory collection. You can use Contains against the collection but the phone numbers would have to match exactly. (so no inner LIKE type comparison)
If you have a reasonable number of search phone numbers and want to do the LIKE type search across the phone numbers then you can leverage LinqKit's PredicateBuilder to prepare a suitable condition. This requires marking the query as "Expandable" so the dynamic predicate can be built.
var query = _dbContext.Person
    .Include(x => x.PhoneNumbers)
    .AsNoTracking()
    .AsExpandable();

if (filter.Phones.Any())
{
    var predicate = PredicateBuilder.New<Person>();
    foreach(var phone in filter.Phones)
        predicate = predicate.Or(x => x.Phones.Any(p => p.Contains(phone)));
    query = query.Where(predicate);
}


I want to arrange and print words entered by the user in different combinations? Can anybody tell me how can I achieve this?

Question: Example:
input:
Number of words user want to enter : 3
Word no. 1: cat
Word no. 2: rat
Word no. 3: dog
output:
cat rat dog
cat dog rat
rat cat dog
rat dog cat
dog cat rat
dog rat cat
something like this.
Here is the code of another program, where I arranged letters in different combinations.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char character_swap(char*, char*);
void permutation(char*, int, int);

int main()
{
 char str[99];

 printf("Enter a string to find its permutations.\n");
 scanf("%s",str);

 system("clear");

 int n = strlen(str);
 permutation(str, 0, n-1);

 return 0;
}

char character_swap(char *x, char *y)
{
 char temp;

 temp = *x;
 *x = *y;
 *y = temp;
}

void permutation(char *a, int l, int r)
{
 if (l == r)
 printf("%s\n", a);

 else
 for (int i = l; i <= r; i++)
 {
 character_swap((a+l), (a+i));
 permutation(a, l+1, r);
 character_swap((a+l), (a+i));
 }
}

Can anybody tell me, how can I do the same thing with words?
Comment: What happens when someone enters a duplicate string? Just the same? You will probably have to accept `char **` (pointer to a char -> string) if you want to do it this way.
Comment: I will remove the duplicate strings/words from the input data. And can you please, how ` char **` will help me?. As I am new to C and there are things that I still don't know. And the problems that I faced during the creation of the program were I was facing trouble in swapping words and taking a multi-dimensional array as a function parameter by using pointers.
Comment: Hi Aayush - first, realize that strings in C are merely arrays of characters (with a null character at the end to denote the end of the string). So, in order to *sort* a bunch of strings, you first need to *store* the strings. This is most easily accomplished with a 2-dimensional array (which you'll want to read up on). Once you have the strings stored, you can modify your character swap if you want, but if all you're interested is the output, you can accomplish this more easily by just re-ordering numbers that correspond to the rows of the array (matrix). Hope this helps.
Answer: You have done a good job separating the permutation implementation from the main interface, such that this can this be done fairly easily. First, there are a few inconsistencies,

In character_swap, one has declare return type char, but never
return anything; must be void. It's used only in this file, so it should be static; this will avoid namespace conflicts let the compiler perform more aggressive optimizations. It also prevents prototype warnings as long as it is declared above.
int is not really the right type for working with indices; size_t is more appropriate.
It's a little awkward to explain that permutation is always going to be called with 0 index as it's second parameter. It's better to drop that and fill it in later, I have accepted the size in character_permutation, which calls character_permutation_r.

I have generalized the type from char to type using a typedef; I just replaced char by type. It would be simpler and clearer to replace type by equivalent char *, but in the next iteration, we are going to replace it with a totally opaque type; a typedef is warranted it because it keeps them all the type information together.
#include <stdio.h>
#include <string.h>

/* This is part of the interface. */

void character_array_output(const char *a, const size_t size) {
 (void)size; /* Don't use the size -- it's null-terminated. */
 printf("%s\n", a);
}

/* This is the implementation. */

typedef char type;

typedef void (*character_array_action)(const type *, size_t);

static character_array_action character_print = &character_array_output;

static void character_swap(type *x, type *y)
{
 type temp;

 temp = *x;
 *x = *y;
 *y = temp;
}

static void character_permutation_r(type *a, const size_t l, const size_t r)
{
 if (l == r)
  character_print(a, r + 1);

 else
 for (size_t i = l; i <= r; i++)
 {
  character_swap((a+l), (a+i));
  character_permutation_r(a, l+1, r);
  character_swap((a+l), (a+i));
 }
}

static void character_permutation(type *a, const size_t size) {
 if(size == 0) return;
 else character_permutation_r(a, 0, size - 1);
}

/* This is part of the interface. */

int main(void)
{
 char str[99];

 printf("Enter a string to find its permutations.\n");
 scanf("%98s", str);

 character_permutation(str, strlen(str));

 return 0;
}

For your question, type is char, and you want it to be char *, you just replace it with typedef char *type. However, a generalization to any assignable type is possible.
#include <stdio.h>
#include <string.h>

/* This is the implementation.
 `name` satisfies `C` naming conventions when mangled
 `nametype` is an assignable type
 `array_output` is a function satisfying `name##_array_action` */

#define DEFINE_PERMUTATION(name, nametype, array_output) \
typedef nametype name##type; \
\
typedef void (*name##_array_action)(const name##type *, size_t); \
\
static name##_array_action name##_array_print = &array_output; \
\
static void name##_swap(name##type *x, name##type *y) \
{ \
 name##type temp; \
\
 temp = *x; \
 *x = *y; \
 *y = temp; \
} \
\
static void name##_permutation_r(name##type *a, const size_t l, const size_t r) \
{ \
 if (l == r) \
  name##_array_print(a, r + 1); \
\
 else\
 for (size_t i = l; i <= r; i++)\
 { \
 name##_swap((a+l), (a+i)); \
 name##_permutation_r(a, l+1, r); \
 name##_swap((a+l), (a+i)); \
 } \
} \
\
static void name##_permutation(name##type *a, size_t size) { \
    if(size == 0) return; \
    else name##_permutation_r(a, 0, size - 1); \
}

/* This is the interface. */

void character_array_output(const char *a, const size_t a_size) {
    (void)a_size;
    printf("%s\n", a);
}

void string_array_output(char *const a[], const size_t a_size) {
    for(size_t i = 0; i < a_size; i++)
        printf("%s%s", i ? ", " : "", a[i]);
    printf("\n");
}

void integer_array_output(const int *a, const size_t a_size) {
    printf("{");
    for(size_t i = 0; i < a_size; i++)
        printf("%s%d", i ? ", " : "", a[i]);
    printf("}\n");
}

typedef int (*operation)(int);
static int value;
void operation_array_output(const operation *a, const size_t a_size) {
    printf("{");
    for(size_t i = 0; i < a_size; i++)
        printf("%s%d", i ? ", " : "", value = a[i](value));
    printf("}\n");
}

DEFINE_PERMUTATION(character, char, character_array_output)
DEFINE_PERMUTATION(string, char *, string_array_output)
DEFINE_PERMUTATION(integer, int, integer_array_output)
DEFINE_PERMUTATION(operation, operation, operation_array_output)

#include <math.h>
static int square_n(const int n) { return n * n; }
static int sqrt_n(const int n) { return sqrtl(n); }
static int double_n(const int n) { return 2 * n; }

int main(void)
{
 char str[] = "abc";
 character_permutation(str, strlen(str));

 char *strings[] = { "cat", "rat", "dog" };
 string_permutation(strings, sizeof strings / sizeof *strings);

 int numbers[] = { 42, 99, 1, 0 };
 integer_permutation(numbers, sizeof numbers / sizeof *numbers);

 operation ops[] = { &square_n, &sqrt_n, &double_n };
 value = 1;
 operation_permutation(ops, sizeof ops / sizeof *ops);
 value = 5;
 operation_permutation(ops, sizeof ops / sizeof *ops);

 return 0;
}


How get process owner use WMI request

Question: I try to receive the list of processes using go-ole library:

    package main

    import (
        "fmt"
        "github.com/go-ole/go-ole"
        "github.com/mattn/go-ole/oleutil"
    )

    func main() {
        ole.CoInitialize(0)
        defer ole.CoUninitialize()

        unknown, _ := oleutil.CreateObject("WbemScripting.SWbemLocator")
        defer unknown.Release()

        wmi, _ := unknown.QueryInterface(ole.IID_IDispatch)
        defer wmi.Release()

        serviceRaw, _ := oleutil.CallMethod(wmi, "ConnectServer")
        service := serviceRaw.ToIDispatch()
        defer service.Release()

        resultRaw, _ := oleutil.CallMethod(service, "ExecQuery", "SELECT * FROM Win32_Process")
        result := resultRaw.ToIDispatch()
        defer result.Release()

        countVar, _ := oleutil.GetProperty(result, "Count")
        count := int(countVar.Val)

        for i :=0; i < count; i++ {
            itemRaw, _ := oleutil.CallMethod(result, "ItemIndex", i)
            item := itemRaw.ToIDispatch()
            defer item.Release()

            processName, _ := oleutil.GetProperty(item, "Name")
            fmt.Println(processName.ToString())
        }
    }

but I cannot receive the owner of process, call method GetOwner
ownerRaw, _ := oleutil.CallMethod(item, "GetOwner")
fmt.Println(ownerRaw)

because GetOwner return value is int32

    uint32 GetOwner(
      [out] string User,
      [out] string Domain
    );

https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/getowner-method-in-class-win32-process

How it is possible to receive the owner as string for each process?
Answer: It took me a while to figure this out.
The GetOwner method is expecting you to pass two string parameters. These strings will contain the results of the method call.
var user ole.VARIANT
var domain ole.VARIANT
res, err := oleutil.CallMethod(item, "GetOwner", &user, &domain)
fmt.Printf("user: %v\tdomain: %v", user.ToString(), domain.ToString())

To get the SID you do the same thing:
 var sid ole.VARIANT
 res, err := oleutil.CallMethod(item, "GetOwnerSid", &sid)
 fmt.Printf("sid: %v\n", sid.ToString())

How get process owner use WMI request


Trying to add Android Studio Project to github

Question: I'm trying to add an Android Studio Project to github, however only the gitattributes and .gitignore files were added to the repository and it won't seems to add the actual project files. Doing VCS->Git->Add does nothing and Committing just gives me a message that no changes are detected
Answer: You're probably having some issues with your .gitignore - it seems to be ignoring too much things.
The best you can do is go to the terminal and run git status --ignored to see if this is the case. If it is, review the contents of your .gitignore and try again.


How to catch browser close in Liferay?

Question: I am catching user logouts with hook with
logout.events.post=...
action and this works.
But also I want to catch browser close as logout too.
How can I accomplish this?
servlet.session.destroy.events=
is not fired I guess.
Thanks.
Comment: I don't believe this is possible. I don't think there is an event that can be fired when the user is closing a tab or browser because there is no notification by the browser that the user closed out a window.
Comment: I found that sessions are closed approximately in an hour after close, but don't know how to deduce user to which session was belong to.
Answer: The browser close happens on the client... and the session may not have been destroyed (user may not have logged out).
On the client side, you may want to do
<code>window.onbeforeunload = function() {
     make_an_ajax_call_to_server_to_notify();
     return null;//to close
     //OR
     //return "Do you really want to close?" to let user click an "Ok" button
}
</code>

How to catch browser close in Liferay?


Eclipse Scala IDE - class file needed by X is missing

Question: The Eclipse Scala plugin sometimes gives me bogus compilation errors saying "class file needed by some class is missing". This may be related to the fact that my project depends on other projects in the same workspace. Cleaning the project - even cleaning all open projects - does not resolve these errors. How can I make them go away?
Answer: This can be caused by having two different versions of the same jar in the classpath (or, I suppose, by having just an old binary-incompatible version of a jar in the classpath). You can use a classpath checking tool like JBoss Tattletale to detect problems like this.
Here is an example Tattletale command line for analysing a project where all the jars are in the lib subdirectory:
java -Xmx512m -jar $HOME/opened/tattletale-1.1.2.Final/tattletale.jar $HOME/$PROJECT/lib $HOME/opened/tattletale-1.1.2.Final/reports/$PROJECT

Tattletale will create the report directory (the last argument) if it does not already exist. There are also versions of Tattletale for Maven and Ant projects.
Then open the file
tattletale-1.1.2.Final/reports/$PROJECT/index.html

in your web browser, and look around, particularly at pages like "Eliminate Jar files with different versions" and "Multiple jar files". Those pages will be empty if no problems of that type have been found.
Comment: IMO this is the most helpful answer, at least it have led me to resolution. I guess you should accept it. Thanks a lot.
Answer: Close all open projects, then open the project that has these error(s). This worked for me, but only in some cases. It's possible that the project clean I did beforehand was needed as well.
Answer: The Scala compiler appears to canonicalise paths (or maybe it's just the Play 1 Scala plugin, I'm not sure). So if you have created a symbolic link on Linux or Mac OS X, which points from foo.jar to foo.jar.orig, the Scala compiler will consider it to not be a .jar file, because it will look at the canonical path. So any jar like this will be silently dropped from your classpath.
Answer: You may NOT have some required symbols in classpath, or, as well (!), you may have multiple versions of a jar in classpath, which was my case.
I had a similar problem while doing full rebuild in IntelliJ after mounting salat and casbah into the project. SBT builds went okay, while idea started to fail.
I've dismounted casbah, as it is transitively imported by salat and the problem vanished.
Hope that helps someone out there.