How do I extract make-3.81.tar.gz?

Question: I am new at Linux, and am currently using Ubuntu in a dual-boot with windows 7. I'm trying to install Make such that I can build a program given to me with it. I can SEE the make-3.81.tar.gz, but don't know how to extract it
For reference, I have this file in /host/Linux/Make
EDIT I do not have internet access on this computer
Comment: `make` is available in the official Ubuntu repositories. Run `sudo apt-get install build-essential` to install the basic compiling tools.
Comment: Euhm... Why is the Ubuntu `make` not good enough for you? You really don't want to install GNU make from source, really. Just do `sudo apt-get install make`? or install from Software Centre. Pro tip: install `build-essential` for all build-related tools.
Answer: As already mentioned in the two comments, you do not need to install your own make program, unless you are looking for a particular version or brand. Most of the tools you need to build your programs are already in the main distribution.
Since you do not have internet access from your Ubuntu installation, and I assume that you are downloading your programs from another computer, you need to search for the correct .deb package in the Ubuntu repositories. Since I do not know your system version, I cannot give you a link.
However, if you insist on using the make that you have on your computer, you can either just double-click on the file and then extract the archive, or open a terminal (Ctrl-Alt-T) and type
cd /host/Linux/Make/
tar xzf make-3.81.tar.gz

Answer: This version of make is available in Ubuntu.
How to check whether make is installed or not?
Just type this into the program "terminal" and press enter:
make --version

It will tell you the version of your current installed make or tell you it is not installed.
It's not installed. What now?
What you did was downloading the source code. So apparently you do have internet somewhere else. So just download this file, it's the binary (compiled) version of make from the official Ubuntu repository: https://launchpad.net/ubuntu/+archive/primary/+files/make-doc_3.81-5.1_all.deb
Copy it on your computer, double click on it and click on Install. It's easy!
I really just want to extract this file!
In this case it does not really make sense, but just to give the information:
Extracting in file browser
Right click on the file and click on extract here (or similar, I'm using Ubuntu in german).
Extracting via terminal
use the command cd to go to the correct folder:
cd /host/Linux/Make

and then extract the file:
tar xzf make-3.81.tar.gz

How do I extract make-3.81.tar.gz?


500 Internal Server Error whenever I use apt-get

Question: I'm running ubuntu 12.04
I'm getting a huge number of "500 Internal Server Error" errors whenever I try to apt-get install/upgrade.   aptitude yields exactly the same errors.   I know there are supposed to be "zillions" of threads about this on the web but none of them seem to work for me.  Most of them seem to be related to installing a specific package, but I get the errors whenever I use apt-get or aptitude
I know this is supposed to be a generic error, but there's nothing  in the /var/log/apt folder that provides any information, or even acknowledges the error.   (The only two files in there are term.log and history.log).
As some have recommended, I've modified my /etc/apt/sources.list file so that the top three lines are
deb http://us-west-1.ec2.archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse
deb http://us-west-1.ec2.archive.ubuntu.com/ubuntu/ precise-updates main restricted universe multiverse
deb http://us-west-1.ec2.archive.ubuntu.com/ubuntu/ precise-security main restricted universe multiverse

But these are giving errors as well.
Can anybody please advise based on this information, or suggest how I can get a more informative error description?
Thanks for help in advance
Here are just a few of errors I get from apt-get upgrade
Err http://archive.canonical.com precise/partner amd64 Packages 500  Internal Server Error
Err http://archive.canonical.com precise/partner i386 Packages 500  Internal Server Error
Err http://archive.canonical.com precise/partner Sources 500  Internal Server Error
Err http://dl.google.com stable/main amd64 Packages 500  Internal Server Error
Err http://dl.google.com stable/main i386 Packages 500  Internal Server Error
Err http://extras.ubuntu.com precise/main amd64 Packages 500  Internal Server Error
Err http://extras.ubuntu.com precise/main i386 Packages 500  Internal Server Error
Err http://extras.ubuntu.com precise/main Sources 500  Internal Server Error
Err http://ppa.launchpad.net precise/main amd64 Packages 500  Internal Server Error
Err http://ppa.launchpad.net precise/main i386 Packages 500  Internal Server Error
Err http://ppa.launchpad.net precise/main Sources 500  Internal Server Error
Err http://security.ubuntu.com precise-security/main amd64 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/main i386 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/main Sources 500  Internal Server Error
Err http://security.ubuntu.com precise-security/multiverse amd64 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/multiverse i386 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/multiverse Sources 500  Internal Server Error
Err http://security.ubuntu.com precise-security/restricted amd64 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/restricted i386 Packages 500  Internal Server Error
Err http://security.ubuntu.com precise-security/restricted Sources 500  Internal Server Error
...
Err http://us-west-1.ec2.archive.ubuntu.com precise/main amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/main i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/multiverse amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/multiverse i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/restricted amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise/restricted i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/main amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/main i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/multiverse amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/multiverse i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/restricted amd64 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/restricted i386 Packages 500  Internal Server Error
Err http://us-west-1.ec2.archive.ubuntu.com precise-security/universe amd64 Packages 500  Internal Server Error

~
~
Comment: Have you tried [using another mirror](http://askubuntu.com/questions/104695/how-do-i-change-mirrors-in-ubuntu-server-from-regional-to-main)? (regular one instead of Amazon) The one you're using from Amazon seems to be having some difficulties... An HTTP 5xx error means it's a *server* error (their fault). Also check if you are using a proxy and include that information.
Comment: Ah now I re-read your error output I see it is about multiple domains. It is very likely this is something locally on your machine. I suspect a proxy server configured or some other configuration issue like DNS not working. Please check the output of `grep -ri proxy /etc/apt` and try to download a simple file from the repo, e.g. `wget "http://security.ubuntu.com/ubuntu/dists/precise-security/Release.gpg" -O -` (yes `-O -`).
Comment: @gertvdijk,   Ahhh!  thank you *so* much for your help.     The download was exactly what I needed to diagnose the problem.    A while ago, I'd set an environment variable "http_proxy" to try to get to my univ library.    When I removed the variable, everything worked fine!
Comment: have you run apt-get update?
Comment: Thanks for your responses!  Yep @wlraider70, when I run apt-get update I get *70* Internal server errors, after sorting and uniq'ing.
Comment: Thanks @gertvdijk. I've tried changing mirrors several different ways, like from ubuntu to mirrors.math.ucdavis.edu and using the "deb mirrors" Always the same number of 500 Errors. This suggests to me that the problem is caused by something stupid that I did rather than it being their fault, like changing permissions of something, but I don't know how to debug the error. The only ways I know how to check if I'm using a proxy is to look in apt.conf, which doesn't exist, and .cshrc (I'm using tcsh) but there is no indication that I am.   Is there another way?
Comment: @LeoSimon Glad to hear that you identified and fixed the issue. Please provide this as an answer to your own question. :)
Comment: hello it sometimes might a problem with a source server..  "Software & update"  -> "Ubuntu software" -> "Download from ..." ... try to change the source server here :) (ideally to the main server) or any close to you ..
Answer: So my problem turned out to be that I'd set an environment variable, which was built into my login script.
setenv http_proxy http://proxy.lib.berkeley.edu:7777/proxy.pac

This was a vain attempt to connect to my library, since chrome in it's wisdom doesn't let you set a proxy connection.    (It didn't work).
If apt-get provided any diagnostic output, I'd have figured this out ages ago.   But it doesn't (In future releases it would be great if a verbose option were provided.)
Thanks to help from @gertfdijk, I tried the following
wget "http://security.ubuntu.com/ubuntu/dists/precise-security/Release.gpg"

which provided me with the diagnostics I needed to track down the error.


Connecting a P-trap to a female drain connector in the wall

Question: I am replacing a bathroom vanity and while I'm doing that, I'm also replacing the p-trap for the sink (mostly because I want one with a drain, but also because I have to raise the height a couple inches) . Right now, there is a 1 1/4" female drain connector sticking out of the wall (which takes 1 1/4" I.D. pipe). The old P-trap was made of metal:

My intention was to use a standard 1 1/4" ABS P-trap, however, ABS is 1 1/4" O.D., and the drain connector takes 1 1/4" I.D. The edge of the connector is about 1/8" recessed from the drywall, which will make cutting that piece off and attaching a coupling fairly difficult, though may be possible. I don't want to actually open up the wall (as you can see, I'm already in the process of patching the messy hole someone made for this pipe).
Anyone have any better suggestions?
Comment: take the trap with you to the hardware store, I'm sure somebody there can help you find the proper fitting.  This seems like it would be a common problem, so I'm sure there is a solution available.
Answer: A 1 1/4" female FIP adapter worked perfectly. As soon as I saw it, I was embarassed for not having thought of it earlier.

I used some teflon tape, screwed the FIP adapter onto the adapter coming out of the wall, then just glued my 1 1/4" pipe directly into it. No reduction in pipe sizes, and 100% ABS parts.
Comment: Nice work, we don't get enough 'after' pictures around here.
Answer: I have made the mistake twice of demoing an old bathroom sink and throwing out the p-trap before the new sink and plumbing went in.  Both times I regretted it because when I went to put in the new p-trap, I found some sort of strange/different plumbing setup which required several trips to the hardware store (and me repeating to myself "why did I throw out the old p-trap!?!?").
My recommendation is to use the old p-trap.  Take some rags and steel wool and clean it inside and out and you should be able to get it looking like new. (And while you are at it use some rags to clean out the connector in the wall too since that looks pretty dirty too.)  And then you can get a drain extension tube to raise the height up to your new sink fairly easily.
The only issue is that the distance from the wall of the old p-trap may not match your new sink.  In that case try using part of the old p-trap to attach to the drain in the wall (since you do not have any extra pipe to work with) and then use a coupling to attach your new p-trap to this steel pipe.  (Although not sure how easy it would be for you to find a coupling for you to attach to that steel pipe.)
Comment: A drain in the p-trap is definitely a nice-to-have, but I have always found it easy to take apart a p-trap for retrieving items (especially the ones made of ABS plastic).
Comment: My biggest issue is the lack of a drain in the P-trap. This means if something gets dropped down the drain, there's no retrieving it without taking apart plumbing.
Answer: Best way I've thought of so far is to use a drain tube extension coming out of the connector in the wall, then go into another female trap connector, then P-trap, and then finally female drain connector for the actual sink drain. Biggest downside is the pipe will get narrower between the wall and the p-trap, since it's 1 1/4" OD. On the upside, it'll be easy to take the p-trap off and clean it all out.
Comment: hmmm... would that be up to code?  I am not sure a tube extension on the smelly side of the trap is allowed.  That seal may not be good enough to prevent all fumes from entering the room.
Comment: Good point - unfortunately though, that's what was already in the wall and probably has been there for 30+ years. The only way to change that though is to take down all the drywall, cut the existing pipe back and re-run, and then patch it all up. I'm really trying to avoid that for something so simple.


Difference between close() and disconnect()?

Question: Android Bluetooth Low Energy API implements 1 method to connect to the device connectGatt() but 2 methods to close the connection disconnect() and close().
Documentation says:

disconnect(): Disconnects an established connection, or cancels a connection attempt
   currently in progress.
close(): Application should call this method as early as possible after it is done with
     this GATT client.

The source code of BluetoothGatt.java shows that close() unregisters the application and disconnect() disconnect the client. However it does not say what that actually means. I mean, if there is only 1 way to connect to the client, why there are 2 ways to close/disconnect the connection?
Comment: I guess `Close` means you will not longer use Gatt object
Answer: With disconnect() you can later call connect() and continue with that cycle.
Once you call close() you are done. If you want to connect again you will have to call connectGatt() on the BluetoothDevice again; close() will release any resources held by BluetoothGatt.
Comment: Whenever I use `disconnect()` or `close()` the callback method `onConnectionStateChange` never get called indicating STATE_DISCONNECTED.
Comment: Super helpful- was only calling `disconnect()` and kept running out of BT interfaces preventing any new connections.  Calling `close()` prevents this.
Comment: close() won't get a call to onConnectionStateChange, but disconnect() should. Are you sure you were really connected when you called disconnect()?
Comment: @AlexanderFarber you can call close() without disconnect() but you won't get an onConnectionStateChange callback in my experience.
Comment: I have also struggled with inconsistent behaviors. If you call gatt.close(), the next time you connect to the same device, you will need to redo service discovery.Bonded BTLE devices are not supposed to do that.A bonded peer knows who you are (both for pairing and whether or not characteristics have been enabled) and can (by spec) send any data immediately. It will assume that you know its services. If you have done a gatt close, you wont know its services and may lose that data. I do not know what Android does down low, but working with embedded low level stacks this is definitely the case.
Comment: Can I call `close()`, without calling `disconnect()`? And will `onConnectionStateChange` be called in the case?
Comment: After calling `disconnect()` and `close()` the `onCharacteristicChanged()` event keeps firing. Does anybody have a solution for this?
Comment: @Brabbeldas My thought is that you probably have multiple peripherals connected and are getting callbacks for the other peripherals, or you disconnected and closed not what you thought you did.
Comment: @DouglasJones Thanks for replying. I am sure I only have a single peripheral connected. I am also sure I only call `mBluetoothGatt = device.connectGatt()` a single time.
Comment: So far, I've only used `close()` instead of both. But, I've just discovered on a Nexus 6P running Android 7.0, that if I call `close()` on a device that is currently pending to be connected, but not connected yet, the smartphone still reconnects to the device as soon as it becomes visible again...
Comment: `disconnect()` does not result in an `onConnectionStateChange()` if the connection had not already been established.
Answer: Here is some food for thought:
As long as you have not called close on the Gatt, you can still try to connect to it, or discover. So when I try to discover services for a machine, I will usually run a thread or runnable that makes the request to connect to the machine for a certain period of time.
The first attempt with a machine connection, will return a BluetoothGatt object that you can later use to try to discover the services for the BluetoothDevice object. It seems pretty easy to connect, but much harder to discover the machine servces.
mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);

So in my thread / runnable, I will check to see if the BluetoothGatt is null. If it is, I will call the above line of code again, else I will attempt to discover the BluetoothGatt services as such.
mBluetoothGatt.discoverServices();

Oh, and I ALWAYS make sure to call BluetoothAdapter.cancelDiscovery() before any attempt at connecting of discovering the service.
mBluetoothAdapter.cancelDiscovery();

Here is a method is use to connect in my runnable etc:
public void connectToMachineService(BLEMachine machine) {
    Log.i(SERVICE_NAME, "ATTEMPTING TO CONNECT TO machine.getDevice().getName());

    mBluetoothAdapter.cancelDiscovery();

    if(mBluetoothGatt == null)
        mBluetoothGatt = machine.getDevice().connectGatt(this, false, mGattCallback);
    else
        mBluetoothGatt.discoverServices();
}

Lastly, make sure that you close out any BluetoothGatt objects that you have connected to. It appears that Android can handle five BluetoothGatt objects before it starts saying "unable to connect to Gatt server" or other something like that.
On every BluetoothGatt that I create, I will call close on it then broadcast an update stating the connection is closed. It seems that there are a lot of times where the BluetootGatt will not respond with a state change when it becomes disconnected. My method of closing the BluetoothGatt goes something like this. I leave the method open up for the Activity to call the service and disconnect if a machine becomes non - responsive and the disconnect state is not called.
public void disconnectGatt(BluetoothGatt gatt) {
    if(gatt != null) {
        gatt.close();
        gatt = null;
    }

    broadcastUpdate(ACTION_STATE_CLOSED);
}

Comment: It is a little bit confusing that you call the method `disconnectGatt` when you actually call `close()` instead of `disconnect()`.


Bathroom Drain Venting

Question: I've been trying to figure out the difference between the following solutions. I'm sure that Option 1 is the best, given it's a short direct route to the vent, but I can't justify to myself why the others are bad? From what I can read it's usually the distance from the fixture to the start of the dry vent that matters, not how long the vent itself is.
Given that the sink (where the P trap is located on the right) is too far away from the main vent (far left), what would be the major differences in the following solutions?
(Blue = Vents)
(Black = Drains)

Option 1:

Option 2:

Option 3:
Comment: How far is the fixture from the vent stack on the left?
Comment: About 10 feet give or take a couple inches
Answer: How about this:

Or, if permitted by code an air admittance valve (AAV). The AAV is a simple in wall or under sink vent that allows air to vent when needed but blocks water and sewer gas from escaping. Just remember, the AAV must be accessible and are usually covered by an access panel for inspection.
Option #2 is also fine. It's called a "Chicago Loop" and used for sinks on kitchen islands.
Option #3 wont allow the sink to properly vent causing drainage problems.
If that sink is near an exterior wall, you may vent it directly outside, code permitting of course.
Comment: Thanks for the input. The reason I ask about alternative solutions is mainly because I'm trying to avoid running pipe in the ceiling, as it's the only part of the bathroom I haven't had to touch, and I'd like to keep it that way lol

Bathroom Drain Venting


gwt multiple modules without redundant code

Question: I'm trying to find a way to rid redundant compilation and js from a client's GWT code. Problem is that they have a multiple EntryPoint site and a massive model that gets compiled for every module. We're talking about 30 GWT modules and entry points each compiling the entire model package of the app separately. It takes about 15 minutes on my 8 core monster just to GWT compile this beast. And yes, compilation is parallellized and uses all cores (can hardly move my mouse in Ubuntu :) )
To change the architecture to a single module is not really an option I think. Is there no way to have inherits be shared between modules? The modules aren't necessarily that big all of them, but the problem is again that all inherits are compiled redundantly for each module. This of course has negative effects for the end user as well since every page basically has to load the entire model-js again and again.
According to
http://www.gwtproject.org/doc/latest/DevGuideOrganizingProjects.html#DevGuideModuleXml
the suggestion still seems to be to just make one great monolithic module. Isn't there any better way?
Any tips highly appreciated!
Answer: As you probably know GWT compiles each module into one big JavaScript file and optimizes everything based on all available information about everything in the whole module. This is why you need to compile everything for each module.
One solution might be to do create one big module, but use code splitting similar to the module structure. Than you don't get one very large monolithic JavaScript file, but 'modules' are loaded as needed.
Did you try compiling with less localworkers, instead of using all possible available cores? I've had the best results with localworker set to 4 (even on a 6-core machine).
Answer: As it is said in the GWT Documentation you refer to, GWT mechanism to face the problem of avoiding redundant code is merging all modules in just a  a super-gwt-module which includes all sub-modules you have in your applications.
I suppose you are producing a module for a different page or feature at your website, so using a unique module, as I say, implies that you will need a mechanism to run the appropriate application-code per page, based on the url or something.
You can take advantage of using code-splitting, so your modules will be EntryPoints instead of RunAsyncCallbacks, and each module will be compiled in one js fragment which will be loaded asynchronously.
Note that you will include the same javascript fragment in all pages, and this will load other fragments depending on the page.
The advantages of this solution are many:

You only have one compilation process. It could take a long time, but for sure it will take much less than compiling all modules individually because redundant code will be compiled once.
You can maintain different <code>.gwt.xml</code>, one to continue developing the individual modules with its own EntryPoint, and another without EntryPoint which will be inherited by your super-module.
Once compiled, the first fragment loaded  (shared by all apps) would be very small, and it will be cached just once, so all apps would load very fast.
Many of the code shared by the modules (gwt-core, jre, etc), could go to the first fragment and would be shared by all the modules, decreasing the final downloaded size of each app.
This is an out-of-the-box solution, gwt compiler makes a good job splitting the code, merging shared code to intermediate modules, and adding the methods to load fragments asynchronously when demanded.
Java ecosystem facilitates modular apps (dependencies, maven, etc).

Otherwise, if you continue wanting individual modules, the way to compile all of them is what you are actually doing: executing gwt compiler once per module (and permutation). You can improve your compilation time, though, having a continuous integration cluster like Jenkins and running jobs in parallel, or using more brute force (memory, cpu, ...).


How to inspect the currently used Nvidia driver version and switch it to another alternative?

Question: I'm trying to find out which Nvidia driver is being used currently in the system (and how to perhaps switch it to another version or the open-source nouveau driver).
modinfo knows about several nvidia drivers installed in the system (nvidia_173 and nvidia_331), but lsmod just calls it nvidia (and modinfo nvidia fails):
$ modinfo nv
nvidia_173  nvidia_331  nvidiafb    nvme        nvram       nv_tco
marsmorgana@marsmorgana:~$ modinfo nvidia_331
filename:       /lib/modules/3.11.0-26-generic/updates/dkms/nvidia_331.ko
alias:          char-major-195-*
version:        331.113
supported:      external
license:        NVIDIA
alias:          pci:v000010DEd00000E00sv*sd*bc04sc80i00*
alias:          pci:v000010DEd00000AA3sv*sd*bc0Bsc40i00*
alias:          pci:v000010DEd*sv*sd*bc03sc02i00*
alias:          pci:v000010DEd*sv*sd*bc03sc00i00*
depends:        drm
vermagic:       3.11.0-26-generic SMP mod_unload modversions 686
parm:           NVreg_Mobile:int
parm:           NVreg_ResmanDebugLevel:int
parm:           NVreg_RmLogonRC:int
parm:           NVreg_ModifyDeviceFiles:int
parm:           NVreg_DeviceFileUID:int
parm:           NVreg_DeviceFileGID:int
parm:           NVreg_DeviceFileMode:int
parm:           NVreg_RemapLimit:int
parm:           NVreg_UpdateMemoryTypes:int
parm:           NVreg_InitializeSystemMemoryAllocations:int
parm:           NVreg_UsePageAttributeTable:int
parm:           NVreg_MapRegistersEarly:int
parm:           NVreg_RegisterForACPIEvents:int
parm:           NVreg_CheckPCIConfigSpace:int
parm:           NVreg_EnablePCIeGen3:int
parm:           NVreg_EnableMSI:int
parm:           NVreg_MemoryPoolSize:int
parm:           NVreg_RegistryDwords:charp
parm:           NVreg_RmMsg:charp
parm:           NVreg_AssignGpus:charp
marsmorgana@marsmorgana:~$ lsmod | fgrep nv
nvidia               9704581  42
drm                   247722  2 nvidia
marsmorgana@marsmorgana:~$ modinfo nvidia
ERROR: modinfo: could not find module nvidia
marsmorgana@marsmorgana:~$

How to find out which one is being used?
How to switch the one being used?
Re: additional-drivers
In 12.04, I have neither an additional-drivers tab in update-manager:

nor an additional-drivers app in the menu, nor such a program (checked by locate), nor such an installable package (checked by apt-cache search).
(Off-topic explanation of my reason to want to inspect and switch the nvidia driver)
Because I might be experiencing problems with running SketchUp under wine because of the nvidia driver, as reported there.
An off-topic UPDATE: actually, it turned out later that this is another known nvidia-unrelated problem (see under "Tips") (found via "Sketchup not responding"), which must be fixed in wine-1.7.31; this version or later is available in the Ubuntu Wine repository for Trusty or later, so I'd need to upgrade from my 12.04 (Precise) to Trusty to use those packages. Nevertheless, my question here makes sense independently of the real solution in my situation.
Comment: nvidia-smi -L **Sample output:** GPU 0: GeForce GTX 1660 Ti with Max-Q Design (UUID: GPU-64ff7c28-7905-a240-e063-91caf97ab792)
Answer: List available drivers via
% apt-cache search nvidia | grep -P '^nvidia-(driver-)?[0-9]+\s'
nvidia-304 - NVIDIA legacy binary driver - version 304.125
nvidia-310 - Transitional package for nvidia-310
nvidia-319 - Transitional package for nvidia-319
nvidia-346 - NVIDIA binary driver - version 346.59
nvidia-driver-390 - NVIDIA driver metapackage
nvidia-340 - NVIDIA binary driver - version 340.107
nvidia-driver-418 - Transitional package for nvidia-driver-430
nvidia-driver-430 - NVIDIA driver metapackage
nvidia-driver-435 - NVIDIA driver metapackage

and install with, eg
sudo apt-get install nvidia-driver-435

Show driver in use

nvidia-smi
Sat Sep  5 11:57:22 2015
+------------------------------------------------------+
| NVIDIA-SMI 340.76     Driver Version: 340.76         |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce 9800 GT...  Off  | 0000:01:00.0     N/A |                  N/A |
| 65%   52C    P0    N/A /  N/A |    271MiB /  1023MiB |     N/A      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Compute processes:                                               GPU Memory |
|  GPU       PID  Process name                                     Usage      |
|=============================================================================|
|    0            Not Supported                                               |
+-----------------------------------------------------------------------------+

nvidia-settings

nvidia-settings -q NvidiaDriverVersion
  Attribute 'NvidiaDriverVersion' (sturm:1.0): 340.76
  Attribute 'NvidiaDriverVersion' (sturm:1[gpu:0]): 340.76

cat /proc/driver/nvidia/version
NVRM version: NVIDIA UNIX x86_64 Kernel Module  340.76  Thu Jan 22 12:11:08 PST 2015
GCC version:  gcc version 4.9.2 (Ubuntu 4.9.2-10ubuntu13)

Comment: `nvidia-smi` is the way if you installed the driver using the official `.run` file.
Comment: GCC version is empty for me. Does that mean I have messed something up?
Answer: Just open the additional-drivers app, search for it in the dash, or in software and updates

In 12.04 you can download an additional drivers app HERE.
Comment: As a workaround, removing the nvidia drivers with `sudo apt-get purge nvidia*` will cause the system to fall back on nouveau.
Comment: In 12.04, I don't have an `additional-drivers` app in the menu (nor a program, nor a package -- checked by `locate` and `apt-cache search` respectively).
Comment: Look in software and updates, like in the screenshot
Comment: Have a look at my screenshot(I've updated the question). It's like yours, but without an "additional drivers" tab.
Comment: Updated with where to find it for 12.04
Comment: Thanks, `jockey-gtk` does show the driver variants! Only one problem: it hasn't listed the `nouveau` variant. (Perhaps, that's because I have `xserver-xorg-video-nouveau-lts-saucy` installed (and the corresponding xorg packages), not the plain `xserver-xorg-video-nouveau`.)


Surface area of a spherical dish

Question: How do I calculate the surface area of a spherical dish with a radius of curvature of 265 meters and a diameter of 305 meters? We can't use the normal formula 4(pi)r^2 because the sphere isn't a full or exactly half. How would you do it?
Comment: By "spherical dish" you mean the shape you would get by plane cutting a hollow sphere across one of its great circles?
Comment: @Frpzzd I think they mean they've cut a sphere of radius $265$ along a line of latitude such that the resulting shape has a diameter of $305$.
Comment: Ah, I see what you mean.
Comment: that's right @kccu
Comment: @Helena Do you know about surface integrals and spherical coordinates?
Comment: I know for the volume I'd use volume of revolution, but how would I find the surface area?
Answer: In the figure below, I've cut a sphere of radius $265$ along a latitude to obtain a spherical bowl of diameter $305$ (I'm just showing a cross-section). We can see a right triangle with hypotenuse $265$, and side opposite angle $\phi$ of length $152.5$. Then we can find $\phi = \arcsin\left(\frac{152.5}{265}\right) \approx 0.613 \text{ rad}$.
If you are familiar with surface integrals and spherical coordinates, the surface area of the bowl can now be computed as the integral of $1$ over the region $0 \leq \theta \leq 2\pi$, $0 \leq \phi \leq \arcsin\left(\frac{152.5}{265}\right)$, $\rho = 265$.

If you've been studying solids of revolution, then maybe you are familiar with the surface area formula $\int_a^b 2\pi x \sqrt{1+\left(\frac{dy}{dx}\right)^2} \ dx$ for the surface obtained by rotation $y=f(x)$, $a \leq x \leq b$, about the $y$-axis. The right half of the cross section of the bowl below is described by $f(x)=\sqrt{265^2-x^2}$, $0 \leq x \leq 152.5$ (assuming we center the sphere at the origin). So
$$\frac{dy}{dx}= \frac{1}{2}(265^2-x^2)^{-1/2}\cdot -2x = \frac{x}{\sqrt{265^2-x^2}}$$
and
$$\sqrt{1+\left(\frac{dy}{dx}\right)^2} = \sqrt{1+ \left(\frac{x}{\sqrt{265^2-x^2}}\right)^2}= \sqrt{1+ \frac{x^2}{265^2-x^2}}=\frac{265}{\sqrt{265^2-x^2}}.$$
So we end up with
$$\int_0^{152.5}2\pi x\frac{265}{\sqrt{265^2-x^2}} \ dx$$
which can be solved by $u$-substitution with $u=265^2-x^2$.
This page might be useful to you: http://tutorial.math.lamar.edu/Classes/CalcII/SurfaceArea.aspx
Comment: Thankyou so much, this makes sense. I was just searching on wikipedia and it gave the formula as 2 π r h, is the the same or different?https://en.wikipedia.org/wiki/Spherical_cap#cite_note-handbook-1
Comment: That is what you should get. Note that you are not given $h$, but you could find it given the radius of the sphere and the diameter of the spherical cap.
Comment: Yep I just tried and found it to be 24.23 meters. So would doing solids of revolution and using the 2 π r h formula give me the same answer?
Comment: Any correct method will give you the same answer.
Comment: I got 80383.752 as the answer with the solids of revolution method but got 40349.00792 with the formula. I can't figure out what i did wrong... What is the answer supposed to be?
Comment: What did you use for the radius and height in the formula from wikipedia? The radius should be the radius of the *sphere*, not the spherical cap.
Comment: I used 265 for the radius, it should be right. I used 24.23... for height, which i found using pythag.
Comment: The height is wrong. The vertical side of the right triangle in my figure has length $x$ where $x^2+15.25^2=265^2$. The height of the spherical cap is then $h=265-x$. I got $80383.752$ using the formula from Wikipedia, so I think your solid of revolution answer is correct.
Comment: Thank you so so much. I entered 285 instead of 265 in my calculator. Now I got the right answer. Thanks!!!

Surface area of a spherical dish


Are there new items in The Zodiac Age?

Question: I've noticed that I am picking up items that I have never seen before in the original game. I've received quite a few "Prince's Kiss" items, which remove sleep from a character, but I seem to remember that an "Alarm Clock" was used in the original.
What other new items have been added to the PS4 remaster?
Answer: Yes, but I cannot tell clearly if these items and name changes came with The Zodiac Age or the earlier Japan only International Zodiac Job System release.
I cannot produce an exhaustive list of changes between the PS2 and the Zodiac Age PS4 release, but there are other facts to keep in mind when comparing these two games.
In Japan, around one year after the release of the original FF 12, they received an updated/reworked version of FF 12 called the International Zodiac Job System, or IZJS for short.
This Japan-only release featured many changes to the game, among these were new items and equipment and changes to existing items.
Here is an extensive GamesFAQ entry that shows differences in the original and IZJS release. I cannot find for sure if there were any item renames done then already, the Alarm Clock mentioned by you is still being listed in this GameFAQ entry, but no Prince's Kiss. The Final Fantasy Wikia entry for Alarm Clock lists it being renamed to Prince's Kiss in the Zodiac versions. I cannot tell if this means the IZJS release or The Zodiac Age.
The changes made in IZJS are included in The Zodiac Age, including the changes and additions that the new game itself brings to FF 12.
According to the differences page in the Final Fantasy Wikia, there do not seem to be any additional items in this release but the game was balanced to be easier, so this might include changed item drops and changed availability in shops.
I hope this info helps to understand the differences in the three games.
Edit: Brandon Zappy's answer has a link for a useful item comparison I did not find on the wikia. I should focus less on work and more on my answer research it seems ;).
Answer: According to this article from IGN there have new weapons and armor, among other things, but no mention of any new items. I didn't remember a "Prince's Kiss" item from the original game either, so I continued doing some research until I found this very helpful wiki article (Really though, what wiki isn't helpful) that show's all the new items that have been added in each category. The items are in a column where the header will either state "FFXII" or "Zodiac" with Zodiac being the new release. Hope this helps!

Are there new items in The Zodiac Age?


PHP Splitting a String

Question: Okay, here is the question. I have a string. This string is a combination of US State Codes
$codes = 'ALAKAZARCACOCTDEDCFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY';

I need to split the string into two letters, such as "AL", "AK", "AZ", "AR" etc.
I can't think of any other SIMPLE function other than preg_split but I am not an expert in regular expression.
Can any of you think about any other easy method to split the string ? The other function close to the answer what I can think of is using "substr".  Looking for more options and also preg_split example.
Comment: ex. regex like `'\[A-Z]{2}\'`
Answer: This should work for you:
<?php

    $codes = 'ALAKAZARCACOCTDEDCFLGAHIIDILINIAKSKYLAMEMDMAMIMNMSMOMTNENVNHNJNMNYNCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY';
    $arr = str_split($codes, 2);
    print_r($arr);

?>

PHP Splitting a String


Heroku can't see config folder; why?

Question: although config folder is committed, heroku dosen't see it ..
when I do heroku run rake db:migrate I get this error:
Running rake db:migrate attached to terminal... up, run.1
rake aborted!
no such file to load -- /app/config/application

I tried to test it like this:
$ heroku run bash -a myapp
~ $ ls config
ls: cannot access config: No such file or directory

although I am sure config folder is committed and pushed, can some one help me ?
here is the git status:
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   .gitignore~
#   modified:   .idea/workspace.xml
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   .idea/workspace.xml

Answer: Are you sure it's not the application.rb file that it can't find? Can you try:
$ heroku run bash -a myapp
~ $ ls -al /app/config

Comment: yes, here is what I get:
ls: cannot access /app/config: No such file or directory
Comment: Your rake output suggests it's trying to load application.rb from inside the /app/config folder whilst in Rails it should be at the same level of the app directory ie /config/application.rb - does the app boot locally?
Answer: Force another git push to your remote heroku repository. There were some git push errors on Heroku today. See http://status.heroku.com
Comment: I tried to force push like this: git push heroku master -f, but ,I get a result: Everything up-to-date, is this the correct way to force git push ?
Comment: make a change to some file, do a local commit, and do another push to Heroku.
Comment: I tried to make changes to boot.rb and application.rb, committed, and did another push, but, I have the same error ..

Heroku can't see config folder; why?


Does Lync Server 2013 support UCWA 2.0

Question: We need to integrate with a partner that runs Lync Server 2013, including the August 2016 cumulative update.
I would like to use UCWA version 2.0, which is well documented here: https://ucwa.skype.com/documentation/whats-new-ucwa
So far I couldn't find any release notes or documentation that confirms that Lync Server 2013 supports UCWA 2.0, and if it does - which updates are required.
Comment: You will want to move to Skype for Business Server 2015 to take advantage of 2.0 features.
Answer: Considering the following:

In general Lync Server 2013 CU1 and above used UCWA 1.0.* (Lync 2013 RTM didn´t have UCWA) while Skype for business Server 2015 used UCWA 2.0.*
In coexistence mode (Lync 2010 and Skype for Business 2015) you must point the Autodiscover CNAME (Lyncdiscover. and LyncDiscoverinternal.) to a Skype for Business Server 2015 pool in order support custom UCWA 2.0 application development (as written here). But that's for Lync 2010 which do not have any UCWA on its frontend server as written here.
A Lync 2013 mobile client used also the UCWA (as mentioned here or here) and is compatible with Skype for Business.
The UCWA 1.0 Code samples, Get started, What is this API?, Core features and Reference URLs here all points now to the UCWA 2.0 links.

lead to the point that this should work.

Does Lync Server 2013 support UCWA 2.0


How can I add space between form fields

Question: I am new to coding and designing with CSS, I am having difficulty adding space between form fields. I tried padding as well as margin attribute but still the space is not being add. Any help or recommendation on how could i add the space.
enter image description here
This is the code i have for form

            First Name
            <input type="text" name="fname" placeholder="John" required>

            Last Name
            <input type="text" name="lname" placeholder="Lewis" required>

            Email
            <input type="email" name="email" placeholder="firstname.lastname@example.com" required>

            Phone Number
            <input type="number" name="phone-no">

Comment: I would recommend you to check out https://getbootstrap.com/docs/4.5/layout/grid/
Comment: classic way to pile them is : `First Name` from there, margin or padding on p will do it can help also to align them if needed, in fact it gives you much more and easier possibilities of styling.
Answer: You can wrap each input field with a block level element e.g
 then give the div some styling to set the position the way you like.

How can I add space between form fields


Rendering a polygon with input vertices in three.js

Question: I have vertices(x,y,z coords) of a polygon as input. How can I render a polygon having these vertices in three.js?
There is this documentation.But it seems to involve bezier. I need simple straight edged polygon.
Answer: You can create a polygon from vertices with the following code:
var geom = new THREE.Geometry();
var v1 = new THREE.Vector3(0,0,0);
var v2 = new THREE.Vector3(0,500,0);
var v3 = new THREE.Vector3(0,500,500);

geom.vertices.push(v1);
geom.vertices.push(v2);
geom.vertices.push(v3);

geom.faces.push( new THREE.Face3( 0, 1, 2 ) );
geom.computeFaceNormals();

var object = new THREE.Mesh( geom, new THREE.MeshNormalMaterial() );

scene.add(object);

Copy and paste this code in and then change x, y, and z coordinates of v1, v2, and v3 (or however many vertices you need) to the coordinates of your vertices.
Essentially, you are creating vertices using THREE.Vector3 to supply the coordinates and then pushing them to the vertices property of an empty THREE.Geometry();
Code is from this answer
Comment: `THREE.Geometry` is removed from Three.JS
Comment: can any one help, how to draw polygon using THREE.BufferGeometry?
Answer: THREE.Geometry is removed, try the following method
    let coordinates = [
     {
       x : 1,
       y : 1,
       z: 10
     },
     {
       x : 2,
       y : 1,
       z: 10
     },
     {
       x : 2,
       y : 2,
       z: 10
     },
     {
       x : 1,
       y : 2,
       z: 10
     }
    ]
    let polyShape = new THREE.Shape(coordinates.map((coord) => new THREE.Vector2(coord.x, coord.y)))
    const polyGeometry = new THREE.ShapeGeometry(polyShape);
    polyGeometry.setAttribute("position", new THREE.Float32BufferAttribute(coordinates.map(coord => [coord.x, coord.y, coord.z]).flat(), 3))
    let polygon = new THREE.Mesh(polyGeometry, new THREE.MeshBasicMaterial({ color: "colorYOuWant", side: THREE.DoubleSide}))
    scene.add(polygon);

Comment: what is 'measurement' or how to define it?
Comment: Why does the polyGeometry need the 2D Shape at initialization when you seem to overwrite the points anyway with `setAttribute("position",..`? Or is this setAttribute not overwriting the points' positions?
Answer: I also need this and while the answer of @Aakash helped me to start, setting the points in the ShapeGeometry was a problem
Just

Build a Shape object with the 2D coordinates (Vector2)
Build a ShapeGeometry from that Shape
Build the Mesh from that Geometry and the Material you want
rotate and scale the Mesh the way you want

Perfect example for it is https://threejs.org/examples/webgl_geometry_shapes
Especially have a look at the californiaShape object and the addShape function
const californiaPts = [];

californiaPts.push( new THREE.Vector2( 610, 320 ) );
californiaPts.push( new THREE.Vector2( 450, 300 ) );
californiaPts.push( new THREE.Vector2( 392, 392 ) );
...

const californiaShape = new THREE.Shape( californiaPts );

addShape( californiaShape, ... );

function addShape( shape, extrudeSettings, color, x, y, z, rx, ry, rz, s ) {

    let geometry = new THREE.ShapeGeometry( shape );

    mesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: color, side: THREE.DoubleSide } ) );
    mesh.position.set( x, y, z - 125 );
    mesh.rotation.set( rx, ry, rz );
    mesh.scale.set( s, s, s );
    ...
}


How to filter on an array in Javascript

Question: I'm new in Javascript,
I want to Create a function that takes an array of non-negative integers and strings and return a new array without the strings.
Examples
filterArray([1, 2, "aasf", "1", "123", 123]) ➞ [1, 2, 123]
I've tried this code :

function filterArray(arr) {
    var j=0;
    var numArr;
    for (let i=0;i<length.arr;i++)
    {
        if (typeof arr[i] ==="number")
        {
            numArr[j]=arr[i];
            j++;
        }
    }
    return numArr
}
console.log(filterArray([1, 2, "aasf", "1", "123", 123]));

but i didn't arrive to run my code, can someone helps me ?
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Comment: use `Array.prototype.filter`
Comment: Does this answer your question? [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes)
Answer: using the filter method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

function filterArray(arr) {
    return arr.filter(x => typeof x === "number");
}

console.log(filterArray([1, 2, "aasf", "1", "123", 123]));
Answer: 1) First the loop should be run up to arr.length not length.arr.
2) No need to use another counter variable j, you can use simply array as
var numArr = [];

and you can use push method to add elements in the array at the end.

function filterArray(arr) {
  var numArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (typeof arr[i] === "number") {
      numArr.push(arr[i]);
    }
  }
  return numArr;
}

console.log(filterArray([1, 2, "aasf", "1", "123", 123]))
// ➞ [1, 2, 123]

Other alternatives

function filterArray(arr) {
  // return arr.filter((el) => +el === el);
  // or
  // return arr.filter((el) => typeof el !== `string`);
  // or
  return arr.filter(el => typeof el === "number");
}

console.log(filterArray([1, 2, "aasf", "1", "123", 123]));
Answer: You can use Array.filter() to filter your elements based on a condition given.

function filterArray(arr) {
    return arr.filter(el => typeof el === 'number');
}
console.log(filterArray([1, 2, "aasf", "1", "123", 123]));
Answer: Why not just like this:
const data = [1, 2, "aasf", "1", "123", 123];
const filtered = data.filter((d) => typeof d === "number");

Answer: Instead of giving the most optimized answer, I will try to address  a few problems with your code. You can look at any other answer to use the best code:

length.arr should be arr.length. That is how JS works.
var numArr, if you will access numArr[0] this will give you an error. Initialize with an empty array.

function filterArray(arr) {
    var j=0;
    var numArr = [];
    for (let i=0;i<arr.length;i++)
        {
        if (typeof arr[i] ==="number")
        {numArr[j]=arr[i];
        j++;
        }
        }
    return numArr
}

Make these changes and your code works.
Answer: Try this
var arr = [1, 2, "aasf", "1", "123", 123],
    num = arr.filter(item => typeof item === "number")

Answer: You can try with this.
const arr = [1, 2, "aasf", "1", "123", 123]
const filteredData = arr.filter((item) =>  Number(item) === item );

How to filter on an array in Javascript


What are the options for putting cabinets in front of receptacles?

Question: I'll be putting some base cabinets in my townhouse (northern Virginia), on an existing wall with several electrical receptacles. The receptacles are near the floor, as this is not a kitchen, and would be covered by the cabinets.
What are my options for dealing with those receptacles in a safe and code-compliant way? I'm not averse to moving them up if need be, so they'll sit above the new cabinets / countertop.
Answer: All junction boxes in use, whether with receptacles, splices, switches or other devices, must be accessible.
Move 'Em
This is probably the generally "best" answer. But it may involve significant work, depending on the type of wall. However, not only can receptacles not be covered, junction boxes can't be covered, even if they are only in use for a splice.
If a cable comes down from above, moving the receptacle up is easy.
If a cable comes up from below, you have a problem because you need to extend the existing cable. Normally you do that by splicing in an additional cable in the junction box. But that doesn't help here because now you have a junction box that still can't be covered. There are splices that are approved for in-wall use (i.e., not accessible) which may be an option.
Use 'Em
Depending on the type of cabinet, or specifically the type of cabinet back wall, you can:

Cut a large enough area in the cabinet back to make the junction box fully accessible. Essentially so that there is wall surface visible around the junction box cover plate, so that the junction box is really "in the wall" and not "inside a hole in the cabinet".
Cut the exact size of the junction box in the cabinet back and add a box extension so that you can mount the receptacles flush with the back of the cabinet. A little more work but will look much more professional.

Both!
With typical walls, you could use the receptacles below and it should be very easy to install receptacles above the counter and drop cable down to the lower receptacles. Pigtail each set of 3 wires (in, out, new) in the lower boxes, even if originally they had the normal in on one screw, out on the other screw.
Answer: Moving them up would be the best bet.
Cutting holes in the back of the cabinets to allow access to them might be code acceptable, as I understand it - if you can open a cabinet door and find the receptacle without having to unscrew anything, it's accessible.
But you need countertop outlets anyway (not specific to kitchen countertop - cabinets with no countertop get a pass on wall outlets (which is silly, you certainly have need of them even if it's a long run of bookcases) but hving a countertop means you have to have outlets as for any other section of wall (and I don't think outlets in the back of the base cabinets qualify for that.)


Spotify crashes opening Ubuntu 20.04

Question: I just installed Spotify two days ago and it worked perfectly. After one day, when I started my computer and opened Spotify, it worked ok, but after closing it and opening it again it crashes. A blank screen appears for 1 second and then closes. I have the free version of Spotify and I'm running Ubuntu 20.04.
edit: If I open Spotify from the terminal this happens:
Gtk-Message: 09:29:30.910: Failed to load module "gail"
Gtk-Message: 09:29:30.910: Failed to load module "atk-bridge"
Gtk-Message: 09:29:30.918: Failed to load module "canberra-gtk-module"
[1012/092931.627932:FATAL:gpu_data_manager_impl_private.cc(439)] GPU process isn't usable. Goodbye.
Trace/breakpoint trap (core dumped)

I forgot to say that I recently used an ad blocker. I saw that it's illegal and I removed it. Firstly I tried to remove ads as shown in this video. It didn't work, so I installed "Spotify adkiller", then I saw it's illegal to remove ads from Spotify and I removed it (at least I think so).
I want to mention that if I turn on my computer, the first time I open Spotify it works perfectly, but if I close Spotify and open it again it crashes. It looks like Spotify wants to open but another application opens over Spotify and closes it. Llike a Spotify closer.
Comment: It does eventually load: `while true; do spotify && exit; done`
Comment: I am also experiencing this issue on Debian. I am investigating and hope to provide an answer soon. This is not related to your ad-blocking activities.
Answer: I had a same problem but got a fix. Here are some solutions that might work.

spotify --disable-gpu --disable-software-rasterizer
spotify --no-zygote
sudo spotify
Or a reboot

while true; do spotify && exit; done eventually loads but most probably you will get black screen and if this happens then second one will work for you.
Comment: the --no-zygote worked for me
Answer: --no-zygote worked for me, but opening terminal to launch spotify was a no for me. When i clicked the spotify icon spotify didn't launch for some reason so I fixed that problem like this:
I put --no-zygote into spotify.desktop file by changing Exec=spotify %U command to:
Exec=spotify %U --no-zygote

If that doesn't work, right click on spotify icon and open properties, Application tab (I'm using kde so it might differ in each distro, not sure) and change spotify %U to spotify %U --no-zygote in the command section
The second one worked for me.
Comment: The right click on the icon will not work in Ubuntu's head version, Gnome3. So if there is another way or option I would be glad to hear it.
Comment: I had to hunt a bit for the `spotify.desktop` file. My lived in /usr/share/applications. Disabling GPU in the Exec section did the job for me...
Answer: It is a bug in the Spotify app NOT in Ubuntu's global system.
Spotify is based on Chromium (that is no secret I think) , now Chromium has a bug :
you can read all about it here
To help you on your way :
open a terminal and simply type: $spotify --no-zygote
this way you can close and re-open spotify a lot of times without a fatal crash.
We have to wait thus on a Chromium update for this error, and we have to wait until Spotify will update from this. There is no other way.
Remember that you run Spotify now out of the terminal process !
Answer: Yes, I also experienced the same thing, then I reinstalled it. In my experience, don't open spotify via the Linux terminal, you can open it via the application menu. It worked for me.
Answer: Open the System Monitor, go to Processes and check if there is still a spotify process running. I haven't used an adblocker but solved a similar issue by simply killing that process.

Spotify crashes opening Ubuntu 20.04


D3 date parse issue with timezone offset

Question: i am creating a line chart which have x-axis as time scale axis and i have to parse the date data coming from backed.
The date is coming in this format from the backend -> 2016-01-14T02:55:55.000Z
I wrote this parse function using d3 date format
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%L");

But this piece of code not able to parse the above mentioned date format and i have to remove Z from the x-axis date data which is takes time when there are huge number of data points.
So, is there a way to handle the above mentioned date format in d3?
Comment: Is the date a typeof string or a Date object?
Comment: @GeorgeHoupis: It is a string.
Comment: how are you calling parseDate?  parseDate( new Date( '2016-01-14T02:55:55.000Z' ) )?
Answer: You need to specify the Z in the format string:
var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ");

I would recommend using var parseDate = d3.time.format.iso; instead, as this is more forgiving.
Comment: Thank You for the answer. This `var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S.%LZ");` solves my issue.


How to upload a large file (> 1GB) directly to Amazon S3 from a given URL using NodeJS without actually saving the file in local?

Question: I tried uploading a large file to S3 in many ways in NodeJS using aws-sdk but eventually ended up just uploading only 1mb of a file which is actually 1.2 GB.
So, I tried using  streaming-s3   in node js, the code is shown below.
I referred  https://www.npmjs.com/package/streaming-s3  for streaming-s3 package.
var streamingS3 = require('streaming-s3');
var request = require('request');
var url = 'XXXXXXXXX';
var rStream = request.get(url);

var uploader = new streamingS3(
  rStream,
  {accessKeyId: 'XXXXXXXXXXXXX',
    secretAccessKey: 'XXXXXXXXX'
  },
 {
    Bucket: 'XXXXXXXXX',
    Key: 'XXXXXXX',
    ContentType: 'text/html'
  },

  {
    concurrentParts: 2,
    waitTime: 10000,
    retries: 1,
    maxPartSize: 10 * 1024 * 1024
  }
);

uploader.begin();

When I run this code, the chunks from the file are not actually getting uploaded to S3 in streams.
Only 1mb is getting uploaded, but not the entire file.
Is there any other way to upload a file to S3 from a URL ?
Answer: Try using s3-upload-stream. It uses Multipart Uploads. For objects larger than 100mb it is recommended to use Multipart Uploads.
Comment: s3-upload-stream pipes a data stream to an s3 object. So you can pipe your `rStream` directly to s3 by `rStream.pipe(compress).pipe(upload)`. Check the  first example on the npm docs of s3-upload-stream(given in answer)
Comment: I want to upload a file from URL, not from local. Seems like  s3-upload-stream is for local file streaming.
Comment: Its not working, I tried it. Only 610 bytes got uploaded out of 800 MB file.
Answer: AWS has "managed upload" to take care of large file upload to S3. Tried a few mb of data and it gets uploaded albeit it takes a few seconds. S3-upload-stream does a great of optimzation and with larger parts (chunks) the optimzation is great. I hope that you arent using http to do that uploads, since 1GB files take a large amount of time to upload and http eventually times out, hence you couldn't see a response. The better way to do that, is to leverage the upload functionality to a worker and once done, send a notification through SSE (since you use nodejs - implementing SSE should be easier since its a javascript paradigm anyway). I can give a sample implementation with a few mb file here, but I urge to follow a different design incase of uploading 1GB files.
Here is an example that I use:
THis is with managedUpload - 10mb arnd 20sec,  50 mb file takes around 32s, 80mb takes (6MB chunks - 16parts)
   @VideoFileValidator
async managedUploadFileToFolder(bucket: BucketModel, fileObj: any) {

    return new Promise(async (resolve, reject) => {
        // first make sure that the bucket exists
        try {
            const bucketList = await this.listBuckets();
            if (bucketList.filter(item => item.Name.toUpperCase() === bucket.name.toUpperCase()).length >= 1) {
                // means there is a bucket and obj can be created
                // create obj params
                const metadata: AWS.S3.Metadata = JSON.parse(JSON.stringify(bucket.fileData.metadata));
                const keyFolder = bucket && bucket.folder ? APP_CONSTANTS.COMMON.APP_NAME + '/' + bucket.folder + '/'+bucket.fileData.name : 'tf-default-video';

                const putObjParam: AWS.S3.PutObjectRequest = {
                    Body: Readable.from(this.utilService.bufferToStream(fileObj['buffer'])).pipe(zlib.createGzip()),
                    Bucket: bucket.name,
                    Key: keyFolder,
                    ContentType: 'multipart/form-data',
                    Metadata: metadata,
                    StorageClass: 'STANDARD'
                }
                this.s3MangedUpload = new AWS.S3.ManagedUpload({
                    leavePartsOnError: false,
                    partSize:1024*1024*6,
                    queueSize: 16,
                    params: putObjParam,
                    tags: this.utilService.createTags(false,true)
                });
                this.s3MangedUpload.send((err, uploadData) => {
                    console.log('aws err obtained:', err);
                    if(err) {
                        reject(AppConfigService.getCustomError('FID-S3-CUSTOM', `Error uploading the data:${err.message} - code: ${err.code} - status: ${err.statusCode}`));
                    }
                    resolve(plainToClass(CommonOutputResponse, {timestamp: AppUtilService.defaultISOTime(),
                        status: 'Success', message: `${fileObj['originalname']} Uploaded successfully with alias ${bucket.fileData.name}`,
                        data: {
                            uploadedToHttps: uploadData.Location,
                            uploadedToFolder: `s3://${bucket.name}//${bucket.folder}`
                        }
                    }));
                });
                this.s3MangedUpload.on('httpUploadProgress', (progress) => {
                    console.log('progress:', progress);
                });

            } else {
                reject(AppConfigService.getCustomError('FID-S3-CUSTOM', `Object cannot be created since ${bucket.name} doesnt exist`));
            }
        } catch (err) {
            console.log('err:', err);
            reject(AppConfigService.getCustomError('FID-S3-CUSTOM', 'Object cannot be uploaded -' + err.message));
        }

    });
}

Code explained:
The decorator

@VideoFileValidator

validates if the input from http is a valid video file of types - mp4, mkv, avi (validates based on the file extension, so no way to read that large buffer)

The method by itself uses AWS.S3.managedUpload -  defines the queue size as part of params and used the Bodyparam to define the stream
Note: The stream here is the one coming from http input. comes as a buffer and hence converted to stream
.send() takes care of the actual streaming of data. I am unsure if piping happens in the backend, but I guess that might be the case. We can check for upload progress, using the 'httpUploadProgress' event.
The s3-upload-stream on the other hand performs better with larger chunk sizes. I tried with the same 10mb and 50 mb files with the below configuration and was able to save a few seconds, so hopefully it might interest you. Again, uploading 1GB file, might needed a better architecture design
@VideoFileValidator
    async streamFileUpload(bucket: BucketModel, fileObj: any){
        const metadata: AWS.S3.Metadata = JSON.parse(JSON.stringify(bucket.fileData.metadata));
        const keyFolder = bucket && bucket.folder ? APP_CONSTANTS.COMMON.APP_NAME + '/' + bucket.folder + '/'+bucket.fileData.name : 'tf-default-video';

        const putObjParam: AWS.S3.PutObjectRequest = {
            Bucket: bucket.name,
            Key: keyFolder,
            ContentType: 'multipart/form-data',
            Metadata: metadata,
            StorageClass: 'STANDARD'
        }

    return new Promise(async (resolve, reject) => {

        const read = this.utilService.bufferToStream(fileObj['buffer']);
        const compress = zlib.createGzip();
        const upload = this.s3Upload.upload(putObjParam);
        upload.maxPartSize(1024*1024*6); // 20 MB
        upload.concurrentParts(15);

        upload.on('part', function (details) {
            console.log('still uploading ....',details);
        });

        upload.on('uploaded', function (details) {
            console.log('upload completed',details);
            upload.end();
            resolve(plainToClass(CommonOutputResponse, {timestamp: AppUtilService.defaultISOTime(),
                status: '200-OK', message: 'Uploaded succesfully',
                data: {
                    location: details['Location'],
                    uploadedTo: details['Bucket'],
                    withName: details['Key']+''+bucket.fileData.name
                }
            }));
        });

        upload.on('error', (error) => {
            console.log('error occured upploading the data:', error);
            upload.end();
            reject(AppConfigService.getCustomError('FID-S3-CUSTOM', 'Error occured:'+error['message']));
        })

        read.pipe(compress).pipe(upload);
    })

    }

"Part" - event to check on progress, "uploaded" - event that is emitted when file is uploaded completely. I more or less used the same configuration


Why does the program fail to load?

Question: I was told that a main() function needs to be put into my code to prevent bugs and ensure the smoothness of the program. However upon loading my game quits when the first board appears.
If I have missed anything out (future potential bugs) I'd like to know.
In future I also plan on putting this game on a website using flask, with the player using the arrow keys to select the location he/she wants to hit before pressing the space bar for the action. If someone could give me an idea on how to begin with this, I'd greatly appreciate it.
Thanks for your help in advance.
The program is a console-based 2-player battleships ships game in python:
from random import randint

game_board = []
player_one = {
    "name": "Player 1",
    "wins": 0,
    "lose": 0
}
player_two = {
    "name": "Player 2",
    "wins": 0,
    "lose": 0
}
total_turns = 0

# Building our 5 x 5 board
def build_game_board(board):
    for item in range(5):
        board.append(["O"] * 5)

def show_board(board):
    print("Find and sink the ship!")
    for row in board:
        print(" ".join(row))

# Defining ships locations
def load_game(board):
    print("WELCOME TO BATTLESHIP!")
    print("START")
    del board[:]
    build_game_board(board)
    show_board(board)
    ship_col = randint(1, len(board))
    ship_row = randint(1, len(board[0]))
    return {
        'ship_col': ship_col,
        'ship_row': ship_row,
    }

ship_points = load_game(game_board)

# Players will alternate turns.
def player_turns():
    if total_turns % 2 == 0:
        return player_two

    else:
        return player_one

# Allows new game to start
def play_again():
    answer = input("Would you like to play again?")
    if answer == "yes" or answer == "y":
        total_turns = 0
        ship_points = load_game(game_board)

    else:
        print("Thanks for playing!")
        exit()

# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
    guess_col = 0
    guess_row = 0
    while True:
        try:
            guess_row = int(input("Guess Row:")) - 1
            guess_col = int(input("Guess Col:")) - 1
        except ValueError:
            print("Enter a number only.")
            continue
        else:
            break
    match = guess_row == ship_row - 1 and guess_col == ship_col - 1
    not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)

    if match:
        player["wins"] += 1
        print("Congratulations! You sunk my battleship!")
        print("Thanks for playing!")
        play_again()

    elif not match:
        if not_on_game_board:
            print("Oops, that's not even in the ocean.")

        elif board[guess_row][guess_col] == "X":
            print("You guessed that one already.")

        else:
            print("You missed my battleship!")
            board[guess_row][guess_col] = "X"
        show_board(game_board)

    else:
        return 0

def main():
    begin = input('Type \'start\' to begin.')
    while (begin != str('start')):
        begin = input('Type \'start\' to begin.')
    for games in range(3):
        for turns in range(6):
            total_turns += 1
            if player_turns() == player_one:
                print("Player One")
                input_check(
                    ship_points['ship_row'],
                    ship_points['ship_col'],
                    player_one, game_board
                )

            elif player_turns() == player_two:
                print("Player Two")
                input_check(
                    ship_points['ship_row'],
                    ship_points['ship_col'],
                    player_two, game_board
                )

            else:
                continue

            if total_turns == 6:
                print("The game is a draw")
                play_again()

            else:
                continue

if __name__ == "main":
    main()

Comment: What is your **question**?
Comment: Why does the game quit?
Answer: Change to the following:
if __name__ == "__main__":

Comment: But this isn't your only problem `UnboundLocalError: local variable 'total_turns' referenced before assignment`
Comment: Works fine! Thanks!
Comment: @moritzg To fix that I put the variable into the main function. so total_turns=0 is right before the incrementation begins.

Why does the program fail to load?


Change Color of each word that starts with specific letter

Question: I'm working in my getter just as a place to test this, but essentially what I'm trying to accomplish is while the users is typing for every instance of 'D' as the first letter of a word change the color of that text to red. The color change is accomplished by bounding the Foreground of a RichTextBox to my Customers.TColor property.
My real logic issues are happening in my TColor property as the program worked when getter was just single line(now commented out) looking for just the first character of Character.Name:
return name.Length > 0 && name[0] == 'D' ? Brushes.Red : Brushes.Black;
However, I'm trying to extend this functionality to every word. Here is my TColor property logic:
 public Brush TColor
    {
        get
        {
            string[] allNames = name.Split(null);
            foreach (string n in allNames)
            {
                if(n[0] == 'D')
                {
                    return Brushes.Red;
                }
                else
                {
                    return Brushes.Black;
                }
            }
            return Brushes.Black;
            //return name.Length > 0 && name[0] == 'D' ? Brushes.Red : Brushes.Black;
        }
        set
        {
            tColor = defaultColor;
        }
    }

What I'm trying to do is get each word individually, so allNames should be splitting the user input into single words then looks at the first char in each of those if it's a D set the brush to red otherwise set the brush for that word to black. If I backspace out of my default values that is set at construction of a Customer object I get a runtime error.
I'm wondering two things
1. if this is the way I should be trying to change the color of an individual word in a RichTextBody.
2. How can I effectively look at the first character of each word and change its color.
Here is what my RichTextBody Currently looks like:
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="10,0,3.4,0" Width="505">

    <RichTextBox x:Name="richTextBox" Height="100" Width="366">
        <FlowDocument>
            <Paragraph Foreground="{Binding Customer.TColor}">
                <Run></Run>
                <Run Text="{Binding Customer.Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
    <Button Content="Update" Command="{Binding UpdateCommand}"/>
</StackPanel>

My relevant variables and properties are as follows:
private string name;
private Brush tColor;
private Brush defaultColor = Brushes.Black;

My constructor is:
public Customer(String customerName)
    {
        Name  = customerName;
        TColor = defaultColor;
    }

My Name property is:
public String Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TColor"));
            //OnPropertyChanged("Name");
        }
    }

Just in case I left anything out, a repo of the project is here
Answer: This example uses the TextChanged handler to format words in a RichTextBox. It'll need to be adapted to your implementation.
XAML
<Grid>
  <RichTextBox x:Name="RichTextBox1" />
</Grid>

Code
public ColorizeWordWindow() {
      InitializeComponent();
      this.RichTextBox1.TextChanged += RichTextBox_TextChanged;
}

    private void RichTextBox_TextChanged(object sender, TextChangedEventArgs e) {
      RichTextBox1.TextChanged -= RichTextBox_TextChanged;
      int position = RichTextBox1.CaretPosition.
                      GetOffsetToPosition(RichTextBox1.Document.ContentEnd);

      foreach (Paragraph para in RichTextBox1.Document.Blocks.ToList())
      {
        string text = new TextRange(para.ContentStart, para.ContentEnd).Text;

        para.Inlines.Clear();

        // using space as word delimiter assumes en-US for locale
        // other locales (Korean, Thai, etc. ) will need adjustment

        var words = text.Split(' ');
        int count = 1;

        foreach (string word in words)
        {
          if (word.StartsWith("D"))
          {
            var run = new Run(word);

            run.Foreground = new SolidColorBrush(Colors.Red);
            run.FontWeight = FontWeights.Bold;
            para.Inlines.Add(run);
          }
          else
          {
            para.Inlines.Add(word);
          }

          if (count++ != words.Length)
          {
            para.Inlines.Add(" ");
          }
        }
      }

      RichTextBox1.CaretPosition = RichTextBox1.Document.ContentEnd.
                                     GetPositionAtOffset(-position);
      RichTextBox1.TextChanged += RichTextBox_TextChanged;
    }

Result


Magento 2 products not being added to cart

Question: The "Add to cart" button changes to "adding" and stays like that. It does nothing after that.It doesn't work from anywhere not even product details page.
Comment: Check magento log file for error descriptions.
Comment: give me the url of website
Comment: `http://localhost/magento2.0/home-furniture/sofa-armchairs.html`
Comment: this is localhost url give me server url..
Comment: i'm testing on localhost
Comment: ok check your console is there any error after clicking button
Comment: no there are no errors
Answer: Change your base URL from localhost to 127.0.0.1.
Using localhost as the domain in your base URL causes problems in Magento 2.
Magento's base URL configuration is located in the core_config_data table. The following values may need to be changed:

web/unsecure/base_url
web/secure/base_url

For example, if you previously had http://localhost/yourproject/, you should change it to http://127.0.0.1/yourproject/
After changing the url, flush the cache (bin/magento cache:flush). You might also need to clear out your var directories.
Answer: go to PHPMyAdmin coreconfigdata
change URL localhost/project to 127.0.0.1/project


Forms miscommunication - asking for best practices

Question: I have built an order form in which the users requires to enter their order details.
One of the fields on the order form is 'Required Number of Passengers', in this field the user enter how many passengers he want to take to the expedition (this is a form submitting for expedition).
The problem I have is:

The user is not usually suppose to request more than the available passengers, or at least he needs to be aware of that.
The site administrators who handle the form submission, doesn't want me to prevent entering more passengers than the available because sometimes when there is an high demand they get additional transportation.
What actually happen is that the users are requesting way more than what they suppose to, they claim that they don't see the alert of how many passengers available are left.

Attached is a screenshot of the order form focus on the relevant area.
I hope you can suggest how to make the alert more visible - right now i think they are visible (but the users think otherwise)

Please note, the red rectangle on the screenshot was added just to show where the relevant field is located
Comment: I can't speak much for how to balance the business process (requirements) and what the system administrator does to accommodate the customers. In terms of the colour, I am not suggesting to use red (unless it is part of the brand or style guide for this purpose), it is just to point out that the blue is similar to other colours that are on the interface as part of the normal style, so it is hard for it to stand out (and for the user to take notice).
Comment: I think it requires some thinking around the business process/logic of the form, because the number of buses also comes into the equation of how someone might fill in the form. In general when you don't put in a sensible rule against a form for validation then you would expect this type of error. This suggests that you should make the logic sensible which will remove the issue around the UI design. I think the user can overlook the availability because of its position and the way it is styled (e.g. if it is in red then people might pick up on it as being rather important).
Comment: @MichaelLai I understand your point but I do have two comments. In regards to the business process, the number of available passengers at the point of submission is Important because you don't want the user to over request seats. But on the same time the organizers (system administrator) would expect 10% of over request because they reserve the option to order a bigger transportation. In regards to color the information in red wont you think it will make them feel as they are doing something wrong, red color is link to an error or something bad such as a low score..
Comment: @MichaelLai I missed your point about the blue color and the fact it is not stand out. Point taken, thanks!
Answer:
Show the warning AFTER the user entered the amount. User focused on entering the info, and the existing message can be just missed (something similar to the banner blindness)
Some animation will draw user's attention
Apply warning color of the entire area to increase visibility and show the relation
Propose a way for the user to get more info and solve this problem

And "60 available out of 180"... This looks a bit disappointing.
Comment: @Silagy I'll be glad to hear from you about the purpose of that number. The UI and interaction can reflect that logic in more elegant way.
Comment: @Silagy you can have something like "Request more seats" link (along with input field with max limit), which reveals a panel/dialog with additional info of how to request more passangeers and the splitting rules.
Comment: Thanks you very much, I like your approach. But I can't remove the alter of "60 seats available out of 80". So the alert you suggested will be in addition to the existing alerts?
Comment: @Silagy yes, you can use the approach along with additional info. Again, 60 of 80 looks a bit ambiguous. If 60 is the available limit, why do you point 80? It it "top max limit"?
Comment: I must say that i don't have a good answer to you. I will ask the customer about it. I might remove it
Comment: I have asked the customer and it seems there is no reason to present "out of"  - the user only needs to know how many seats are available
Comment: It sounds like a very good solution, I will definitely consider that


Is the receiver for my ceiling fan defective or do I need to modify my wall switch?

Question: I just got this minka aire wave ceiling fan an completed the installation but it will not turn on (neither with remote nor switch) UNLESS i take the receiver out altogether and just operate it with the wall switch. I wouldn't mind doing this except there is no drop string to change the fan speed. There are two possibilities here:
1. The receiver is dead
2. The fan does not support wall switch and remote at the same time
I don't care to control the speed or dimmer from the wall just simply need a on/off option.
I did not find any information in the manual but I just want to verify that a ceiling fan with a remote kit installed should not lose operation from the wall switch?
Answer: If your wall switch is a simple mechanical switch I don't see how it could possibly have anything to do with the problem.
You can easily rig up a test apparatus to determine if the receiver/transmitter is working properly. (This worked for my Hunter fan with light fixture, but of course I can't say whether a pure resistive load would test the receiver for a Minka Wave fan.
In summary, cut the cord of a working lamp with say a 40-W incandescent bulb and insert the receiver into the cut as if it were the fan. I used this to determine that my receiver was working and the failure must have been due to a poor connection. I had noticed on removing the receiver that at least one of the stranded wires was poorly stripped (most of the strands cut away). I have now replaced the receiver, re-stripped and tinned the wires (on the receiver not on the fan, those were OK) and the fan/light are now working.
See Why doesn't my ceiling fan's light kit work?
Answer: I know I am a bit late here but the answer is to NEVER trust the seller! The fan was never programmed to begin with; it was suppose to be plug and play type so I disregarded the programming instructions assuming this was not applicable.
Comment: Glad you got it figured out in the end!
Answer: It sounds like the receiver is quite dead, yes.  (While a fan receiver may not support having a wall switch yanking its proverbial powercord out from under it well, it ought to function still when the switch is on!)
I would take the switch out and wirenut the hot and switched wires connected to it together, and then try the fan again -- if it still doesn't work, then ask your fan manufacturer for a replacement receiver.
Comment: Today we had a fairly new Hunter fan with light fixture wired through a receiver switch stop working (neither fan nor light worked). I removed the receiver and both fan and light are now working (no switch but with the two pull chains). I thought maybe the connections were bad, but wanted to see if the fan was working. Now that it works I don't feel like  trying the receiver again. I messed around with a non-contact detector before disconnecting the receiver, and got a positive on the output side of the switch but fan wouldn't run. Could it be the neutrals didn't work to complete the circuit?
Comment: @JimStewart -- a fried receiver would be more likely
Comment: I tested the receiver with a light and found both light and fan worked so I put it back into the fan and it worked. Problem solved; I figured it must have been bad connections. Then I  go in today and it doesn't work! All the other fans on the same circuit work. I turn the breaker off, let it sit off for 20 min and then back on. The problem fan now works. I guess there is an intermittent fault in the receiver. I am leaving it on for an extended period to see if the receiver "burns in", but I expect this will recur.
Answer: When using a remote system, the power to the receiver should always be on. Only use the on/off button on the remote to turn the fan off and on. If you want a wall control in addition to a hand held one, you should buy a wall remote, which has all the functions as the hand held including on/off.  It will also have a small switch that sends power to the receiver, which should always be powered on except in the case of an emergency. There's a lot of electronics involved here which I will not bother to explain, but doing this will prevent any of the above problems from occurring.


Prisma How to automatically update "updatedAt" field of parent element when a child element is created or updated?

Question: Let's say I have this schema:
model User {
   id String @id @default(cuid())
   name String
   email String
   profile Profile?
   createdAt DateTime @default(now())
   updatedAt DateTime @updatedAt
}

model Profile {
   id Int @id @default(autoicrement())
   bio String?
   avatar String?
   user User @relation(fields: [userId], references: [id], onDelete: Cascade)
   userId String @unique
}

Now what I want to archive is, if a user's profile is updated, for example, a bio field is updated, I want the updatedAt field on User model to automatically reflect that and get updated too to the current timestamp.
Any guide, hint or suggestion will be much appreciated!!
Comment: updatedAt is metadata for the User model. If you need to keep track of when the Profile is updated, you should put updatedAt DateTime @updatedAt on the profile itself. Updating the timestamp on parent model will just confuse developer debugging it in the future.
Answer: The easiest way would be to make some wrapper function I think, for example:
const updateUserProfile = (id, data) => {
  return prisma.profile.update({
    where: {
      id
    },
    data: {
      ...data,
      user: {
        update: {
          updatedAt: new Date()
        }
      }
    }
  })
}

Comment: Sorry, to clarify, @Danila, it will be executed on the NodeJS (application) server, aka the Prisma client, not the MySQL or Postgres (database) server.

Database servers have a now() function. You may run multiple application servers around the globe with different server times, but the database server's time should be the source of truth in the database.  If it's not and you query based on time stamp -- you can see where this is going - you'll be returning times from different clocks - some of which may be set to the future or distant past.
Comment: The solution above is probably fine for a hobby project/small scale.

But to illustrate the issue @fotoflo was saying: imagine you have 3 servers running the same application (e.g. NodeJS) behind a load balancer. All 3 servers will have slightly different time. Let's say:

Now let's say Server 3 saves a record. `updatedAt` is +1. Now Server 1 reads `where updatedAt < ..` but the record was saved in the DB according to Server 3's time. There are other examples where this is problematic.
Comment: Hi hi, thanks for this.  it looks to me like this will use the timestamp based on whatever is executing the prisma client, not on the server time, and is prone to causing bugs.
Comment: @fotoflo it will be executed on the server and it will use your server time of course, what bugs it can cause?
Comment: thanks @Danila, sorry to say you are totally incorrect.  Also rude, but hey it's the internet. Again, new Date() executes in the javascript runtime environment, while select now(); executes in the mysql runtime environment.  I'll write the answer when i get.
Comment: @fotoflo It literally does not matter because date will be store in UTC anyway, so if you have 1 server in USA and 1 in Japan you can still do that, *unless* you server time is incorrect for some reason. If you have correct local server time set then it's all good.
Comment: @EamonnGahan please don't try to make a completely different argument now and turn discussion upside down, @fotoflo was saying `servers around the globe with different server times`, not +-1 second issue. If you server time is incorrect then you are up for other issues as well, you can't use any date related business logic at all. Also this discussion is 100% unrelated to prisma and original question, if you have different/better answer to the question - just post it.
Comment: no i was talking generally we want to use the database server's now() function instead of the javascript runtime's time. @EamonnGahan has it right.


My OpenGL program is not drawing filled polygons

Question: I'm trying to learn OpenGL in c++ (I used it in Java) but I have a problem, I make a triangle, but it doesn't draw on GL_FILL and in GL_LINE it just draw a line, I can't find my mistake, I guess my bug is in vertex buffers, but I can't detect it, can anyone help me please?
CglApp.cpp:
    CglApp::CglApp() {

    glm::vec3 vertices[] = {
            {0.5f,  0.5f, 0.0f} ,  // top right
            {0.5f, -0.5f, 0.0f},  // bottom right
            {-0.5f, -0.5f, 0.0f},  // bottom left
            {-0.5f,  0.5f, 0.0f}   // top left
    };
    unsigned int indices[] = {  // note that we start from 0!
            0, 1, 3,  // first Triangle
            //1, 2, 3   // second Triangle
    };

    glm::vec3 vertices2[] = {
            //{0.5f,  0.5f, 0.0f} ,  // top right
            {0.5f, -0.5f, 0.0f},  // bottom right
            {-0.5f, -0.5f, 0.0f},  // bottom left
            {-0.5f,  0.5f, 0.0f}   // top left
    };

    unsigned int indices2[] = {  // note that we start from 0!
            //0, 1, 3,  // first Triangle
            1, 2, 3   // second Triangle
    };

    cglSolidModel.loadModels(vertices,indices);
    cglSolidModel1.loadModels(vertices2,indices2);

}

CglApp::~CglApp() {

}

void CglApp::run() {

    while (!cglWindow.shouldClose()){

        // input
        // -----
        inputManager.processInput(cglWindow.getWindow());

        // render
        // ------
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        cglSolidModel.bind(cglShaders.getDefaultShader());
        cglSolidModel1.bind(cglShaders.getDefaultShader());

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(cglWindow.getWindow());
        glfwPollEvents();

    }

}

CglShaders.cpp
CglShaders::CglShaders() {
    createDefaultShader();
}

CglShaders::~CglShaders() {

}

void CglShaders::createDefaultShader() {

    const char *vertexShaderSource = "#version 330 core\n"
                                     "layout (location = 0) in vec3 aPos;\n"
                                     "void main()\n"
                                     "{\n"
                                     "   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
                                     "}\0";
    const char *fragmentShaderSource = "#version 330 core\n"
                                       "out vec4 FragColor;\n"
                                       "void main()\n"
                                       "{\n"
                                       "   FragColor = vec4(1.0f, 0.9f, 0.2f, 1.0f);\n"
                                       "}\n\0";

    createShader(vertexShaderSource,fragmentShaderSource);

}

void CglShaders::createShader(const char *vertexShaderSource, const char *fragmentShaderSource) {

    // build and compile our shader program
    // ------------------------------------
    // vertex shader
    unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    // check for shader compile errors
    int success;
    char infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // fragment shader
    unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);
    // check for shader compile errors
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // link shaders
    unsigned int shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    // check for linking errors
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    shaderPrograms.push_back(shaderProgram);

}

CglSolidModel.cpp
CglSolidModel::CglSolidModel() {

}

CglSolidModel::~CglSolidModel() {

}

void CglSolidModel::loadModels(glm::vec3 vertices[], unsigned int indices[]) {

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);
    // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)nullptr);
    glEnableVertexAttribArray(0);

    // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // remember: do NOT unbind the EBO while a VAO is active as the bound element buffer object IS stored in the VAO; keep the EBO bound.
    //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
    // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
    glBindVertexArray(1);

    // uncomment this call to draw in wireframe polygons.
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

}

void CglSolidModel::bind(unsigned int shaderProgram) {

    // draw our first triangle
    glUseProgram(shaderProgram);
    glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
    //glDrawArrays(GL_TRIANGLES, 0, 6);
    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
    // glBindVertexArray(0); // no need to unbind it every time

}

Im creating the VBO, EBO and VBA inside each SolidModel.
Only two lines for two different triangles with GL_LINE
Answer: A problem I see in your code is that you take the sizeof() an unsized array, which yields the size of the pointer to that array and not the size of array itself.
void CglSolidModel::loadModels(glm::vec3 vertices[], unsigned int indices[]) {
{
    ...
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    ...
}

Here is a small test case that demonstrates the issue.
void func(int array[]) {
    printf("sizeof(array) = %d\n", sizeof(array));
}

int myArray[10];
func(myArray);

Output when compiled for x64:
sizeof(array) = 8

This is the size of the 64bit pointer to the array. You would expect 10*sizeof(int) = 40. In your code (assuming x64) it only sends 8 bytes of the vertice array to the VBO, which is enough to fill the XY coordinates for the first vertex. That goes some way to explaining why you only see 1 partial triangle.
It's not possible for C++ to determine the size of an unsized array. In C++ int array[]; is equivalent to const int *array; and so sizeof(array) is the same in both cases. This isn't the case for sized arrays, int array[10]; would give you 40 bytes as you would expect.
I would recommend you pass another parameter which contains the size of the array or use a container like std::vector which stores the size along with the array. Be aware that std::vector returns the number of elements and not the number of bytes which glBufferData expects.
Comment: Oh I understand, thanks so much, I'm gonna use sizeof(vertices[0])*vertexCount in this case.
Comment: Happy to help. One small thing I noticed in your code was glBindVertexArray(1) after your VAO/VBO is loaded - What is object #1? Usually glBindVertexArray(0) is used to unbind VAO to openGL. Infact the call glBindBuffer(GL_ARRAY_BUFFER, 0); looks risky as you still have your VAO bound, I would suggest a call to glBindVertexArray(0) is all that is needed after initialisation, this will leave your VAO in its setup state