How to make JSON data as Array in PHP?

Question: Am trying to output an array from this JSON response
[
    [
        {
            "nombre": "TSU EN TICME",
            "nivel": 1,
            "numero": 4,
            "alias": "TICME",
            "inicio": "2016-09-02",
            "fin": "2019-09-26"
        },
        {
            "nombre": "TSU EN CONTADURIA",
            "nivel": 1,
            "numero": 6,
            "alias": "CONT",
            "inicio": "2016-09-03",
            "fin": "2019-09-27"
        }
    ]
]

Comment: Because it shows no research, this question was asked countless times
Comment: That's a lot of downvotes for a brand new user. Maybe instead of simply downvoting, ya'll could provide some guidance that would actually be useful. `¯\_(ツ)_/¯`
Comment: @CaddyDZ, I'm not saying the question doesn't merritt downvotes. I'm saying it's not particularly helpful for a brand new user to see a bunch of downvotes on their question without any explanation as to why.
Comment: Possible duplicate of [how to convert json string to array in php?](https://stackoverflow.com/questions/35269178/how-to-convert-json-string-to-array-in-php)
Answer: You can use the json_decode (see docs) function to take the data you have and parse it into a php array.
$array = json_decode('[[{"nombre":"TSU EN TICME","nivel":1,"numero":4,"alias":"TICME","inicio":"2016-09-02","fin":"2019-09-26"},{"nombre":"TSU EN CONTADURIA","nivel":1,"numero":6,"alias":"CONT","inicio":"2016-09-03","fin":"2019-09-27"}]]');

Keep in mind, Laravel is not a programming language. It is a PHP framework. That's why you won't find this in the Laravel documentation. When you are looking for something like this, you should be searching the PHP documentation.
Comment: How can I reproduce it in a foreach or in a for?
Comment: Here you go: https://www.php.net/manual/en/control-structures.foreach.php
Comment: @RaymundoAparicioOlarte, if this answer solved your problem, please upvote it, and mark it as "accepted" (checkmark), so that it can help other users in the future. Thanks!

How to make JSON data as Array in PHP?


How to open (.tif) file using System.Diagnostics

Question: I have problem during opening a (.tif) file it throws an exeption
"The system cannot find the file specified". Below is my code on how to open (.tif) file:
try
{
    ProcessStartInfo p = new ProcessStartInfo();
    p.FileName = "MSPVIEW.exe";
    p.Arguments = @"C:\New folder\sample.TIF";
    p.UseShellExecute = false;
    p.ErrorDialog = false;
    p.RedirectStandardOutput = true;
    p.WindowStyle = ProcessWindowStyle.Maximized;
    Process.Start(p);
}
catch (Exception ex)
{

    MessageBox.Show(ex.Message);
}

But when I'm going to open a (.txt) file there's no problem with it.  Below is my code on how to open (.txt) file:
try
{

    ProcessStartInfo p = new ProcessStartInfo();
    p.FileName = "notepad.exe";
    p.Arguments = @"C:\New folder\NewTextFile.txt";
    p.UseShellExecute = false;
    p.ErrorDialog = false;
    p.RedirectStandardOutput = true;
    p.WindowStyle = ProcessWindowStyle.Maximized;
    Process.Start(p);
}
catch (Exception ex)
{

    MessageBox.Show(ex.Message);
}

Is there anybody have the same issue of opening of (.TIF) file? Or provide some solution on how to fix this?
Comment: where is mspview.exe? the location of the file
Answer: It sounds like either the path to mspview.exe or sample.TIF isn't valid. Can you specify the full path to mspview.exe and open Windows Explorer to verify the path to sample.TIF?
Comment: Read the question again: `But when I'm going to open a (.txt) file there's no problem with it`
Comment: A little more info: a call to notepad.exe (no path) works because it's in the base windows directory which is in the PATH environment variable.  mspview.exe is a part of Microsoft's document imaging and its path is not normally stored in the PATH area.  So you have to provide the full path to the executable.
Comment: Change "notepad.exe" to "MSPVIEW.exe" and this will probably be the correct answer.
Comment: I tried to edit the code which given solution from @NotMe, from this code  p.FileName = "MSPVIEW.exe" to this one  p.FileName = @"C:\Program Files (x86)\Common Files\microsoft shared\MODI\12.0\MSPVIEW.exe". Then it works, Thank you very much
Comment: Sorry, copied the filename from the wrong example in the question. Meant to say MSPVIEW.exe. Thanks for updating it!


Trouble understanding, implementing and then using multiprocessing module in Python

Question: I am experimenting with python multiprocessing module and now I have got a task to complete via using multiprocessing . I have already tried many ways of doing it, but I always end up either with:

An endless cycle creating subprocesses
An absurdly slower time than when running it regularly
A straightforward error regarding syntax or other (for me completelly foreign) different errors

Here is one of my functions, that I would need to speed up via multiprocessing:
<code>def CosineEvaluation(dictOfElements, nestedDictOfFiles):
    upperHalf = 0
    lowerHalfLeft = 0
    lowerHalfRight = 0
    nestedKeys = []
    resultsList = []
    result = 0

 for evaluationNum in range(len(nestedDictOfFiles)):

        for keys in nestedDictOfFiles["file" + str(evaluationNum)].keys():
            nestedKeys.append(str(keys))

        howManyKeys = len(nestedDictOfFiles["file" + str(evaluationNum)])
        print(howManyKeys)
        dictOfElementsCopy = dictOfElements
        if(len(dictOfElements) < howManyKeys):
            for emptyValue in range(len(dictOfElements), howManyKeys):
                dictOfElementsCopy["empty" + str(emptyValue+1)] = 0

        for key, value in dictOfElementsCopy.items():
            for itemCount in range(len(nestedDictOfFiles["file" + str(evaluationNum)])):
                if(nestedKeys[itemCount] == key):
                    upperHalf += value * nestedDictOfFiles["file" + str(evaluationNum)][nestedKeys[itemCount]]
                lowerHalfRight += value ** 2
                lowerHalfLeft += nestedDictOfFiles["file" + str(evaluationNum)][nestedKeys[itemCount]] ** 2

        result = (math.sqrt(upperHalf)  / (math.sqrt(lowerHalfLeft) + math.sqrt(lowerHalfRight))) * 100
        result = round(result, 5)
        resultsList.append(f"Percentage of file no. {evaluationNum} is: " + str(result) + " %")

        indexWord = 0
        upperHalf = 0
        lowerHalfLeft = 0
        lowerHalfRight = 0
        nestedKeys.clear()

    print(resultsList)
</code>
I understand and very well know, that this function is (probably) an algorithmic hell (when regarding speed) but one of the conditions for this task was not to use any additional libraries besides the basic ones (that essentially means that I can use native Python libraries and Numpy). Also, I am learning and I want to make better programs eventually. But that is not that relevant now.
The function I put there is just one of the functions that are in the project, but they are basically all the same code-wise (nested loops and various calculations). Would it be possible for me to refactor the code to work with multiple processes? If yes, could anyone please show me the way to do it on this function?
Thanks alot in advance :)
Comment: It just does not make any sense to use multiprocessing here, because if your PC works at 100% CPU, it won't get faster by splitting the calculations into multiple processes. In fact, AFAIK it should even be slower, because all the variables need to be created once for every process, instead of only one time. If you want your code to be faster, you need to make it faster in itself (clean up the "algorithmic hell")
Comment: I apologize that I did not mention it - CPU is not at 100% when the code is running, it is merely chilling at 20%, hence why I am looking for improvement, because there is CPU space to be filled I think.
Comment: Okay, you are right, 20% CPU are quite depressing. But, yould you add the code where you got "A straightforward error regarding syntax or other (for me completelly foreign) different errors" and post these errors, too ?
Comment: I figured out, that those errors were caused by badly written code - you see I am quite new to multiprocessing so I had to google a bit to find out what was wrong. Still though, despite me fixing that issue, I end up in an endless loop of subprocesses being created.
Answer: So the problem I had was indeed something I would have never thought of - Windows behaves completelly differently than Linux when regarding threads/subprocesses. That means, that without a pre-defined main function and a split function, that (as the name suggests) splits the algorithm into integer parts (not decimal!), you can't convince the interpreter to track those processes correctly. So, create a split function, create main function and call it from there - looks like problem solved, program is running aprox 3-4 times faster now.


problem updating user space IEEE 802.11 AP and IEEE 802.1

Question: while updating software on Ubuntu 14.02 LTS using Software Updater, I am having problem.
There is 62.6 MB of update available, but after opening the Software Updater window, it shows all updates checked except one

User space IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator

check box for this update is grayed out and unable to select this update to download.
After clicking Install Now leaving that update unchecked, it gives error just after.

I have also tried the command line
$sudo apt-get update
$sudo apt-get upgrade

But nothing happend.
Answer: I had the same problem. I still don't know to solve this grayed out check box problem but if you want to have update version of this software, here is the solution:-

Open Synaptic Package Manager(or any package manager you prefer)
Search hostapd and uninstall it.
Then re-install the package and newly installed package will be the latest version.
Answer: I was facing the same problem.
What I did:
I opened Ubuntu Software Center and searched for "User space IEEE 802.11 AP and IEEE 802.1X/WPA/WPA2/EAP Authenticator" and found that it's called hostapd. I clicked on "Remove" to uninstall it, and a prompt showed up saying that I need to uninstall ap-hotspot too. It's an app to turn your computer into a WiFi hotspot, much like Windows' Connectify. I let ap-hotspot be uninstalled along with hostapd. I searched for hostapd and installed it (again). Problem solved. Then I installed ap-hotspot too. Yay.
For anyone reading this, check if you use ap-hotspot. If you are, probably that's the problem. If you are not, search for a solution elsewhere; this answer is useless to you.
Edit:
ap-hotspot doesn't work when you update hostapd, must be buggy. You might want to think over it again, if you want to update it or not. Depends on how important ap-hotspot is to you.


How do I mount a pendant light with only a cord (no chain or metal tube)?

Question: I would like to hang a glass pendant light to replace a light in my house. The box is good (I never had a problem with the old light and it looks fine on inspection) but I can't quite figure out how to get the new one up there. I have the cross piece, which connects to the canopy, but nowhere that I can see does it actually attach to the cord (see the attached picture). The cord simply goes through the piece to attach to the home wiring. I'm pretty sure I don't want the home wiring to hold the weight of the fixture (it's not super heavy, but it's not light either). There is no set screw in the canopy which could hold onto the cord. Is there some sort of collar with a set screw I can use around the cord? Am I supposed to tie a knot or some such thing?
Thanks in advance for the help.
Comment: Should be a threaded hole where the cord/wire goes into the lamp.  You do not use the cord to hang/hold weight.
Comment: That flat plate, of which we have a perfect edge-on view, should have a couple of holes in it that line up with threaded holes in the ceiling box. You should have a couple of screws that go through the plate and into those holes in the box and that's what holds the weight of the lamp. Please provide pics of the plate and the box ([edit] them into your post) for confirmation.
Comment: @FreeMan Yes, of course the flat plate has screw holes in it. That plate certainly attaches to the box and the canopy attaches to it. The issue is that the canopy and the plate have no connection to the cord or to the glass bell itself.
Answer: So, I forgot to zoom in earlier.

My prime suspect now is that you simply need to loosen the barely seen setscrew on this part (or two if it has two) and slide it up until it will thread on to the nipple. There appears to be a setscrew just barely visible on the side, there appears to be a line indicating that this part is not attached to the lamp, and the treatment of the end of it facing the lamp matches the treatment of the part on the lamp with its clearly seen setscrew. They are a pair of cord-clamps - one on the lamp, one on the ceiling fixing. The one on the ceiling fixing whould thread onto the nipple and hold the cover in place.
Me, I'd still put a knot in the cord above the nipple, simply to keep from dropping the lamp and yanking the connections while threading this on and later removing it. But wait - what's this? A cable clamp so you don't have to tie a knot up there for that purpose, I do believe. Set your desired length, clamp that on the cable, connect wires and screw plate into box, slide the outside cable clamp up the cord, screw on to secure the cover and tighten setscrew to firmly grasp the cord.

If that doesn't turn out to be the case, the original (below) still applies.
Either

The top-most nut causes compression of an o-ring that grabs the cord
jacket (a cable gland)though this does not look quite right for that.

OR

You tie a knot in the cord, such as the so-called Underwriter's Knot.

OR

You replace that fitting with a cable gland/strain relief/cord grip.
Comment: Are you suggesting that the fixture should actually be supported by the cord and that the plate (of which we have a perfect edge-on view) isn't supposed to be screwed to the box to support the weight?
Comment: The plate is screwed to the box. The cord supports the fixture, the plate supports the cord. Hanging lamp cords are designed to do that. Heck, virtually everybody's dining room table lamp when I was growing up had a cord retractor reel so you could raise it up or pull it down to suit the number of diners and how far the table was pulled out.
Comment: Gotcha. That does make sense and identifies you, like me, as a child of the 70s. :)
Comment: Thanks for the response! Unfortunately, that thing that looks like a set screw on the upper piece (which is indeed separate from the lower one) is merely an artifact of the light reflecting badly in the photo (the bottom piece does have a set screw, which you can see). Also, that cord clamp up top is flimsy plastic, meaning that I don't really want to trust the weight of the lamp to it. I ended up buying some of these (https://www.amazon.com/gp/product/B07VQXJBM9/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1) from Amazon to screw into the cord up top. Do you think that'll be strong enough?
Comment: I think tying a knot in the cord above the tube (or using the flimsy clamp since that's apparently as designed and intended - or both for belt and suspenders) would be adequate, but those might also work - and I'd still knot the cord.
Answer: Some lamps are designed to be suspended by their electrical cords (using appropriate cable also designed for that).   Other lamps are designed to be connected to the box ears via a cross bar or the box stud via a nipple.
Lamps suspended from cords usually have rubber cords, a canopy that is secured to the box, and either a knot or a clamp to suspend the cable from the canopy.  You have a rubber cord but none of the other features of such a lamp.
Lamps attached to the box usually have wires, not a rubber cord, run through the threaded pipe, and a way to attach the pipe to the lamp and to the box.  You have a cord, not wires, you have a threaded pipe and a cross bar, but it's not clear if the pipe can be attached to the lamp.
It is hard to be sure from your photos, but it looks like the lamp can be connected to the threaded pipe at the point where @ecnerwal drew a yellow box.  The threaded rod is connected to the cross bar and the cross bar connects to the box ears.  The cable, running through the pipe, should be completely slack, you should make a few loops with it where it exits the pipe at the top to allow the lamp to be raised and lowered and attached via the threaded rod.   You might need some kind of adapter to connect the rod to the lamp.
If that's wrong, if the top of the lamp is secured to the cable by compression and cannot be screwed onto the threaded rod, you should eliminate the threaded rod, and just use the cross bar to suspend the cord by tying a knot in the cord or attaching a plastic compression bushing above the cross bar.    Your canopy does not look like it was designed to perform this function.
Comment: There is clearly a canopy, and if the part in the yellow box is the cord clamp which threads to the nipple it secures the canopy to the box **and** is a cord clamp...so jumping to "you don't have these parts" seems a bit premature without some further input form the questioner.
Comment: For the canopy to support the lamp via the cord it would have to be attached to the box via box screws, and I don't see that here, it looks like the canopy is supported by a nut or the lamp threaded to the rod.  If the canopy and lamp are supported by the rod, then the cord plays no part in supporting anything.  Even if there's an integrated cord clamp, it has no role.    Of course further info might change/improve this answer! But I'm fairly confident in what I see here.
Comment: Hi all, thanks for the answer and comments. I'm not totally sure I follow all of your points, but to clarify. There is a plate that attaches to the box in the ceiling. The threaded rod hanging from this has a hole that goes through the canopy. The piece below that threads onto the rod and supports the canopy. That's all good. The problem is that none of the previously-mentioned pieces attaches to the cord in any obvious way. There's no real compression clamp (just the flimsy plastic one you see) or anything else that's obvious to me.
Comment: Also, just so we're clear, these is no rod attached to the lamp. Only a rubber electrical cord.
Comment: You should follow the new detailed instructions in the answer from @Ecnerwal.  I think he has identified how this lamp was meant to be assembled.


Strange freeze when loading IntelliJ IDEA Editor

Question: Since about three weeks IntelliJ is freezing when I'm trying to load any project. It's the same with a new project too.
It seems like it freezes the whole xserver - I can't interact with any application until I kill the java process in the terminal.
Currently I'm using Ubuntu GNOME 14.04 (tried it with Kubuntu 15.04 too) and IntelliJ 14.1.4.
What have I checked already?

Several log files (IntelliJ Log, syslog) - There is nothing about the error
Console output of IntelliJ - nothing too

What have I tried already?

New, raw installation of IntelliJ (same problem)
Reinstall the operating system (it worked until the first reboot after the installation of IntelliJ)
Different Java versions (Oracle/OpenJDK, JDK7/8) (same problem)
Other desktop environment (Gnome, KDE Plasma) (same problem)
Change some JVM args (related to RAM) (not working)
Run IntelliJ as root (not working)

Maybe an additional interesting piece of information is that this error first occured after I changed my mainboard, CPU and RAM. However, IntelliJ on Linux is the only program with troubles - so I hardly believe that the reason of the problem is the change of the hardware.
Output of free -m
<code>             total       used       free     shared    buffers     cached
Mem:         15943       5518      10424        100        704       2541
-/+ buffers/cache:       2272      13670
Swap:         8192          0       8192
</code>
Comment: Add the output of `free -m`.
Comment: @prakharsingh95 I added it to the post.
Comment: This seems to be the same problem, the "workaround" to use taskset 0x80 ./idea.sh works, but IDEA is very slow: http://ubuntuforums.org/showthread.php?t=2278238
Answer: I've experienced a similar freezing issue with IntelliJ IDEA 2016.2.4 (162.2032.8) on Ubuntu 16.04.1 (64-bit) when importing a project.
JetBrains support suggested the following work-around:
Before the UI becomes unresponsive change from "Packages" to "Project" view.
That allowed me to proceed past the freezing.
The support referenced this unresolved issue from 2008 regarding this behavior: IDEA-18765 Slow synchronous package view tree update


Dishwasher Drain Pump: How to Test?

Question: my dishwasher isn't draining.
I checked the drain hose and it's clear enough that I could blow air through it.

I removed the drain pump, model #W10158351B I measured the resistance
between the two connector pins: ~24ohms.
I connected the two leads to
a 120VAC supply. The impeller would turn maybe 2-3 degrees and stop,
with the motor making a hum. I did this with the polarity only one
way (randomly chosen).

I think this is pretty conclusive that the motor is dead but I'd like to be sure before I buy the replacement.
I'm also surprised to find water has been leaking out of the pump bit by bit. I presume that means water has made it past the impeller seal and is generally bad?
Is my drain pump bad? Are there other tests I should perform?
Thanks!
Comment: does the impeller turn freely by hand?
Comment: It did. There was some resistance, but not a ton.
Answer: I have the same problem you had.  I am not sure of the proper impedance you should have.  One internet repair place says 200 ohms for a good motor.  I did the same thing you did (same problem - dishwasher not draining) lines were clear to disposal - I also exercised the check valve which is in the 90 degree black elbow right off the drain pump on my machine (Whirlpool model WDF760SADM) forward and backward to ensure it flowed and would stop flow in the reverse direction, which it did.  I do not have leads that are compatible with the motor to check that it runs.  I am going to replace the drain pump to see if that is the problem.  Also, the jerky motion on the impeller is due to the magnetism on the motor.
Comment: It's been 2+ years since I posted this. After sitting out of the dishwasher for a few days, the old motor just decided to start working again and has worked fine ever since. I figure it dried out and became fine.

I actually bought a new replacement motor and have it sitting in the box. I'll measure the resistance on it and post back.
Answer: For future reference. You can try removing the hose casing from the pump motor and clean the motor around the propeller throughly and Lubricate then turn the propeller manually a few turns to get anything that may be jamming it out then reconnect. If it's receiving electricity (making a humming noise) but not turning, chances are that something is stopping it from rotating.
Answer: For future reference, before you take the thing out:
Unplug and replug the power and switch it on. Three things should happen in a reasonably modern dishwasher.

Power light will become bright
The water inlet sensor will either open or fail-close on pressure of inlet water. Closed switch means no power to dishwasher.
The drain pump will do one or two revolutions at minimum

It can be the water inlet sensor or the water inlet pressure that is fouling up. Since the sensor is fail close it should get hot to the touch (by just a few degrees, don't worry) over time if it is working. So check that it gets warm. Some models also have lights to indicate SENSOR OK, that saves a bit of waiting. If that isn't working, check the water on the inlet side. Remember you have to power down the machine with the plug to reset the switch, if you find you have a valve closed. If the water is fine, the sensor is fine, the drain swamp is reasonably clean, and still no "chugs" from the pump - take it out for manual testing.
Any leakage or failure to run should be considered graveyardable offenses. It just isn't economically reasonable to do anything else than getting a working one - scrap dealers usually have tonnes of them.
Answer: Not taking the dishwasher out, able to reach the pump, diconnecting and removing it, I then took my wet vac and connected it to the end of the discharge hose. Then using the blow side of the wet vac tried to blow forward breaking up the blockage. This not working using the vac side broke the blockage and about a gallon of water that was traapped. Put everything together disshwasher worked fine.
Answer: With the pump still on the machine:

Use a multimeter on the continuity setting check each lead to see if either one has continuity to the frame of the machine. If it does, that is bad. This is an unlikely culprit.
Put the multimeter on the ohms setting. Put the probes on the two motor contacts. Anything in the 10s to 100s of ohms should be considered good. If it is higher than hundreds, it is possibly bad.

If it passes those tests, remove the pump and attach 120v AC (or whatever the specs say on the label on the pump depending on the country you live in). You can do this by taking an old power cord from a junk appliance, tool, or light and stripping the ends of power and common. Attach them to the motor leads and plug it in keeping hands away from those wires. If the impeller spins it is good. If it doesnt spin it is bad.
If it spins, Id suggest looking into the impeller housing- there may be a small chip of glass or ceramic in there that could be jamming the impeller.
Answer: Dishwasher was not draining completely. Checked hoses and found them to be clear. Could not hear pump running as was usual when starting a cycle. I was about to order a new pump when I decided to see if the check valve was operating properly. The valve was fine but I did notice that the impeller was difficult to turn. Further investigation revealed a chunk of ceramic pottery that had become wedged between the impeller housing and the impeller. Removal of the piece of pottery restored the dishwasher to normal operating condition.
Comment: Hello, and welcome to Home Improvement. This is interesting, but doesn't answer the original question. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: Make sure you check the pipes connected to the drain hose going to your sink. We FINALLY found that the connection from the drain hose to the PVC pipe was corroded and completely blocked. Dishwasher is running fine now...3 weeks later.

Dishwasher Drain Pump: How to Test?


How to generate an xorg.config on Ubuntu 16.04.1

Question: We've been trying all the techniques to generate an xorg Config on Ubuntu 16.04.1 but have not had any luck. Has anyone figured out how to do this on the lates Ubuntu 16.04?
Here are things we've tried:
Where is the X.org config file? How do I configure X there?
Comment: If you have NVIDIA drivers installed, I believe you run `nvidia-xconfig` from the command line to create a xorg.conf.
Comment: What was the problem with original answer there?
Comment: Hi anwar, We've been trying the original answers, they don't work. We are using NUC5i5MYHEs so no nvidia utilities.
Answer: You could install the NVIDIA linux driver from the nvidia webpage which will ask you to generate the xorg.conf during installation. To do that:

Determine your card:
<code>$ lspci -vnn | grep VGA
</code>
and check for your card details. On my system i get the following output running the above command:
<code>$ 03:00.0 VGA compatible controller [0300]: NVIDIA Corporation GK110GL [Quadro K6000] [10de:103a] (rev a1) (prog-if 00 [VGA controller])
</code>
So you see im using a Quadro K6000.
Head over to NVIDIA Drivers entry page and search the proper driver for your card:

Click search and download the driver to your desktop.
The do the following to install the driver:

switch to console mode: Alt+Ctrl+F1
kill x server: sudo service lightdm stop
switch to desktop: cd ~/Desktop
make the downloaded driver executable: sudo chmod a+x
NVIDIA-Linux-x86_64-367.44.run
install it with sudo rights: sudo ./NVIDIA-Linux-x86_64-367.44.run

During the installation answer YES when you get asked if the installer should generate the xorg.conf file.

If you already have the nvidia packages installed from the repositories user Terrance comment is fine


Short code samples, solving interesting problems (in multiple languages)

Question: recently I've found an interesting  sample "spell checker in 21 lines of code" by head of Google research department - Peter Norvig http://www.norvig.com/spell-correct.html
Although it's an very interesting stuff by itself, it's also interesting to see how the same problem are solved in different languages!
Do You know more of such samples (solved in multiple languages)? Please post link here.
Comment: Not a real question since there cannot be a *right* answer
Answer: Have look at PLEAC the same problems solved in numerous languages.
Currently these languages are included:

perl
groovy
ocaml
python
ruby
guile
commonlisp
rexx
tcl
pike
php
haskell
merd
picolisp
ada
haskell-on-steroids
java
cposix
pliant
c++
factor
smalltalk
forth
erlang
R
objective-c
masd
bash
nasm
go
Answer: Check Rosetta Code, it's a huge collection of tasks solved in different languages.
Answer: The website 99 Bottles of Beer holds implementations of the lyrics of the song 99 Bottles of Beer in 1434 programming languages.
PLEAC contains implementations in several languages of the common programming problems presented in the Perl Cookbook.
The Rosetta Code also presents solutions to the same task in many different languages.


Complex analysis question including maximum of real part of $x+i$

Question: I'm asked to prove that:
$$\max_{x\in \mathbb{R} } \operatorname{Re}(x+i)^{10} = -\left(\sin \left(\frac{\pi}{18}\right)\right)^{-9}$$
any ideas? i don't even know where to start.
Comment: It easy to see that $\sup_{x\in \mathbb{R} } \operatorname{Re}(x+i)^{10}=+\infty$. Probably you are looking for the minimum!
Answer: You can start by expanding $x+i$ :
$$(x+i)^{10}={10 \choose 0}x^{10}+ {10\choose 1}x^9i^1+{10\choose 2}x^8i^2...{10 \choose 10}i^{10}=\\\\x^{10}+ {10\choose 1}x^9i^1-{10\choose 2}x^8...-{10 \choose 10}\\\\$$
Then, any term left over that still contains $i$ could be changed to complex notation, $$i=e^{i\pi/2} => i^m = e^{i^m(\frac{\pi}{2})^m}=cos(\frac{\pi^m}{2^m})+sin(\frac{\pi^m}{2^m})i^m$$
I think that $x^{10}$ would win out in the end. You can show that any term without $i$ will be smaller than $x^{10}$ because it's power of x will be smaller, and any term multiplied by a $sin$ or $cos$ will also be smaller because $sin$ and $cos$ are always smaller than 1.


How can I drag and drop single item in flatlist when use panResponder?

Question: I use flatList for render each item from array data. I want to drag and drop each item flatlist so I used panResponder and aminated API. But when I drag and drop, it moving all item in flatList at the same time. How can I move only 1 item that I click in this.
<code> return (
  <Animated.View
    key={item.index}
    {...this.panResponder.panHandlers}
    style={this.state.pan.getLayout()}>
    <View
      key={item.index}
      style={[styles.event, {
        left: item.left + 50,
        height: item.height,
        width: item.width,
        top: item.top
      }]}
    >
      {this.props.renderEvent ? this.props.renderEvent(item) : (

        <TouchableOpacity
          activeOpacity={0.5}
          onPress={() => this._onEventTapped(this.props.events[item.index])}
        >
          <Text numberOfLines={1} style={styles.eventTitle}>{item.title || 'Event'}</Text>

          {numberOfLines > 1
            ? <Text
              numberOfLines={numberOfLines - 1}
              style={[styles.eventSummary]}
            >
              {item.summary || ' '}
            </Text>
            : null}
          {numberOfLines > 2
            ? <Text style={styles.eventTimes} numberOfLines={1}>{moment(item.start).format(formatTime)} - {moment(item.end).format(formatTime)}</Text>
            : null}
        </TouchableOpacity>

      )}

    </View>
  </Animated.View>
)
</code>
enter image description here
Answer: you could try this lib: https://github.com/computerjazz/react-native-draggable-flatlist
it does exactly what you need.


ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory

Question: How should I solve this error in Ubuntu16.04?
    import cv2
  File "/opt/conda/envs/pytorch-py3.6/lib/python3.6/site-packages/cv2/__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory

Comment: At first fix your APT errors, then install `libglib2.0-0` package.
Answer: Try this:
sudo apt-get install libglib2.0-0

Then, run your command again.  If that doesn't do the trick, try this:
sudo apt-get install libglib2.0-0:i386

I'm on a 64-bit computer, but the tool I'm using uses 32-bit.
Comment: You might want to use ... apt-get ...
Answer: Try to install
apt-get install libgtk2.0-dev

worked for me.
Answer: @Janin answer worked for me however I needed to first run apt-get update -y. I assume this is because I was running in a container with perhaps a different version of Ubuntu.
Full solution -
apt-get update -y
apt-get install libglib2.0-0


Utility Knife Blade Tool that is a "Block"

Question: Is there any kind of tool that is a "block" (imagine a sanding block) that accepts utility-knife blades?
Imagine cutting a piece of rigid foam.
And instead of using a straight pencil mark or (blue) snap line, and trying to follow the line with a utility knife.....
You could secure a straight edge (or a level with a bigger edge) 2" from the line, and the "block" would "ride" against the level/straight edge...and the blade being in the center of the block (but 2 inches from the edge) would cut a perfectly straight line.
Whenever I use a utility knife and the straight-edge/level, I still get a little wobbling.
Comment: You'll never get an air-tight joint between the rafters and the pieces of rigid foam. How about leaving a deliberate 1/4" gap, and filling with spray foam?
Comment: You could run your utility knife against a straight edge.  You can also cut it with a circular Saw and a straight edge.
Comment: Hello, and welcome to Stack Exchange. Unfortunately, "shopping" questions are off-topic here. That said, why don't you just run the knife against the straightedge?
Comment: As stated.  I get "wobble".  When I break the rigid foam, that little wobbles throw off the clean break.  I have 3.5 inch thick rigid foam.  I need to cut both sides of the foam and need the (not all the way through) cuts to be perfectly in line with each other.  Also, the cut pieces are going in between rafters, so to prevent any air passage, I need a really clean cut.  Using table saw causes too much nasty dust.  Thanks.
Comment: Try a jig saw with a long blade or google hot wire foam cutting
Comment: Thanks Kris.  With your tips, I (eventually) came across this.  https://www.youtube.com/watch?v=1j0UurpIKAA&feature=related  (which is an electrical knife mounted upside down in a router table)
Answer: They make a handy sliding block with a blade that protrudes from the bottom, just like you describe. They are great for scoring and cutting thin sheet material like laminate:

Comment: YES!  I knew I'd seen it at some point.


Black wire x3, white wire x3, ground wire x3.

Question: I took out a ceiling fan in a bedroom. I didn't pay much attention to how it was wired up because I've replaced 5 ceiling lights in the house previously and they've been without issue. My issue on this one is I have 3 black, whites, and grounds coming out. So I figured I'd hook them all together to the single black, white and ground in my ceiling light and they would work. So I do this, restore power at the breaker and go to the bedroom,  flip the switch and blow the breaker. I've also noticed if I throw the switch to the ceiling fan in my master it will also blow the breaker.  I've has no previous problems until removing this ceiling fan. Electrical is not my strong suite. I do have an ohm meter, but not exactly sure what to do with it...
Comment: `Electrical is not my strong suite` .... that knowledge should be the incentive to take pictures before you disconnect anything  ..... is there any way that you can figure out how everything was originally connected? .... look at the length of wires and how they are curved
Comment: Unfortunately there is no way to tell. The old fan is gone as well..
Comment: Take pictures of the inside of the junction box, as well as any switch boxes. How was the old fan controlled, switch or remote, and were the fan and light separate switches?
Comment: Controlled by 1 light switch, controls for light and fan were on the fan itself. Not separate on wall.
Comment: Can you post photos of the insides of both boxes please?
Comment: Pro tip, when you change fixtures, **only mess with the wires that go to the old thing**. At least one of those bundles, possibly two, *did not* have any wires from the fan going to it.    You should not have touched that/those bundles with a 10 foot pole.
Answer: This answer is brought to you by the term Switch Loop.
You're thinking "Oh, they must be color-coded".  They can't be color coded because Every cable in every house in North America looks exactly like this.  Black white bare.  Bare is reserved for safety ground, so it doesn't even count!

A light has 3 wire functions:  1. Always-hot.  2. Switched-hot (hot when the lamp is desired to be on). 3. Neutral (the current return for all loads).  You can't code 3 different wire functions when all your wire is the same 2 colors! (ground can never be used to carry power).
This is why I own 10 colors of electrical tape. So I can tape wires by function. Neutral must be white; I prefer black for always-hot and red for switched-hot.

I trust you have googled "switch loop".  That's one of your 3 cables.  The two wire functions are always-hot and switched-hot, and obviously, at least one of them has a misleading color!   (white is allowed to be things other than neutral- sure be nice if someone had taped it like I do!)
The other two cables are supply; and power onward to other outlets.  In both these cables, the wire functions are always-hot and neutral.  Since neutral is present, it must be white.
Your next step is figure out which of the 3 cables coming into your box is the switch loop.   Separate and cap them all, and turn power on.

The black wire that lights up a voltage tester, that is your supply cable.   One down.

Now if you notice, somewhere in your house something else has lost power. Go find it.  Put a load of some kind on it so you can tell when it comes back.

Turn off the power, and pick either unidentified cable.  Nut its black to the supply cable's black. Nut its white to the supply cable's white.  TURN OFF THE SWITCH. (the third cable will be disconnected) Turn the power back on and see if the thing that had lost power has it back on again.  If it does, that cable you just nutted is the onward power cable.
What remains is the switch loop.  You can confirm this with an ohmmeter with the power off; near 0 ohms with switch on, infinity with switch off.  Open up the switch.  Get some RED electrical tape.  Get access to the white wire at both ends, and wrap both ends with red tape to mark it as  switched-hot.  Do the same to the "hot" (non-white) wire on your fan or light.

Now thanks to the tape, you are color coded, and you can match "like color" to "like color" with wirenuts.


Is it possible that isIdleTimerDisabled is ignored in some occasions?

Question: Is it possible that even when isIdleTimerDisabled is set to true, it could still be ignored under certain circumstances? For instance, if the device is in Low Power Mode (e.g., when ProcessInfo.processInfo.isLowPowerModeEnabled returns true), could the screen still turn off despite setting isIdleTimerDisabled to true in the AppDelegate?
I have received feedback from some users that the app screen shuts down after some time (there was no incoming phone calls during that time). However, it is difficult for me to reproduce the issue. So my question is, could the screen turn off if isIdleTimerDisabled is set to true?
Answer: Yes. Turning on Low Power Mode forces autolock after 30 sec. I have tested this on my phone with an example app. The observed behaviour is:
When isIdleTimerDisabled set to true and low battery is on

iPhone is connected to charger -> screen will not turn of after 30 sec
iPhone is on battery -> screen will turn off after 30 sec
Comment: Its strange, cause for me when I set idle timer to false, it works even on Low Battery mode without the charger. Is this documented somewhere?


Parsing multiple subcommands at once using parse_known_args

Question: import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='config command help')

# create parser for config command
parser_config = subparsers.add_parser('config', help='config help')
parser_config.add_argument('--configname', required=True, nargs=1)
parser_config.add_argument('--login', required=True, nargs=1)
parser_config.add_argument('--password', required=True, nargs=1)

parser_config1 = subparsers.add_parser('config1', help='config help')
parser_config1.add_argument('--configname', required=True, nargs=1)
parser_config1.add_argument('--login', required=True, nargs=1)
parser_config1.add_argument('--password', required=True, nargs=1)

rest = 'config --configname name1 --login abc1 --password def1 config1 --configname name2 --login abc2 --password def2'.split()

print(rest)
while rest:
        args,rest =  parser.parse_known_args(rest)
        argslist.append(args)
        print(args, rest)

Gives:
$ python3 create_config.py
['config', '--configname', 'name1', '--login', 'abc1', '--password', 'def1', 'config1', '--configname', 'name2', '--login', 'abc2', '--password', 'def2']
Namespace(configname=['name2'], login=['abc2'], password=['def2']) ['config1'] [Namespace(configname=['name2'], login=['abc2'], password=['def2'])]
usage: create_config.py config1 [-h] --configname CONFIGNAME --login LOGIN
                                --password PASSWORD
create_config.py config1: error: the following arguments are required: --configname, --login, --password

I was hoping to see
['config', '--configname', 'name1', '--login', 'abc1', '--password', 'def1', 'config1', '--configname', 'name2', '--login', 'abc2', '--password', 'def2']
Namespace(configname=['name1'], login=['abc1'], password=['def1']) ['config1', '--configname', 'name2', '--login', 'abc2', '--password', 'def2']
Namespace(configname=['name2'], login=['abc2'], password=['def2']) []

How can I accomplish this ?
Answer: The config subparser gets:
['--configname', 'name1', '--login', 'abc1', '--password', 'def1', 'config1', '--configname', 'name2', '--login', 'abc2', '--password', 'def2']

It parses
['--configname', 'name1', '--login', 'abc1', '--password', 'def1']

as expected.  It then sees config1, which it can't handle (no positionals).  It puts that in the extras list, and continues to parse the rest
['--configname', 'name2', '--login', 'abc2', '--password', 'def2']

That overwrites the previous optional's values, which is what you end up seeing in the args.
I think that if the two subparsers took different flags, then this approach would work.  I think issues like this were explored in the links to your previous question, but I'd have to study them to be sure.
Anyways, parse_known_args doesn't just quit when it encounters a string it can't parse.  Like the regular parse_args it tries to handle the whole list, only it returns leftovers as a list rather than raise an error.  And repeated optionals are allowed, even if they don't don't anything useful (unless defined as append actions).
Comment: I have been looking for a way to correctly handle such argument parsing. I will further look at other answers in the links provided. Thanks


Averaging Coin Tosses with Accumulator C++

Question: This is the problem I am working with
Using a loop and rand(), simulate a coin toss 10000 times
Calculate the difference between heads and tails.
Wrap the above two lines in another loop, which loops 1000 times.
Use an accumulator to sum up the differences
Calculate and display the average difference between the number of heads and tails.
The accumulator is not working the way I want It to? Very much a C++ Noob, for homework lol. Anyone help please?
Why am I using rand()????
second part of the assignment has us using the newer method (mt19937), just trying to tackle this bit first before moving on.
#include <iostream>
using namespace std;
int main() {

int heads = 0, tails = 0, num, total = 0;

srand(time(NULL));

for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
    for (int i = 0; i < 10000; i++) // COIN TOSS
    {

            int random = rand() % 2;

        if (random == 0)
        {
        heads++;
        }
        else
        {
        tails++;
        }

    }

    cout << abs((heads++ - tails++));
    cin >> num;
    total =+ num;

}
cout << "The average distance between is " << total / 1000 << endl;

cin.get();
return 0;
}

Comment: Why the `++` in this line: `cout << abs((heads++ - tails++));`? And why the `std::cin`? Taking input from the user seems very unnecessary. Also, the integer division at `total / 1000` will likely give you bad results.
Comment: Please challenge your instructor as to why they are still teaching the use of `rand()` when it's been [known to be harmful](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) for almost a decade.
Comment: @Casey 2nd part of the assignment was to do it with the new random device method. should've mentioned that. literally had the link in his instructions
Comment: That's amazing! An educator that keeps up-to-date!
Answer: With your code, you never actually save the values that you need. And there's some unnecessary arithmetic that would throw off your results. This line:
cout << abs((heads++ - tails++)); increments the heads and tails variables, but they shouldn't be.
The next two lines make no sense. Why do you need to get a number from the user, and why do you add that number to your total?
Finally, this expression: total / 1000 performs integer division, which will throw off your results.
Those are the immediate issues I can spot in your code.
Next, we move on to your problem statement. What is an accumulator? To me, it sounds like you're supposed to have a class? It also reminds me of std::accumulate, but if that's what you intended, it would have said as much. Also, std::accumulate would require storing results, and that's not really necessary for this program. The code below performs the main task, i.e. it runs the necessary simulations and tracks results.
You'll notice I don't bother counting tails. The big average is also calculated as it goes since the total number of simulations is known ahead of time.
#include <cmath>
#include <iostream>
#include <random>

int flip_coin() {
  static std::mt19937 prng(std::random_device{}());
  static std::uniform_int_distribution<int> flip(0, 1);

  return flip(prng);
}

int main() {
  constexpr int tosses = 10'000;
  constexpr int simulations = 1'000;
  double diffAvg = 0.0;

  for (int i = 0; i < simulations; ++i) {
    int heads = 0;
    for (int j = 0; j < tosses; ++j) {
      if (flip_coin()) {
        ++heads;
      }
    }
    diffAvg +=
        std::abs(heads - (tosses - heads)) / static_cast<double>(simulations);
  }

  std::cout << "The average heads/tails diff is: " << diffAvg << '\n';

  return 0;
}

Comment: Just regular variable naming.
Comment: Here's a citation from the [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es9-avoid-all_caps-names)
Comment: Small nitpick: naming constants with all caps is no longer considered good practice because of clashes with macros.
Comment: That's the first I'm hearing of that, but it makes sense. Probably hasn't affected me because I go out of my way to avoid macros. Is there some alternative for constants, or just regular variable naming?
Answer: What I ended up doing that seems to work for **THIS VERSION WITH RAND() (using the new method later) **
#include <iostream>
using namespace std;

int main()
{
int heads = 0, tails = 0, total = 0;

srand(time(NULL));

for (int h = 0; h < 1000; h++) // Loop Coin Toss
{
    {
        for (int i = 0; i < 10000; ++i) // COIN TOSS
            if (rand() % 2 == 0)
                ++heads;
            else
                ++tails;

        total += abs(heads - tails);
    }
}
cout << "The average distance between is " << total / 1000.0 << '\n';

cin.get();
return 0;

}


$_POST is not being set correctly

Question: FRONT END CODE
    <form action="search.php" method="POST">

                        <input type="checkbox" name="search" id="ing1" class="custom" value="Passion Fruit"/>
                        Passion Fruit

                        <input type="checkbox" name="search" id="ing2" class="custom" value="Banana"/>
                        Banana

                        <input type="checkbox" name="search" id="ing3" class="custom" value="Mango"/>
                        Mango

                        <input type="checkbox" name="search" id="ing4" class="custom" value="Orange Juice"/>
                        Orange Juice

                        <input type="checkbox" name="search" id="ing5" class="custom" value="Ice"/>
                        Ice

                        <input type="checkbox" name="search" id="ing6" class="custom" value="Sausages"/>
                        Sausages

                        <input type="checkbox" name="search" id="ing7" class="custom" value="Bacon"/>
                        Bacon

                        <input type="checkbox" name="search" id="ing8" class="custom" value="Eggs"/>
                        Eggs

                        <input type="checkbox" name="search" id="ing9" class="custom" value="Beans"/>
                        Beans

                        <input type="checkbox" name="search" id="ing10" class="custom" value="Milk"/>
                        Milk

    <input type="submit" action="search.php" value="Search For Recipes">
    </form>

PHP CODE
     if (isset($_POST['search'])) {

     $choices = $_POST["search"];
     $count = count($choices);

     echo "
" . $count . "
";
     echo "
" . $choices . "
";

     }

nothing is being returned when i check some boxes so this suggests to me the checkbox is not being picked up correctly :S HELPP!!!! i am making a web app searchable list hence the cod for this
Answer: checkboxes are not radiobuttons. Their names must be different otherwise you're returning only the last one!
If you want to retrieve them all, you have to change every checkbox name from search to search[]. This way, you'll be able to retrieve them all into a single array, located into $_REQUEST['search'] (*)
If, instead, you want to have only one possible selection, change the inputs type from checkbox to radiobutton and keep the current name.
(*) $_REQUEST is a superglobal variable which contains the same values you'll find in $_POST or $_GET. It's the best choice usually to write flexible scripts (you may have to change the form's method and with $_REQUEST you won't have to rewrite the whole PHP script in the back end.
Comment: You can also name the elements.

E.g. "search[1]" allowing you to more easily pull out a value relating to a specific id, etc...
Comment: sure. I often do that too in more complex forms. I think that's better to start with the basics for now and for this problem, at least. Thanks for the heads up. :)
Comment: I don't think OP wants only one selection, then there are no reason for counting number of choices. +1 for issuing the problem and explaining it well.
Comment: Comment was aimed more as additional info for the OP on top of this answer. Didn't think it warranted it's own answer :).
Answer: Instead of name="search" you could use name="search[]", that way, when $_POST is populated in PHP, it creates an array of values. What you have now just takes one of the elements, because all of their names are the same.
Answer: I think what you want to do is get your results in an array because I can see you are trying to execute :
$choices = $_POST["search"];
$count = count($choices);

If you want this to work, you'll have to change the name attribute for your input elements.
Try giving them a name in this format:
<input type="checkbox" id="ing1" name="search[]" .../>
<input type="checkbox" id="ing2" name="search[]" .../>
<input type="checkbox" id="ing3" name="search[]" .../>

I'm fairly sure that the issues you are facing are because multiple elements share the same name so their values are being overridden.

If you'd like your results to be in an associative array that will let you access each element individually and by name, you could pace the value of the id attribute inside the name attribute as well - like this:
<input type="checkbox" id="ing1" name="search[ing1]" .../>
<input type="checkbox" id="ing2" name="search[ing2]" .../>
<input type="checkbox" id="ing3" name="search[ing3]" .../>

Now you'll be able to access the elements like this:
$_POST["search"]['ing1']
$_POST["search"]['ing2']
...

Answer: Try to name all your checkboxes:
<input type="checkbox" name="search[]" ...

into the php
if (isset($_POST['search'])) {
    print_r($_POST['search']);die();
}

Comment: Just to make sure he gets the structure of the variable.
Comment: die() only makes sure that the PHP stops executing. But that would happen anyway in OP's case?
Comment: It stop executing so the developer can see the structure of the variable and then can see how to access the values and remove it to implement the rest properly, it is there just for debugging purpose.
Answer: change the name of the checkbox "search" with "search[]" also remove the action attribute from submit button.
Answer: Instead of name="search" you need to write name="search[]", so that PHP can fetch the values from the Array.
index.php
<form action="search.php" method="POST">

                        <input type="checkbox" name="search[]" id="ing1" class="custom" value="Passion Fruit"/>
                        Passion Fruit

                        <input type="checkbox" name="search[]" id="ing2" class="custom" value="Banana"/>
                        Banana

                        <input type="checkbox" name="search[]" id="ing3" class="custom" value="Mango"/>
                        Mango

                        <input type="checkbox" name="search[]" id="ing4" class="custom" value="Orange Juice"/>
                        Orange Juice

                        <input type="checkbox" name="search[]" id="ing5" class="custom" value="Ice"/>
                        Ice

                        <input type="checkbox" name="search[]" id="ing6" class="custom" value="Sausages"/>
                        Sausages

                        <input type="checkbox" name="search[]" id="ing7" class="custom" value="Bacon"/>
                        Bacon

                        <input type="checkbox" name="search[]" id="ing8" class="custom" value="Eggs"/>
                        Eggs

                        <input type="checkbox" name="search[]" id="ing9" class="custom" value="Beans"/>
                        Beans

                        <input type="checkbox" name="search[]" id="ing10" class="custom" value="Milk"/>
                        Milk

    <input type="submit" value="Search For Recipes">
    </form>

search.php
if (isset($_POST['search'])) {

 $choices = "";
 $count   = count($_POST["search"]);

 for($i=0;$i<$count;$i++) {

     $choices .= $_POST["search"][$i] . " ";
 }

 echo "
" . $count . "
";
 echo "
" . $choices . "
";

 }

Comment: Tryed this and it returns nothing. using local host via xammp
Comment: @user2346125 please double check the code and run it again. It's running good in my localhost...
Answer: Answers has been given to change the name of element from search to search[] and that is of course correct, but take a look at your php-code as well:
 if (isset($_POST['search'])) {

 $choices = $_POST["search"];
 $count = count($choices);

 echo "
" . $count . "
";
 echo "
" . $choices . "
";

 }

I believe what you want is list the items being selected, then you could iterate the choices in a foreach-loop like this: Note that I'm using H2 instead of H1 because using several H1's on a html-page would not validate correctly. (Of course you could a span or something else, it's just an example)
 if (isset($_POST['search'])) {

 $choices = $_POST["search"];
 $count = count($choices);

 echo "
" . $count . "
";

 foreach($choices as $choice) {
  echo "
" . $choice . "
";
 }

 }

Instead of making checkboxes like you do I would put all item into an array and then do an iteratation to create the
-tags with its contents. (because it's more flexible and you don't have to rewrite same thing over and over again)
The code would look something like this:
<form action="search.php" method="POST">

<?php
$ingredientsArray = array('Passion Fruit', 'Banana', 'Mango', 'Orange Juice', 'Ice', 'Sausages', 'Bacon', 'Eggs', 'Beans', 'Milk');

$cnt = 0;
foreach($ingredientsArray as $ingredient) {
    $cnt++;
    echo '
';
    echo '<input type="checkbox" name="search[]" id="ing' . $cnt . '" class="custom" value="' . $ingredient. '"/>';
    echo '' . $ingredient. '';
    echo '
';
}
?>

<input type="submit" value="Search For Recipes">
</form>

Comment: why `action="search.php"` attribute in submit button?
Comment: @6339 - no of course, that's not necessary. Thanks! (I just copied that part of the html from OP) I've deleted that part.

$_POST is not being set correctly


How I can Assign specific values to the array?

Question: How can I store all the divisors in the array a ??
this program shows the divisors of a number and then decide if it's prime and/or perfect ... The problem is I can't store the values of the divisors in the array a.
<code>#include <stdio.h>
#include <stdlib.h>

int main()
{   int DivCount=0,n,i,j,a[100],sum=0;

    printf("Please Enter the Number : ");
    scanf("%d",&n);

    for(i=1;i<=n;i++)
    if (n%i==0){
            a[i-1]=i;
              DivCount++;
                }

    printf("\nThe Number Has %d divisors : ",DivCount);
    for(i=0;i<DivCount;i++)
    printf("%d\t",a[i]);

    if (DivCount==2)
        printf("\nThe Number is Prime");
    else
        printf("\nThe Number is NOT Prime");

     for(i=0;i<DivCount;i++)
        sum+=a[i];
     printf("\nThe Sum of the divisors is :%d",sum);

    if (sum==n)
        printf("\nThe Number is Perfect");
    else
        printf("\nThe Number is NOT Perfect");

    return 0;
}
</code>
for example (n=6) the array should be = {1,2,3,6}
Comment: `a[i-1]=i;` is major problem. Use another variable for array indexing and thus keep count of divisors. For ex: `a[divisor_count++] = i;`
Comment: OT:  for ease of readability and understanding: 1) follow the axiom: *only one statement per line and (at most) one variable declaration per statement.*  2)  do not omit optional braces '{' and '}'
Answer: <code>#include <stdio.h>
#include <stdlib.h>

int main()
{   int DivCount=0,n,i,j,a[100],sum=0;

    printf("Please Enter the Number : ");
    scanf("%d",&n);

    for(i=1;i<=n;i++)
    if (n%i==0){

        //a[i-1]=i;  <--- check this
        a[DivCount]=i;
        DivCount++;
    }

    printf("\nThe Number Has %d divisors : ",DivCount);
    for(i=0;i<DivCount;i++)
    printf("%d\t",a[i]);

    if (DivCount==2)
        printf("\nThe Number is Prime");
    else
        printf("\nThe Number is NOT Prime");

     for(i=0;i<DivCount;i++)
        sum+=a[i];
     printf("\nThe Sum of the divisors is :%d",sum);

    if (sum==n)
        printf("\nThe Number is Perfect");
    else
        printf("\nThe Number is NOT Perfect");

    return 0;
}
</code>


How to make a child process survive service shutdown?

Question: script1.py:
#do somthing
os.system('nohup python3 -u script2.py {} {} >> {}.out &'.format(xxx, yyy, zzz))
#do somthing

script2.py:
this scipt always run with loop.run_forever()
When script1 run as a service, this script runs script2 correctly.
But if i kill Script1 with 'kill pid' command, Script2 will also be killed automatically, which I do not want and I want Script2 to continue working.
Edit: I use systemd for running script1.py
Comment: Which specific process supervision system are you using? If it's systemd, f/e, there are configurable options about how children get killed. If whatever process supervision system you're using is shutting down the whole cgroup, `nohup` doesn't do anything to switch cgroups, so there you are.
Comment: BTW, using `os.system` is generally frowned on -- the `subprocess` module is a strict superset: It can do everything `os.system` can and much, _much_ more (including, importantly, not invoking a shell; the code above is prone to serious security problems if `xxx`, `yyy` or `zzz` are user-controlled; to fix that while still using a shell you'd need to substitute in `shlex.quote(xxx)`, not just `xxx`).
Comment: @charles-duffy Hi thanks, so I do with subprocess.
And about my problem, I use systemd
Can you explain more fully what I should do?
Comment: See the `KillMode` option in systemd. Setting it to `process` is the most conservative choice, in terms of approaches least likely to kill things other than your process yourself. If you edit the detail that you're using systemd into your question, I'll add that as an answer.
Comment: Thanks, I edited
Answer: If you want child processes you start to not be killed by systemd, change the KillMode configured for your service. Thus, in your service file:
[Service]
KillMode=process

The default value is KillMode=control-group, such that systemd kills everything in the cgroup it created for the service; and nohup doesn't know anything about cgroups.


How to delete file from directory using vb.net?

Question: I have a asp.net website folder namely Website3 inside website3 folder there is a upload folder. I want to delete files inside upload folder on button click event.
MY directory status :
Website3 > upload

I'm using the following command but it doesn't delete the file from upload directory
Protected Sub ListView1_ItemDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewDeletedEventArgs) Handles ListView1.ItemDeleted
        Dim lab As Label = CType(ListView1.Items(ListView1.SelectedValue).FindControl("photoLabel"), Label)
        System.IO.File.Delete(System.IO.Path.GetDirectoryName("/upload/") & lab.Text)
    End Sub

Answer: You should be using Server.MapPath
File.Delete((MapPath(".") + ("\\" + lab.Text)))

Answer: Just try this:
Public Function DelAllUploadedFiles()
For Each Uploadedfiles As var In System.IO.Directory.GetFiles(Server.MapPath("~/upload/"))
System.IO.File.Delete(Uploadedfiles )
Next
End Function

Answer: Try to put try and catch and see if you have
Exception . In general in order to delete in IIS process pool ,should be defined under strong user .
Answer: First you have to set the folder settings on the server
who can enter this folder and has delete authority
Login to your server account and give delete permission to the folder to everyone


How to separate a package into modules? (Like Firebase SDK)

Question: If you download Firebase JS SDK you only need to add one dependency:
firebase
From there you can access all different modules based on your import attributes:
import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';

And then any library that won't be used is automatically removed if you use any tree-shaking tool.
How can I achieve something similar?
I'm looking to build a collection of packages for our organization so that, instead of having everyone working and updating 15 packages, having a single package that can be divided into modules/imports so a project only imports the necessary modules.
I have been looking for some days and I don't even know how to name this approach.
Could anyone link me to a tutorial, a document or anything to be able to start my investigation?
Answer: If you check out the Firebase JS SDK repository, you can see that they use a monorepo to manage all of this, and they are actually all separate packages. They use Lerna to manage their monorepo - but there are several monorepo tools out there (npm workspaces, yarn). I like npm workspaces myself since it's native.
What they do is they make heavy use of exported modules in npm. You can see the documentation for that here: https://nodejs.org/api/packages.html#exports
So they have a repository that looks vaguely like this:
my-project
├── packages
│   ├── pkg-1
│   │   ├── package.json
│   │   └── index.js
│.  ├── pkg-2
│   │   ├── package.json
│   │   └── index.js
│   └── all
│.      ├── pkg-1
│       │   └── index.js
│.      ├── pkg-2
│       │   └── index.js
│       ├── package.json
│       └── index.js
└── package.json

The key part of the root package.json is the declaration of packages:
{
  ...
  packages: [
    "packages/*",
  ],
  ...
}

Sample package.json from a package:
{
  "name": "@my-project/pkg-1",
  "main": "index.js",
  ...
}

The trick here is where they have an extra package which just exports all of the other packages in the repo:
my-project/packages/all/package.json:
{
  "name": "my-project"
  "exports": {
    "./pkg-1": "./pkg-1/index.js",
    "./pkg-2": "./pkg-2/index.js",
  }
  "dependencies": [
    "@my-project/pkg-1": "*",
    "@my-project/pkg-2": "*",
  ],
  ...
}

example /my-project/packages/all/pkg-1/index.js:
export * from "@my-project/pkg-1"

Now when someone tries to install your package all, they will get all of the other packages aliased.
import * as pkg1 from "all/pkg-1"

They also bundle together ES modules and CommonJS so you can use "import" or "require". Take a long hard look at their package.json files in their repository, it's a work of art! https://github.com/firebase/firebase-js-sdk
Answer: TLDR; In your package.json add the files property.  This will expose the directories that you specify.  This will also make them accessible by path as you seek.
{
  "name": "mybase",
  "main": "index.js",
  "files": ["app/**", "store/**"]
}

With a config like above you would be able to access a file like this:
import { initializeApp } from 'mybase/app';
import { getFirestore, collection, getDocs } from 'mybase/store/lite';

Just make sure that the files exist as @KaKi87 mentioned.  Specifying the files property in your package.json is key to exposing your file structure to client apps.
Answer: There's nothing particular to do : it's just natural.
For example, the following structure :
foo
├── bar
│   ├── baz
│   │   └── index.js
│   └── index.js
├── fum
│   ├── index.js
│   └── qux
│       └── index.js
├── index.js
└── package.json

Allows the following usage :
import foo from './foo';
import foobar from './foo/bar';
import foobarbaz from './foo/bar/baz';
import foofum from './foo/fum';
import foofumqux from './foo/fum/qux';

For testing purposes, consider each js file exports a string containing the concatenated value of all its parent folder names, e.g. ./foo/bar/baz/index.js contains export default 'foobarbaz';, while package.json contains { "type": "module" }.
Then, the following code :
console.log({
    foo,
    foobar,
    foobarbaz,
    foofum,
    foofumqux
});

Outputs :
{
  foo: 'foo',
  foobar: 'foobar',
  foobarbaz: 'foobarbaz',
  foofum: 'foofum',
  foofumqux: 'foofumqux'
}

Comment: I'm afraid this is not what I meant. The idea is that if you *export this as a package* people can import the different modules without having to import other modules. In your case you would be exporting everything directly from your index file and not the sub indexes.
Comment: I used `export default 'foobarbaz';` for demonstration purposes but I could have used `export const foobarbaz = 'foobarbaz'` and `import { foobarbaz } from './foo/bar/baz/index.js'` instead, if that's what you meant. If not, sorry I didn't get it
Comment: But if you import this from a different project you can not simply do `import {foofumqux} from 'foo/fum/qux'`. My question goes strictly to using this project as a package in a different project.
Comment: Yes you can, it works exactly the same way.


Forward uploaded file from a service to another service

Question: I'm trying to create a REST API with ExpressJS that accept an image and pass it to another service (with a POST request) which is in charge to perform some operations (resize, etc..) and store into an AWS S3. I know that the same solution can be easily done with a Lambda Function directly but I have a K8s and I want to make worth it.
All components are already working with the exception of the service that forward the image to the second service.
The idea that I've found on internet is using a stream, but I got the exception Error: Expected a stream at Object.getStream [as default]
How can I solve that? Is the right practice or there is a better solution to achieve the same result?
const headers = req.headers;
const files: any = req.files

const filename = files[0].originalname;
const buffer = await getStream(files[0].stream)
const formFile = new FormData();
formFile.append('image', buffer, filename);

headers['Content-Type'] = 'multipart/form-data';
axios.post("http://localhost:1401/content/image/test/upload/", formFile, {
            headers: headers,
        })
        .catch((error) => {
          const { status, data } = error.response;
          res.status(status).send(data);
})

Answer: I've found a solution that I post here for those who'll have the same problem.
Install form-data on node:
yarn add form-data

Then in your controller:
const headers = req.headers;
const files: any = req.files
const formFile = new FormData();

files.forEach((file: any) => {
 const filename = file.originalname;
 const buffer = file.buffer
 formFile.append('image', buffer, filename);
})
// set the correct header otherwise it won't work
headers["content-type"] = `multipart/form-data;  boundary=${formFile.getBoundary()}`

// now you can send the image to the second service
axios.post("http://localhost:1401/content/image/test/upload/", formFile, {
headers: headers,
})
.then((r : any) => {

  res.sendStatus(r.status).end()

})
.catch((error) => {
  const { status, data } = error.response;
  res.status(status).send(data);
})


Xubuntu: "desktop-file-utils" stopped being able to be installed

Question: After doing some package installs, the desktop-file-utils package is now failing to be installed via apt and aptitude. This is for Xubuntu 20.04.2.
When running apt, I now always get this error:
dpkg: error processing package desktop-file-utils (--configure):
 installed desktop-file-utils package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 desktop-file-utils

I know that I can purge this package, but then quite a few of its dependencies will also be uninstalled, and my system is likely to become unusable.
I don't understand what could have caused this problem, because I don't know what I could have done to affect this package.
Is there some way to fix this other than purging desktop-file-utils and making my system unusable? Also, is there some way where I can get more detailed information about exactly how the post-installation script is failing? If so, perhaps I could debug this.
Thank you in advance for any suggestions.
Comment: Are you able to `apt install --reinstall` the package?
Comment: @matigo That will more likely fail. My answer explains this in detail.
Comment: Before doing the purge, would marking the dependencies as being manually installed prevent them from being removed with the purge?  `apt-mark manual pkg1 pkg2 etc`
Answer: Let's fix this error step by step.

First, run force install to know the exact problem:
sudo apt --fix-broken install

Identify the error:
Errors were encountered while processing:
desktop-file-utils

Mark dependencies as manually installed to prevent them from getting removed;
 sudo apt-mark manual libglib2.0-0 libc6

Remove the post-installation files:
sudo mv /var/lib/dpkg/info/desktop-file-utils* ~/

Purge the package:
sudo dpkg -P --force-all desktop-file-utils

Re-install the package (Optional):
sudo aptitude -f install desktop-file-utils

Explanation
As the error message states:
installed desktop-file-utils package post-installation script subprocess returned error exit status 1

This usually implies that there are transient issues in the post-installation files.

In the first step, we executed a command that attempted to correct the mistakes.

In step three, we deleted the package's post-installation files.

We purged the package in step four to remove any configuration files.

In step five, we reinstalled the package to make sure it didn't break any other packages.
Comment: Thank you, but in the recent past with a different package, I did a purge like this, and not only did the `official` Ubuntu dependencies get wiped out after the purge, but also, there were other dependencies that came from packages that I added from from other repos, and they got wiped out, also. I know for a fact that there are other such packages that I have added from other repos which are dependencies of `desktop-file-utils` directly. I will carefully find all of those and mark them as `manual` before I go forward with this. Thank you for all your help!
Comment: Thank you very much. However, as I mentioned in my original post, purging the package will also uninstall numerous dependencies, and this could render my OS unusable. I am trying to see if I can fix this without purging.
Comment: PS: Is there a different option, other than `--force-all` which will only purge the one package and not uninstall any of its dependencies?
Comment: @HippoMan You can try: `dpkg -r` without force-all
Comment: @HippoMan See the edit
Comment: Oh, so are you saying that after Step 5 and before Step 6, the only package which will be uninstalled would be `desktop-file-utils` and not any of its dependencies? If so, then I see that this would indeed be a "safe" way to deal with this problem.
Comment: Oh ... I'm sorry ... I missed step 3 in the edit. So ... I have to figure out all of the dependencies and then mark them as being manually installed; then, they won't be uninstalled during the purge. That raises the question of how to get an accurate list of dependencies, but perhaps I can figure that out.
Comment: @HippoMan I've already added all the dependencies in my answer.
Comment: In `aptitude`, a much longer list of dependencies is shown to me.
Comment: @HippoMan I believe those packages are further dependencies of the listed packages. I saw that on the Official Ubuntu package search. Thus, marking the packages as manual will mark all packages as manual.
Answer: It turns out that this has nothing to do with packages nor with the apt system.
I discovered that I had accidentally set XDG_DATA_DIRS to point to a non-existent directory.
Once I fixed this, the problem went away.
Here are more details as to why this fixed the problem ...
These are the contents of /var/lib/dpkg/info/desktop-file-utils.postinst ...
#!/bin/sh

set -e

update-desktop-database -q

if [ "$1" = "triggered" ]; then
    exit 0
fi

I ran update-desktop-database -q from the command line, and it didn't give any output, but it exited with a non-zero return code.
I ran it again like this: update-desktop-database -v. This time, it gave an error message which stated that the applications subdirectory of the path that is contained in XDG_DATA_DIRS didn't exist. This showed me that I had set XDG_DATA_DIRS incorrectly.
Once I reset XDG_DATA_DIRS to a proper value, the update-desktop-database command started exiting with a zero return code, and the desktop-file-utils error in apt that I mentioned above stopped occurring.


How to use named parameters in a native spring-data @Query?

Question: I'm trying to set up a db query using spring-data-jpa and a native query for a postgres database. But the following does not work. Why?
@Query(value = "SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = 'public.my_table'::regclass", nativeQuery = true)
public int count();

Result:
java.lang.IllegalArgumentException: org.hibernate.QueryException: Not all named parameters have been set: [:bigint, :regclass;]

Answer: Found it: the :: have to be escaped like \\:\\:


How to change the text of a specific button in Python

Question: I'm using tkinter and this problem bothers me a lot.
My goal:

Create several buttons
When clicking a specific button, change the text shown on that button

I tried the codes below, but no matter what button I clicked, only the last one got changed.
import tkinter as tk

list1 = []

def update_btn_text(index):
   list1[index].set('new')

for i in range(10):
   btn_text = tk.StringVar()
   list1.append(btn_text)
   btn = tk.Button(root, textvariable=list1[i], command=lambda: update_btn_text(i))
   btn_text.set('button' + str(i+1))
   btn.pack()

root.mainloop()

I guess the problem is because of the i value, but how can I fix it?
Thanks a lot!
Answer: You have to create a local variable for every iteration and pass it as a value in updatd_btn_text()
command=lambda i=i: update_btn_text(i)

Also you could try this for configuring text of the button
def update_btn_text(index,button):
   button.config(text=list1[index])

for i in range(10):
   btn = tk.Button(root)
   btn.pack()
   btn.config (command=lambda i=i, btn=btn: update_btn_text(i, btn))

Comment: @zhmff no problem. Consider accepting the answer :)


Can't install Xamarin.Firebase.Common on shared Xamarin project

Question: Is the package Xamarin.Firebase.Common supposed to be able to get installed on the shared Xamarin project?
I try to install it, but I get an error:

Error NU1202  Package Xamarin.Firebase.Common 22.214.171.124 is not
compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package
Xamarin.Firebase.Common 126.96.36.199 supports:

monoandroid12.0 (MonoAndroid,Version=v12.0)
net6.0-android31.0 (.NETCoreApp,Version=v6.0)

Both Target Framework and Target Android Version are set to Android 13 for the Android project.
Comment: No, it's not. "Common" is not a description for a shared cross-platform library but means it contains common classes shared by several other nugets for Firebase. You need to install this into your Android project.
Comment: What am I supposed to install to the shared project though? I'm trying to use `FirebaseNetworkException` in my code and it's not recognized. Visual Studio suggests to install `Xamarin.Firebase.Common` to fix the error. I have done that already for the Android project. It's not possible for the Shared project.
Comment: You shouldn't have to deal with that in your shared project, because network exceptions are platform specific. Your Xamarin app is hosted inside a native app and thus doesn't know specifics about the platform it's running on. What exactly are you trying to achieve? What do you think you need `FirebaseNetworkException` for?
Comment: Just to deliver a relevant message to the user.
Comment: More context, please. What are you using Firebase for in your app?
Comment: It's Firebase Authentication. There are other exceptions that are also useful to catch, like `WeakPassword` for example. I also use `Plugin.FirebaseAuth`.
Comment: Firebase auth is implemented differently on Android and iOS, there are separate libraries for each, but there are also cross-platform libraries, such as `Plugin.FirebaseAuth`, which handle the platform specifics under the hood, but they essentially work in the same way. In any case, you cannot catch the exceptions from the platform specific code from within the shared context. The reason is the direction of the dependencies. Platform specific code depends on shared code, not the other way around. `Plugin.FirebaseAuth` defines a `FirebaseAuthException` with an `ErrorType` field you can use.
Comment: You should update your question and explain what you are *actually* trying to accomplish in the question, because currently, the answer to your *current* question simply is: **no**, you cannot install Xamarin.Firebase.Common into the shared project. Don't forget to include the code where you're trying to catch the exception.
Answer: First of all, you cannot use the Xamarin.Firebase.Common package, which has a dependency on Android, in the shared project of your Xamarin.Forms app.
Secondly, you cannot use native exceptions in the shared, cross-platform context. Therefore, you won't have access to FirebaseNetworkException, etc. in the shared project.
Instead, since you're already using the Plugin.FirebaseAuth, you need to catch FirebaseAuthException instead, which wraps the different platform-specific exceptions and hides them behind error codes.
Your code should be looking something like this:
try
{
    var provider = new OAuthProvider("google.com");
    var result = await CrossFirebaseAuth.Current.Instance.SignInWithProviderAsync(provider);
}
catch (FirebaseAuthException e)
{
    switch(e.ErrorType)
    {
        case ErrorType.NetWork:
            //handle network error
            break;
        case InvalidCredentials:
            //handle invalid credentials
            break;
        //...
        default: break;
    }
}

There's a full list for the mapping of the ErrorType enum to the Firebase exceptions in the documentation.
Therefore, wherever you need to catch an exception, you can check the ErrorType and perform the appropriate operation or show an error message to the user.
Comment: OK. So that's how `ErrorType` can get utilized in the code. Thanks for making it clear!
Answer: Just as ewerspej said, you need to install the Xamarin.Firebase.Common pakcage in the xamarin.forms project's android part.
And then, you can create a class in the android part and use the FirebaseNetworkException in the class's method. After that, you can use the dependency service to call the method in the shared Xamarin project.
For more information, you can refer to the official document about the Xamarin.Forms DependencyService Introduction.
Comment: I see that `Plugin.FirebaseAuth` has `Error Types`: https://github.com/f-miyu/Plugin.FirebaseAuth#firebaseauthexception-error-types These aren't exceptions, so they can't be used in a try-catch block, right? How can they be used though? They probably can be used in the shared project, so there is no need for utilizing the `Dependency Service`.


Grub rescue after converting primary partitions into logical partitions

Question: I have a dual boot system (Ubuntu 18.04 & Windows 10) with 4 primary partitions - the system reserved partition (boot), the windows partition, the ubuntu partition (has /boot, /root, /home, etc) and the swap partition for ubuntu. I want to create another partition (for sharing between windows and ubuntu) and so I need to convert the ubuntu and swap partitions into logical partitions. I did that using fixparts (using this), but on rebooting, I got the grub rescue prompt. While I was able to recover by booting into a live CD and changing the partitions back into primary partitions, I would still like to change the partitions into logical partitions and still have a working system.
What do I need to do here?
Edit 1: More info on UUID
Yes, when I convert the partitions to logical, the UUID does change. After edits with fixparts, when I reload gparted to view the partition information, I don't get an UUID for the partitions at all. I also get this error when I try to get additional information on the partitions:
for /dev/sda5 (the erstwhile primary partition with Ubuntu root, boot etc):
<code>e2label: No such file or directory while trying to open /dev/sda5
Couldn't find valid filesystem superblock.
tune2fs 1.44.1 (24-Mar-2018)
tune2fs: No such file or directory while trying to open /dev/sda5
Couldn't find valid filesystem superblock.
Couldn't find valid filesystem superblock.
dumpe2fs 1.44.1 (24-Mar-2018)
dumpe2fs: No such file or directory while trying to open /dev/sda5
Unable to read the contents of this file system!
Because of this some operations may be unavailable.
The cause might be a missing software package.
The following list of software packages is required for ext4 file system support:  e2fsprogs v1.41+.
</code>
Edit 2:
From here:
"Note that the /boot directory must be located on a filesystem that is supported by GRUB. Not all filesystems are. The function of stage 1.5 is to begin execution with the filesystem drivers necessary to locate the stage 2 files in the /boot filesystem and load the needed drivers. This means that stage 2 of GRUB2 can be located on a standard EXT filesystem but it cannot be located on a logical volume. So the standard location for the stage 2 files is in the /boot filesystem, specifically /boot/grub2."
This seems to imply that I can't convert to logical partition for /boot?
Comment: Did the conversion change the UUID? If so, you may need have needed to reinstall all of grub, so it creates new grub menu and edit fstab with new UUID. I would perhaps just changed swap. You can delete it and delete fstab entry that mounts swap. Then create new extended partition and add swap and shared NTFS. Add new swap using new UUID. Make sure Windows 10 fast start up is off as it sets hibernation flag on all NTFS partitions preventing full use from Ubuntu.
Answer: Grub needs some files in /boot folder of your Linux partition. If you change this partition from primary to logical, you have to reinstall Grub to it find them again. You can use boot-repair or do it manually: https://howtoubuntu.org/how-to-repair-restore-reinstall-grub-2-with-a-ubuntu-live-cd
Comment: Is there a way to backup/restore my grub config before I do this? So that in case things go wrong, I can back out?


php compare dates without year

Question: I'm trying to compare two dates. I've found many threads to this topic, but in every thread there was also a year. What I want to achieve is compare the dates without any year value. Example:
if(31.07 > 16.11) {
    // do stuff
}

I tried the following:
$sDayMonth = date("d.m", strtotime($row["date"]));
$sDateCompare = date("d.m", strtotime("31.07"));

if($sDayMonth > $sDateCompare){
    // do stuff
}

Unfortunately it always executes the code in the if statement. I cannot figure out why. Is this even possible? If yes, what am I doing wrong?
The variable $row is a row returned from SQL database, it contains the correct value.
Comment: Fundamentally, the logic is flawed in that there is no way to establish whether one date falls before or after another unless you add a year. If you always assume "this year", add it to the code, and just compare "strtotime($row['date'] . '.2016') > strtotime('31.07.2016')". But that's quite ugly too.
Comment: Why "d.m" ? "md" could be better
Comment: @markdwhite Well, it's not always the same year. I have to check in which season the date is. E.g. 16.11.2013 is in season "2013/2014" and 04.02.2014 is also in season "2013/2014", but there are two different years. The season break is on 31.07 in every year. You know what I mean? :)
Comment: @Mate Oh, didn't thought about this. But unfortunately it has the same effect. If statement is always executed :/
Comment: Are you just trying to figure out if a date is after April 31st?
Comment: @Mate yes, but I just noticed that `$sDateCompare` is always "0101" instead of "0731"
Comment: @LoganBailey Yes, if a date is after July 31st, it has to execute the code, otherwise ignore the code in the if statement...
Comment: @Tyler I do see what you mean, which would suggest that your approach is flawed. Unless you have the year stored in the DB too, in which case you can use that and still directly compare using strtotime(). Though the DateTime object is the better way to compare dates.
Answer: Why not just pick a constant year which will be used in both dates you're comparing. This way you can still make use of strtotime().
$year = '2000';
$ts1 = strtotime($row["date"] . '.' . $year);
$ts2 = strtotime("31.07." . $year);

if($ts1 > $ts2){
     // do stuff
}

Alternatively, you can concatenate $month and $day in this order. That way you're able to convert these to integer and compare them this way, eg. Aug 11 would be 811 and Nov 30 is 1130 and 1130 > 811.

php compare dates without year


Why is the back of a perspective frustrum larger than the front?

Question: I'm following this tutorial on the perspective projection.
Question: If the point of a perspective projection is to create the perspective effect (where objects faraway appear to be smaller):

then why does it generate a frustrum in which the back is larger than the front? Should it be the other way around?
Answer: It might help to think of it this way:
Both the near plane and the far plane are the size that will fit onto the screen you are viewing on. The further away something is, the bigger it can be and still fit on the screen. Close up, a playing card can fill the whole screen, but in the distance, an entire building can fit on the screen.
Consider the example image:

If a playing card exactly fills the near plane, then you will be able to fit 4 playing cards on the far plane. This reflects the fact that when a playing card is twice as far from the camera, it appears to have half the height and width.
Think of the near plane and the far plane as simply the area that will fit on your screen. The further away you point your camera, the more will fit on the screen. This matches up with the fact that things look smaller in the distance - this means you can fit bigger things on the screen if they are further away.
Answer: It is bigger because it fills the same view and it ts further away. It would be smaller if it wouldn't fill the same view but then it wouldn't fill the camera view and it wouldnt work.
So the inverse relation applies. If you want something to stay constant in size in the view then it needs to grow as it gets further.
Your just comparing apples with oranges.
Answer: if you place your hand by your ear, you can't see it ... now then if you move it forward, suddenly you'll start seeing it ... this is what the frustrum represents, as in your second picture...


How to draw a point on the graph

Question: I am drawing the graph below

with the following code:
start = 0
finish = len(predictions)
pl.plot(predictions[start:finish,0], predictions[start:finish,2], 'bo', label="Predicted")
pl.plot(actual_measurements[start:finish,0], actual_measurements[start:finish,1], 'g^', label="Actual")

The blue circles follow the green triangles to a some point but then start diverging away. That point happens to be the last 60 blue circles (the actual predicted points).
Question
Is there a way I can point out on the plot where the last 60 blue circles begin?
Comment: @Anthony what do want to do, draw a point or to point out? Its not clear what you want to do. You can use `annotate` method of the plot object to 'point out' where the start is.
Comment: if you change last 60 values in `actual_measurements` then last 60 points change position.
Comment: @furas I'm not clear by what you mean. Could you please elaborate
Comment: sorry I'm not clear what you mean in question.
Answer: If you know the point where the two curves a diverging you can just plot this point again e. g. in a different color. Add this at the end of your code:
pl.plot(actual_measurements[finish - 60:finish - 59, 0],
        actual_measurements[finish - 60:finish - 59, 1], 'ro',
        label="Diverging")

If you do not know the point you need some algorithm to determine it.

How to draw a point on the graph