Piix4_SMBus: 000:00:07.3: Host SMBus controller bus not enabled

Question: I have been using Ubuntu on VMware Player; today when I logged into VMware, it showed updates available for Ubuntu 15.xx. I allowed the updates and after downloading all the packages it restarted automatically, but never booted back. It is throwing messages like
Piix4_SMBus: 000:00:07.3: Host SMBus controller bus not enabled
failed to start /etc/rc.local compatibility

Please describe a way to fix it!
Comment: Updated received was 'Wily Warewolf'
Comment: There has been a [fix for this problem](http://whitehatty.com/2012/09/30/vmware-fusion-5-fix-ubuntu-linux-12-04-host-smbus-controller-not-enabled/) for a while, but you need to access your Ubuntu installation 'hard disk' to edit the file `/etc/modprobe.d/blacklist.conf` and add the line `blacklist i2c-piix4`  .  You may be able to do this by booting the VM from an ISO file for Ubuntu, and choosing 'Try Ubuntu'
Comment: Hi Charles, thanks for your quick response. Could you please elaborate the steps as I am not really good in doing this. How do I access Ubuntu Installation hard disk? Please provide the navigation. I am using VMware Player and installed Ubuntu on VMPlayer. Apologies for the trouble.
Comment: Had the exact same problem today with Debian 13 (Trixie) under VMWare Workstation 17, apparently after installing packet `webcam`. [This answer](https://askubuntu.com/a/691737/614483) mainly gave me the trick!
Answer: First, add this line in your vmx file to increase the boot time to 50s
bios.bootDelay = "50000"

Start the VM, hold the left shift key down, then hit Enter.
In the grub menu, choose Advanced options for Ubuntu -> Recovery mode.  Once the system boots, choose 'Root' to drop into a root shell.
In the root shell, enter the following commands
mount -o remount,rw /
nano /etc/modprobe.d/blacklist.conf

go down a few lines (almost anywhere) and enter the line
blacklist i2c-piix4

Then press ctrl+o to save the file, and ctrl+x
Finally, enter the command
reboot
Comment: Thanks Charles for the detailed answer. I am able to resolve the first issue. I almost shouted 'Eurekha', but it did not boot yet :-(, still another issue is pending, Error: failed to start /etc/rc.local compatibility
see "sstemctl status rc-local.service" for details. Request you to provide your valuable solution. Appreciate your time & patience.
Comment: @MuraliG  You'll probably need to open a separate question, and you should try cross-posting into the [vmware community forums.](https://communities.vmware.com/welcome)
Comment: I had to additionally run `update-initramfs -u` after editing `blacklist.conf`
Comment: Sorry to hear continues problems.
Comment: Yeah...hopefully everything gets resolved with the solution you are going to provide. But blacklist i2c-piix4 is a good learning for me. Your crystal clear answer helped me in resolving that.
Comment: Did you happen to remove the vmtools from your virtual machine before updating?
Comment: 2nd question, if you execute `systemctl status rc-local.service` in the machine, what happens?
Comment: Initially I was not getting internet connection to the VM. So I have installed the vmtools and then internet connection was active. I have got the updates as the internet connection was active and I performed update. when I gave the command systemctl status rc-local.service i got the below:                                                                                Loaded: loaded (/lib/systemd/system/rc-local/service;static;vendor preset:enabled)
Drop-In: /lib/systemd/system/rc-local/service.d
          debian.conf
Active: inactive(dead)
Comment: Well, I don't see anything that is wrong there, but it's really gone beyond what I can help much with.
Comment: No problem Charles. Thanks a lot for your support. Have a great weekend.
Comment: I would request someone in the forum to help me with this. I am trying by exploring through various forums to close this, but no luck. Please need your support in closing this.
Comment: @MuraliG I did find another Ubuntu forum with a question related to this, where rc.local was being used to load the vmtools and caused problems.  Try this:  Log into the recovery mode as above, then `cd /etc` followed by `mv rc.local rc.local.old` and `touch rc.local` and chmod 755 rc.local`.  Then reboot.  This will copy your current rc.local into a different file, and create a new, empty, rc.local
Comment: Hi Charles, when I tried moving rc.local to rc.local.old I am getting error message "cannot move, read only file system". Should I change any permissions, please guide. Thanks a lot for coming back.
Comment: Ah - you forgot the part `mount -o remount,rw /` - when you start in the recovery mode, your computer is in read-only mode be default...
Comment: Dear Charles, I tried the above options but still no luck. I posted this in VMware forums also. https://communities.vmware.com/message/2552370#2552370. I have attached the screenshots also for your reference.
Comment: I know this post is old. but I have the same problem. when I do the @CharlesGreen said, my ubuntu is boot, but after some minutes (when I worked with it). It is hanging .how can I solve this problem? Help me plz :)
Comment: @H.Ghassami  I certainly do hope that you find an answer to your problem - I no longer run VMWare, but instead use KVM/QEMU to host virtual machines.  You could search, and post, your problem in the [vmware community forum](https://communities.vmware.com) perhaps, and receive some assistance.
Comment: Did not work for VMware Ubuntu 64-bit 18.04 on macOS
Comment: @TimD1 I don't think you should have to do that, but it has been a long time since I ran VMWare!
Comment: I too had to run `update-initramfs -u` only to find that I had made a small mistake in `/etc/fstab` - I had changed the root mount from `/` to `/i` - likely by pressing `i` in the `vi` editor :) When `update-initramfs -u` complained it could not find what disk to boot from, I knew to check `/etc/fstab`; removed the `i` from `/i`, re-ran `update-initramfs -u` (this time really necessary to set the correct root/boot patiation), and it all worked fine again. Also blacklisted the i2c-piix4 at the same time, which I now suspect was no the original issue, just a (now fixed) error during boot.
Comment: I know this forum is Ubuntu-related but, in case someone has the same problem under Debian (13), as it happened to me, the file to append is slightly different: `/etc/modprobe.d/intel-microcode-blacklist.conf`.
Answer: The method above didn't work for me on Ubuntu 16.10 and VMWare Workstation 12.5.1..
Boot into Ubuntu Recovery Mode --> drop into the root shell and open the kernel blacklist config file.
nano /etc/modprobe.d/blacklist.conf

Then add this line into the file and save.
blacklist intel_powerclamp

I found this solution from this post:
https://websiteforstudents.com/question/student-question-resolve-ubuntu-16-10-piix4_smbus-host-smbus-controller-bus-not-enabled/
Answer: At first, open *.vmx file from your VMware folder via notepad. Then add this line to the file and save it.
cpuid.1.eax = "0000:0000:0000:0001:0000:0110:1010:0101"

The problem will be fixed.
Comment: This option worked for me, but only with one CPU -- had to reduce number of CPUs, before it worked. Now I can disable smbus in /etc/modprobe.d.  I tried blacklisting from grub but none worked - OpenSUSE Tumbleweed 20180124 - Thanks!
Comment: didn't work for me
Answer: Although I'm late to the party, the solution to your other problem (failed to start /etc/rc.local compatibility etc., as described in the later comments to Charles Green's answer) is most probably (at least was for me), to wipe old, incompatible vmhgfs (shared VM disk) settings/module, since they break a couple of things.
First, the module doesn't load if there are version mismatch etc. Remove vmhgfs from /etc/modules, and now the init should run properly.
Secondly, if you added a fstab entry for your vmhgfs, systemd-fstab-generator generates a systemd startup task for it, also resulting in failed systemctl unit. Comment out or remove your vmhgfs line in fstab, and remove the relevant mnt-*.mount (e.g. mnt-vmhgfs.mount) files from your /run/systemd/generator. That should fix the 2nd part of the problem.
Answer: I was able to solve the problem by dropping into safe mode and running clean.
EDIT:
This was done holding shift when rebooting the VM. when in the grub go to "advanced options". Then in that menu run "clean"
Comment: Could you edit your answer and provide more detail about how to enter safe mode and run clean ?


Is this plumbing repair sound?

Question: I opened up a wall as part of a project and discovered some obviously newer pieces of copper pipe on one of the water supply lines. The drywall shows evidence of water stains as does the drywall and doors on the floor below. There must have been a leak in the pipe that was subsequently repaired (before I bought the house).
Looking at the repaired water line, I don't see any solder - it looks as if the new pieces are just crimped on. Is this an acceptable way of repairing a leak in copper, or should I be worried about it leaking in the future?
Comment: These seem to be called press-fit fittings.
Answer: These are copper press fit connectors. They have "o"rings installed at each end of the connector.

Once the connectors are in place, they are crimped with a special, and expensive, tool. They are supposed to be as good as sweating and Sharkbite connectors but they are not reusable.
Answer: Those fittings are crimped on with a very expensive machine and are good if done properly.
If not done well they leak straight away and I had to have the plumber come back to do a few on stainless pipe...

Is this plumbing repair sound?


Start a project

Question: Occurred some errors while I was starting to make a project.
I just installed all packages. tried to create new project. it is my first time to work with react-native.
what's wrong? what should I do?
This will walk you through creating a new React Native project in /TestApp
Installing react-native...
Consider installing yarn to make this faster: https://yarnpkg.com
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: react@undefined
npm WARN node_modules/react
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer react@"18.1.0" from firstname.lastname@example.com
npm WARN node_modules/react-native
npm WARN   react-native@"*" from the root project
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: react@undefined
npm WARN node_modules/react
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer react@"^16.0.0 || ^17.0.0 || ^18.0.0" from firstname.lastname@example.com
npm WARN node_modules/react-native/node_modules/react-shallow-renderer
npm WARN   react-shallow-renderer@"^16.15.0" from email@example.com
npm WARN   node_modules/react-native
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: react@undefined
npm WARN node_modules/react
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer react@"^16.8.0 || ^17.0.0 || ^18.0.0" from email@example.com
npm WARN node_modules/react-native/node_modules/use-sync-external-store
npm WARN   use-sync-external-store@"^1.0.0" from firstname.lastname@example.com
npm WARN   node_modules/react-native
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: @babel/preset-env@undefined
npm WARN node_modules/@babel/preset-env
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer @babel/preset-env@"^7.1.6" from email@example.com
npm WARN node_modules/jscodeshift
npm WARN   jscodeshift@"^0.13.1" from email@example.com
npm WARN   node_modules/react-native-codegen
npm ERR! code FETCH_ERROR
npm ERR! errno FETCH_ERROR
npm ERR! invalid json response body at https://registry.npmjs.org/react reason: Unexpected end of JSON input

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-11-27T19_45_05_880Z-debug.log
Error: Command failed: npm install --save --save-exact react-native
    at checkExecSyncError (child_process.js:635:11)
    at execSync (child_process.js:671:15)
    at run (/usr/local/lib/node_modules/react-native-cli/index.js:294:5)
    at createProject (/usr/local/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/usr/local/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/usr/local/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14) {
  status: 1,
  signal: null,
  output: [ null, null, null ],
  pid: 45745,
  stdout: null,
  stderr: null
}
Command `npm install --save --save-exact react-native` failed.

This is my OS information:
Operating System: Debian GNU/Linux 11
KDE Plasma Version: 5.20.5
KDE Frameworks Version: 5.78.0
Qt Version: 5.15.2
Kernel Version: 5.10.0-19-amd64

I install all requirments.
I need Terminal Commands what i should to do.
I would be appreciated you.
Answer: Try using expo. https://docs.expo.dev/get-started/create-a-new-app/
Expo, in my opinion, does a better job than react-native walking through new users on how to use react-native.
run npx create-expo-app my-app this will create a new app called "my-app".
Or you could run npx create-expo-app --template to begin with a starter app. I like to use 'Navigation (TypeScript)'.
The expo link will explain how to set up your app and how to run your app in a simulator or with the expo go app on your phone. It's a great resource. There is also a tutorial that explains in depth how to create, style, and build an app using react-native.
Hope that helped!
Comment: I received this error:
`✖ Something went wrong installing JavaScript dependencies. Check your npm logs. Continuing to create the app.`
and then when I wanna run `npm run android`
I get another error: `> firstname.lastname@example.com android
> expo start --android

sh: 1: expo: not found`

Start a project


Fastest way to compute point to triangle distance in 3D?

Question: One obvious method for computing the minimum distance from a point to a 3D triangle is to project the point onto the plane of the triangle, determine the barycentric coordinates of the resulting point, and use them to determine whether the projected point lies within the triangle.  If not, clamp its the barycentric coordinates to be in the range [0,1], and that gives you the closest point that lies inside the triangle.
Is there a way to speed this up or simplify it somehow?
Comment: Clamping the barycentric coordinates does not give the orthogonal projection to the closest edge and therefore not the correct distance if one point on the edges (without vertices) is closest.
Answer: There are different approaches to finding the distance from a point P0 to a triangle P1,P2,P3.

The 3D method.
Project the point onto the plane of the triangle and use barycentric coordinates or some other means of finding the closest point in the triangle.  The distance is found in the usual way.
The 2D method.  Apply a translation/rotation to the points so that P1 is on the origin, P2 is on the z-axis, P3 in the yz plane.  Projection is of the point P0 is trivial (neglect the x coordinate).  This results in a 2D problem. Using the edge equation it's possible to determine the closest vertex or edge of the triangle.  Calculating distance is then easy-peasy.

This paper compares the performance of both with the 2D method winning.
Comment: The link is broken, and there is no answer actually (what to do exactly after projection).
Comment: The paper is definitely not scientifically correct. Author should definitely present whole code alongside the paper. I have working implementation which uses at most 2 square roots. And it can be brought down to 1 square root using 2 parameter parametrization of triangle - as can be seen in https://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistPointTriangle.h
Answer: I'll lead with my test case results.

The test case code and implementation is in C#
    public void ClosestPointToShouldWork()
    {
        var r = new Random(0);
        double next() => r.NextDouble() * 5 - 1;
        var t = new Triangle(new Vector3(0,0,0), new Vector3(3.5,2,0), new Vector3(3,0.0,0));

        DrawTriangle(t);

        var hash = new Vector3( 0, 0, 0 );
        for (int i = 0; i < 800; i++)
        {
            var pt = new Vector3( next(), next(), 0 );
            var pc = t.ClosestPointTo( pt );
            hash += pc;

            DrawLine(pc,pt);
        }

        // Test the hash
        // If it doesn't match then eyeball the visualization
        // and see what has gone wrong

        hash.ShouldBeApproximately( new Vector3(1496.28118561104,618.196568578824,0),1e-5  );

    }

The implementation code is fiddly as I have a number of framework classes. Hopefully you can treat this as pseudo code and pull out the algorithm. The raw vector types are from https://www.nuget.org/packages/System.DoubleNumerics/.
Note that some of the properties of Triangle could be cached to improve performance.
Note that to return the closest point does not require any square roots and does not require transforming the problem to 2D.
The algorithm first quickly tests if the test point is closest to an end point region. If that is inconclusive it then tests the edge external regions one by one. If those tests fail then the point is inside the triangle. Note that for randomly selected points far from the triangle it is most likely that the closest point will be a corner point of the triangle.
public class Triangle
{
    public Vector3 A => EdgeAb.A;
    public Vector3 B => EdgeBc.A;
    public Vector3 C => EdgeCa.A;

    public readonly Edge3 EdgeAb;
    public readonly Edge3 EdgeBc;
    public readonly Edge3 EdgeCa;

    public Triangle(Vector3 a, Vector3 b, Vector3 c)
    {
        EdgeAb = new Edge3( a, b );
        EdgeBc = new Edge3( b, c );
        EdgeCa = new Edge3( c, a );
        TriNorm = Vector3.Cross(a - b, a - c);
    }

    public Vector3[] Verticies => new[] {A, B, C};

    public readonly Vector3 TriNorm;

    private static readonly RangeDouble ZeroToOne = new RangeDouble(0,1);

    public Plane TriPlane => new Plane(A, TriNorm);

    // The below three could be pre-calculated to
    // trade off space vs time

    public Plane PlaneAb => new Plane(EdgeAb.A, Vector3.Cross(TriNorm, EdgeAb.Delta  ));
    public Plane PlaneBc => new Plane(EdgeBc.A, Vector3.Cross(TriNorm, EdgeBc.Delta  ));
    public Plane PlaneCa => new Plane(EdgeCa.A, Vector3.Cross(TriNorm, EdgeCa.Delta  ));

    public static readonly  RangeDouble Zero1 = new RangeDouble(0,1);

    public Vector3 ClosestPointTo(Vector3 p)
    {
        // Find the projection of the point onto the edge

        var uab = EdgeAb.Project( p );
        var uca = EdgeCa.Project( p );

        if (uca > 1 && uab < 0)
            return A;

        var ubc = EdgeBc.Project( p );

        if (uab > 1 && ubc < 0)
            return B;

        if (ubc > 1 && uca < 0)
            return C;

        if (ZeroToOne.Contains( uab ) && !PlaneAb.IsAbove( p ))
            return EdgeAb.PointAt( uab );

        if (ZeroToOne.Contains( ubc ) && !PlaneBc.IsAbove( p ))
            return EdgeBc.PointAt( ubc );

        if (ZeroToOne.Contains( uca ) && !PlaneCa.IsAbove( p ))
            return EdgeCa.PointAt( uca );

        // The closest point is in the triangle so
        // project to the plane to find it
        return TriPlane.Project( p );

    }
}

And the edge structure
public struct Edge3
{

    public readonly Vector3 A;
    public readonly Vector3 B;
    public readonly Vector3 Delta;

    public Edge3(Vector3 a, Vector3 b)
    {
        A = a;
        B = b;
        Delta = b -a;
    }

    public Vector3 PointAt(double t) => A + t * Delta;
    public double LengthSquared => Delta.LengthSquared();

    public double Project(Vector3 p) => (p - A).Dot( Delta ) / LengthSquared;

}

And the plane structure
public struct Plane
{
    public Vector3 Point;
    public Vector3 Direction;

    public Plane(Vector3 point, Vector3 direction )
    {
            Point = point;
            Direction = direction;
    }

    public bool IsAbove(Vector3 q) => Direction.Dot(q - Point) > 0;

}

Comment: How do you calculate TriPlane.Project( p ) without using a square root?
Comment: Can you describe how you do your return TriPlane.Project( p ); ? I try with your code  return (Vector3.ProjectOnPlane(p, TriNorm));, but it doesn't work well
Comment: Ok, considere adding this function into the Plane struct:
`public Vector3 Project(Vector3 randomPointInPlane, Vector3 normalPlane, Vector3 pointToProject)
    {
        Vector3 v = pointToProject - randomPointInPlane;
        Vector3 d = Vector3.Project(v, normalPlane.normalized);
        Vector3 projectedPoint = pointToProject - d;
        return (projectedPoint);
    }`
Answer: Assuming you're using one of the known fast algorithms, the only way to speed it up is when you are doing a lot of measurements on a lot of triangles. In that case, you can keep a lot of quantities precomputed in "edge" or "winding" structures. Instead of storing the 3 points, you store meshes comprised of edge structures. Projection then becomes very quick and barycentric tests can be coded so that they are branch-predictable.
The real key is to just keep everything in cache. Processors can do MUL and DIV in nearly 1 clock cycle so memory is usually the bottleneck.
Also, consider writing the algo in SSE3 or something similar (such as Mono's SIMD support). It's work, but you can usually do a couple triangles at a time if you think hard enough about it.
I'll try to find some papers on the topic, but you might want to Google for "Ray Mesh Intersection". That will bring up all the great work from the 80s and 90s when people worked hard on optimizing this stuff.
Comment: "Processors can do ... DIV in nearly 1 clock cycle so memory is usually the bottleneck." - really? The last figure I've heard was closer to 17 cycles.
Answer: I don't think the barycentric coordinate method can be sped up much per se, but you can pre-compute some some things if you will be testing many points against the same triangle.
Here is some robust code that I wrote for computing this projection, based on this answer combined with this post (which is in turn based on the book Realtime Collision Detection).
Note that you can precompute anything that doesn't depend directly or indirectly upon p (which saves around half the computational work for each test, if you're reusing the same triangle many times).
The code is designed to return null if the orthogonal projection of the point p onto the plane of the triangle does not fall within the triangle. You could extend this to find the closest point on the edge of a triangle if the barycentric coordinates are out of range, by computing the projection of the projection point onto each of the triangle's edge vectors, then checking whether the projection is within any pair of the triangle's vertices. (If not, a corner vertex would be the closest point.) For my purposes though, I only wanted orthogonal projections, which is why this code returns null if the orthogonal projection does not fall within the triangle.
The code is in Java, using the JOML linear algebra library.
/**
 * Find the closest orthogonal projection of a point p onto a triangle given by three vertices
 * a, b and c. Returns either the projection point, or null if the projection is not within
 * the triangle.
 */
public static Vector3d closestPoint(Vector3d p, Vector3d a, Vector3d b, Vector3d c) {
    // Find the normal to the plane: n = (b - a) x (c - a)
    Vector3d n = b.sub(a, new Vector3d()).cross(c.sub(a, new Vector3d()));

    // Normalize normal vector
    double nLen = n.length();
    if (nLen < 1.0e-30) {
        return null;  // Triangle is degenerate
    } else {
        n.mul(1.0f / nLen);
    }

    //    Project point p onto the plane spanned by a->b and a->c.
    //
    //    Given a plane
    //
    //        a : point on plane
    //        n : *unit* normal to plane
    //
    //    Then the *signed* distance from point p to the plane
    //    (in the direction of the normal) is
    //
    //        dist = p . n - a . n
    //
    double dist = p.dot(n) - a.dot(n);

    // Project p onto the plane by stepping the distance from p to the plane
    // in the direction opposite the normal: proj = p - dist * n
    Vector3d proj = p.add(n.mul(-dist, new Vector3d()), new Vector3d());

    // Find out if the projected point falls within the triangle -- see:
    // http://blackpawn.com/texts/pointinpoly/default.html

    // Compute edge vectors
    double v0x = c.x - a.x;
    double v0y = c.y - a.y;
    double v0z = c.z - a.z;
    double v1x = b.x - a.x;
    double v1y = b.y - a.y;
    double v1z = b.z - a.z;
    double v2x = proj.x - a.x;
    double v2y = proj.y - a.y;
    double v2z = proj.z - a.z;

    // Compute dot products
    double dot00 = v0x * v0x + v0y * v0y + v0z * v0z;
    double dot01 = v0x * v1x + v0y * v1y + v0z * v1z;
    double dot02 = v0x * v2x + v0y * v2y + v0z * v2z;
    double dot11 = v1x * v1x + v1y * v1y + v1z * v1z;
    double dot12 = v1x * v2x + v1y * v2y + v1z * v2z;

    // Compute barycentric coordinates (u, v) of projection point
    double denom = (dot00 * dot11 - dot01 * dot01);
    if (Math.abs(denom) < 1.0e-30) {
        return null; // Triangle is degenerate
    }
    double invDenom = 1.0 / denom;
    double u = (dot11 * dot02 - dot01 * dot12) * invDenom;
    double v = (dot00 * dot12 - dot01 * dot02) * invDenom;

    // Check barycentric coordinates
    if ((u >= 0) && (v >= 0) && (u + v < 1)) {
        // Nearest orthogonal projection point is in triangle
        return proj;
    } else {
        // Nearest orthogonal projection point is outside triangle
        return null;
    }
}

Answer: To find the distance, first one has to compute the closest point in triangle. The following code for finding the closest point in 3D triangle ABC to point P is taken from highly optimized Embree library:
Vec3fa closestPointTriangle(Vec3fa const& p, Vec3fa const& a, Vec3fa const& b, Vec3fa const& c)
{
  const Vec3fa ab = b - a;
  const Vec3fa ac = c - a;
  const Vec3fa ap = p - a;

  const float d1 = dot(ab, ap);
  const float d2 = dot(ac, ap);
  if (d1 <= 0.f && d2 <= 0.f) return a; //#1

  const Vec3fa bp = p - b;
  const float d3 = dot(ab, bp);
  const float d4 = dot(ac, bp);
  if (d3 >= 0.f && d4 <= d3) return b; //#2

  const Vec3fa cp = p - c;
  const float d5 = dot(ab, cp);
  const float d6 = dot(ac, cp);
  if (d6 >= 0.f && d5 <= d6) return c; //#3

  const float vc = d1 * d4 - d3 * d2;
  if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f)
  {
      const float v = d1 / (d1 - d3);
      return a + v * ab; //#4
  }

  const float vb = d5 * d2 - d1 * d6;
  if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f)
  {
      const float v = d2 / (d2 - d6);
      return a + v * ac; //#5
  }

  const float va = d3 * d6 - d5 * d4;
  if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f)
  {
      const float v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
      return b + v * (c - b); //#6
  }

  const float denom = 1.f / (va + vb + vc);
  const float v = vb * denom;
  const float w = vc * denom;
  return a + v * ab + w * ac; //#0
}

Here dot(p,q) = p.x*q.x + p.y*q.y + p.z*q.z is dot product of vectors p and q.
The algorithm is based on partitioning the plane with the triangle on 7 regions by drawing two rays from each vertex outside the triangle orthogonal the adjacent edges of the vertex:

Each if in the algorithm corresponds to Region #1-6. And the section after the last if - to triangle's internals or Region #0.
Comment: Good source code, but I think the illustration is wrong. Based on the code, the regions are like that: http://const.me/tmp/triangle-regions.png
Comment: This is exactly what I was looking for - it was very fast in my benchmarks compared to my old method.


Simple OpenCL program compiles and runs but output is incorrect

Question: I wrote a simply OpenCL program based off the SDK and it compiles and runs, however the output is wrong.  Is there something I'm doing wrong?
Any suggestions for learning to debug C and OpenCL is much appreciated.  I'm quite new to the platform.
Code is below.
The output in array c is all zeros.
Thanks.
test_opencl.h
<code>#ifndef _TEST_OPENCL_H_
#define _TEST_OPENCL_H_

int main( int argc, const char** argv);
int runTest( int argc, const char** argv);

#endif
</code>
test_opencl.cl
<code>// simple test of adding a[i] to b[i] to get c[i]
__kernel void add_array(__global float *a, __global float *b, __global float *c)
{
    int xid = get_global_id(0);
    c[xid] = a[xid] + b[xid];
}
</code>
test_opencl.cpp
<code>// standard utility and system includes
#include <oclUtils.h>
#include "test_opencl.h"

// OpenCL error catcher
cl_int err = 0;

// Main Program
// *********************************************************************
int main( int argc, const char** argv)
{
    // set logfile name and start logs
    shrSetLogFileName ("test_opencl.txt");
    shrLog(LOGBOTH, 0, "%s Starting...\n\n", argv[0]);

    // run the main test
    int result = runTest(argc, argv);
    shrCheckError(result, 0);

    // finish
    shrEXIT(argc, argv);
}

//! Run a simple test for OPENCL
// *********************************************************************
int runTest( int argc, const char** argv)
{
    cl_context gpu_context;
    cl_command_queue cmd_queue;
    cl_program program;
    cl_kernel test_kernel;

    const size_t szGlobalWorkSize = 10;
    const size_t szLocalWorkSize = 10;

    // size of memory required to store the array
    const unsigned int mem_size = sizeof(int) * 10;

    // create the OpenCL context on a GPU device
    gpu_context = clCreateContextFromType(0, CL_DEVICE_TYPE_GPU, NULL, NULL, &err);
    shrCheckError(err, CL_SUCCESS);

    // get devices
    cl_device_id device;
    if( shrCheckCmdLineFlag(argc, argv, "device") ) {
      int device_nr = 0;
      shrGetCmdLineArgumenti(argc, argv, "device", &device_nr);
      device = oclGetDev(gpu_context, device_nr);
    } else {
      device = oclGetMaxFlopsDev(gpu_context);
    }

    // create a command-queue
    cmd_queue = clCreateCommandQueue(gpu_context, device, 0, &err);
    shrCheckError(err, CL_SUCCESS);

    // allocate and initalize host memory
    int a[10], b[10], c[10];
    for (int i = 0; i < 10; i++) {
        a[i] = i;
        b[i] = i * i;
    }

    // create buffers on device
    cl_mem vol_a = clCreateBuffer(gpu_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size, a, &err);
    shrCheckError(err, CL_SUCCESS);

    cl_mem vol_b = clCreateBuffer(gpu_context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size, b, &err);
    shrCheckError(err, CL_SUCCESS);

    cl_mem vol_c = clCreateBuffer(gpu_context, CL_MEM_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, mem_size, c, &err);
    shrCheckError(err, CL_SUCCESS);

    // copy data from host to device
    err = clEnqueueWriteBuffer(cmd_queue, vol_a, CL_TRUE, 0, mem_size, a, 0, NULL, NULL);
    err |= clEnqueueWriteBuffer(cmd_queue, vol_b, CL_TRUE, 0, mem_size, b, 0, NULL, NULL);
    shrCheckError(err, CL_SUCCESS);

    // Program Setup
    size_t program_length;
    char* source_path = shrFindFilePath("test_opencl.cl", argv[0]);
    shrCheckError(source_path != NULL, shrTRUE);
    char *source = oclLoadProgSource(source_path, "", &program_length);
    shrCheckError(source != NULL, shrTRUE);

    // create the program
    program = clCreateProgramWithSource(gpu_context, 1, (const char **)&source, &program_length, &err);
    shrCheckError(err, CL_SUCCESS);

    // build the program
    err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
    if (err != CL_SUCCESS)
    {
        // write out standard error, Build Log and PTX, then return error
        shrLog(LOGBOTH | ERRORMSG, err, STDERROR);
        return(EXIT_FAILURE);
    }

    clFinish(cmd_queue);

    shrLog(LOGBOTH, 0, "%s Starting kernel operation...\n\n", argv[0]);

    // create the test kernel
    test_kernel = clCreateKernel(program, "add_array", &err);
    shrCheckError(err, CL_SUCCESS);

    // set the args values for the kernel
    err  = clSetKernelArg(test_kernel, 0, sizeof(cl_mem), (void *) &vol_a);
    err |= clSetKernelArg(test_kernel, 1, sizeof(cl_mem), (void *) &vol_b);
    err |= clSetKernelArg(test_kernel, 2, sizeof(cl_mem), (void *) &vol_c);
    shrCheckError(err, CL_SUCCESS);

    err = clEnqueueNDRangeKernel(cmd_queue, test_kernel, 1, NULL, &szGlobalWorkSize, NULL, 0, NULL, NULL);
    shrCheckError(err, CL_SUCCESS);

    clFinish(cmd_queue);

    // copy result from device to host
    err = clEnqueueReadBuffer(cmd_queue, vol_c, CL_TRUE, 0, mem_size, c, 0, NULL, NULL);
    shrCheckError(err, CL_SUCCESS);

    int d[10];
    err = clEnqueueReadBuffer(cmd_queue, vol_a, CL_TRUE, 0, mem_size, d, 0, NULL, NULL);
    shrCheckError(err, CL_SUCCESS);

    clFinish(cmd_queue);

    shrLog(LOGBOTH, 0, "%s Finished kernel operation...\n\n", argv[0]);

    bool passed = true;

    for (int i = 0; i < 10; i++) {
        if (c[i] != i + i * i)
            passed = false;
            shrLog(LOGBOTH, 0, "c = %d    d = %d\n", c[i], d[i]);
    }

    if (passed)
        shrLog(LOGBOTH, 0, "%s Test Passed\n\n", argv[0]);
    else
        shrLog(LOGBOTH, 0, "%s Test Failed\n\n", argv[0]);

    // cleanup OpenCL
    clReleaseMemObject(vol_a);
    clReleaseMemObject(vol_b);
    clReleaseMemObject(vol_c);

    clReleaseKernel(test_kernel);
    clReleaseProgram(program);
    clReleaseCommandQueue(cmd_queue);
    clReleaseContext(gpu_context);

    return 0;
}
</code>
Answer: The problems in the code and the solution can be found here.
Comment: you should perhaps mark yourself as correct so this doesn't show up on the unanswered list? (thanks for posting the answer, even if it was someone else who spotted it... :o)


What kind of circuit breaker is this?

Question: Breaker #4 in the picture is wired to my kitchen lights and living room outlets. It keeps tripping every few days. I thought maybe we overloaded our living room at first, but it tripped this morning with only lights and TV on.
Now I'm thinking it might be a bad breaker, but when I went to Home Depot to buy another one, there were no Square D breakers with that little white button on top.
Comment: The arc-fault breakers are in individual packaging and are much more expensive than regular breakers, which may be why you didn't notice them. They're required in new construction, so HD certainly stocks them. It's unlikely that you have a bad breaker. Some device is probably arcing current to the neutral.
Comment: @DragonYen -- that's a QO in the picture, not a HOM
Comment: It looks like it might be a GFCI, AFCI or combo breaker. with the panel cover off, is there a white wire coming directly out of the base of the breaker?
Comment: @isherwood `Some device is probably dropping current to the neutral`. What does this mean?
Comment: https://en.wikipedia.org/wiki/Arc-fault_circuit_interrupter
Answer: That is a Square D QO series breaker. The one in question is an AFCI, or arc-fault breaker.
The early incarnations of QO AFCIs had some issues. There were blue, green, purple and I believe another color "test" buttons. How old is this breaker?
An AFCI can trip due to electrical "noise" on the line, motor brushes like in vacuums, etc, any kind of arcing or sparking in the circuit, frayed cords, and more.
Here is a good troubleshooting guide for AFCI breakers right from Square D:
http://static.schneider-electric.us/docs/Circuit%20Protection/Miniature%20Circuit%20Breakers/Arc%20Fault%20Circuit%20Interrupters-AFCI/0760DB0204.pdf
Also, more from Square D: http://www.schneider-electric.us/en/faqs/FA125415/
Here is another very good answer to the same question: https://diy.stackexchange.com/a/74242/19875

What kind of circuit breaker is this?


Float left  + transition on height = issues

Question: I am applying a transition hover effect that causes the
 to enlarge.
Problem is the last child on ever row, when hovered over, pushes the next 2
 below several spaces to the right.
Any way I can keep this from happening? I'm kinda new to using transitions and have been racking my brain trying to see if this can be fixed.
Thanks!
CSS
body {
margin: 0;
padding: 0;
}

#wrapper {
width: 985px;
min-height: 500px;
margin: 0 auto;
}

ul #fourbox {
list-style-type: none;
}

#fourbox li {
display: block;
width: 188px;
height: 213px;
margin: 15px 10px;
padding: 15px;
background: #F1F1F2;
border: 1px solid #D1D2D4;
float: left;
box-shadow: 0px 0px 0px #888888;
transition:all 0.5s ease;
-webkit-transition:all 0.5s ease;
}

#fourbox li:hover {
width: 198px;
height: 228px;
margin: 5px 5px;
box-shadow: 0px 7px 10px #888888;
}

HTML

1

2

3

4

5

6

7

8

Refer: http://jsfiddle.net/aasthatuteja/mVrMH/
Comment: inline-block worked! Thank you all so much! What a great and speedy community!
Comment: [jsFiddle](http://jsfiddle.net/4pehD/)
Comment: Thanks! I'm new to the site so I'll do just that.
Answer: Here is one solution:
jsFiddle here
Use display:inline-block as opposed to float:left
#fourbox li {
    width: 188px;
    height: 213px;
    margin: 15px 10px;
    padding: 15px;
    background: #F1F1F2;
    border: 1px solid #D1D2D4;
    display:inline-block;                     /* ADD THIS <<< */
    box-shadow: 0px 0px 0px #888888;
    transition:all 0.5s ease;
    -webkit-transition:all 0.5s ease;
}

Alternatively, you can also use clear:both if you need to float them.
Either solutions work. Nice little animation though!
Answer: Remove "float:left" and replace that "display:block" with "display:inline-block"...
#fourbox li {
    display: inline-block;
    width: 188px;
    height: 213px;
    margin: 15px 10px;
    padding: 15px;
    background: #F1F1F2;
    border: 1px solid #D1D2D4;

    box-shadow: 0px 0px 0px #888888;
    transition:all 0.5s ease;
    -webkit-transition:all 0.5s ease;
}

Fiddle: http://jsfiddle.net/aasthatuteja/sAmxE/
Hope that works for you!
Answer:         body {
            margin: 0;
            padding: 0;
        }

        #wrapper {
            width: 985px;
            min-height: 500px;
            margin: 0 auto;

        }

        ul #fourbox {
            list-style-type: none;
            display: block;
        }

        #fourbox li {
            display: inline-block;
            width: 188px;
            height: 213px;
            margin: 15px 10px;
            padding: 15px;
            background: #F1F1F2;
            border: 1px solid #D1D2D4;
            box-shadow: 0px 0px 0px #888888;
            transition:all 0.5s ease;
            -webkit-transition:all 0.5s ease;
        }

        #fourbox li:hover {
            width: 198px;
           height: 228px;
            margin: 5px 5px;
            box-shadow: 0px 7px 10px #888888;
        }
    </style>

1

2

3

4

5

6

7

8

. Just made few changes and its working
Answer: Looking at it, it looks like you're trying to keep it to 3 boxes per row, right?  If that's the case, you could simply use a clear:both; between each set of 3.
Works for me here.  http://jsfiddle.net/Tzh8b/

Answer: You either need to give the elements more breathing room for that extra space or use JS to decrease the %(assuming they are 50%s) of all li and than add the hover effect on $(this) li so when you hover over an li you than decrease all the other lis allowing for enough room for it to grow.
so $("li").hover(function() {
$("li").css('width','smaller');
$(this).css('width','larger');
});
Answer: Instead of using actual widths and heights why not use CSS Transforms! They're neat :)
transform:scale(1.1);

or for webkit
-webkit- transform:scale(1.1);

It doesnt affect normal flow and is easy to implement :) Let me know if this works for you!
DEMO
http://jsfiddle.net/eYCQq/


How to check Django version

Question: I have to use Python and Django for our application. So, I have two versions of Python, 2.6 and 2.7. Now I have installed Django. I could run the sample application for testing Django successfully. But how do I check whether Django uses the 2.6 or 2.7 version and what version of modules Django uses?
Comment: Shortest way - `python3 -m django --version`
Comment: In my installation python3 is not recognized. This works: python -m django --version
Comment: another shortest way is `django-admin --version`
Comment: I believe since a somewhat old Python version is preinstalled on MacOS systems, a suffix of "3" is required on "python" command to avoid confusions from the OS side on which version to use.
This isn't required on Windows systems so @AnttiA 's solution works just fine.
Comment: The suggested commands show your installed django version, not the code version. Check the *requirements.txt* `cat src/requirements.txt | grep "Django=="` or in your application's settings.py file, on the fifth line you'll see something like `Generated by 'django-admin startproject' using Django x.x.x` (for the user-specific question, the accepted answers are the way, but I found that this could also be useful).
Answer: Django 1.5 supports Python 2.6.5 and later.
If you're under Linux and want to check the Python version you're using, run python -V from the command line.
If you want to check the Django version, open a Python console and type
>>> import django
>>> django.VERSION
(2, 0, 0, 'final', 0)

Comment: Just dive into env before you check the version, otherwise no module named django.
Comment: This says - `AttributeError: module 'django' has no attribute 'VERSION'`
Answer: Basically the same as bcoughlan's answer, but here it is as an executable command:
$ python -c "import django; print(django.get_version())"
2.0

Comment: Combining Brady Emerson and bcoughlan:  ```python -c "import django; print(django.VERSION)"``` returns
```(1, 8, 5, 'final', 0)```
Comment: You should do `python -c "import django; print(django.__version__)"` instead. It also returns `'2.2.4'` (it's [just a call to `get_version()`](https://github.com/django/django/blob/master/django/__init__.py#L5)) and is the standard followed by most other libraries because it's [defined in PEP 8](https://www.python.org/dev/peps/pep-0008/#module-level-dunder-names). It works since [Django 1.8](https://github.com/django/django/blob/1.8/django/__init__.py#L5)
Answer: If you have installed the application:
$ django-admin --version
3.2.6

Comment: this worked for me: ubuntu 18.04, virtualenv with P 3.6 and Django 2.2
Comment: As May 2018 (the date I've tested this answer again), it shows version as 1.11.5 despite I've installed 2.0.1. But `>> django.VERSION` in python shell displays the right version
Comment: For older versions it is `django-admin.py --version`. Depending on how you've done your python installation, you may even need `python django-admin.py --version`.
Comment: This works for me in 2022, ubuntu 20.02, virtualenv with Python 3.8 and Django 4.0.2
Comment: this just shows you the django-admin version. it's `python3 -c "import django; print(django.get_version())"` that will give you the actual django version installed
Answer: Go to your Django project home directory and do:
./manage.py --version

Comment: I like this one as we as Django devs often use the manage.py functionalities. You can also use 'python manage.py version' (no need for --)
Answer: >>> import django
>>> print(django.get_version())
1.6.1

I am using the IDLE (Python GUI).
Answer: If you have pip, you can also do a pip freeze
and it will show your all component version including Django .
You can pipe it through grep to get just the Django version. That is,
josh@villaroyale:~/code/djangosite$ pip freeze | grep Django
Django==1.4.3

Answer: As you say you have two versions of Python, I assume they are in different virtual environments (e.g. venv) or perhaps Conda environments.
When you installed Django, it was likely in only one environment. It is possible that you have two different versions of Django, one for each version of python.
In from a Unix/Mac terminal, you can check your Python version as follows:
$ python --version

If you want to know the source:
$ which python

And to check the version of Django:
$ python -m django --version

Answer: For Python:
import sys
sys.version

For Django (as mentioned by others here):
import django
django.get_version()

The potential problem with simply checking the version, is that versions get upgraded and so the code can go out of date. You want to make sure that '1.7' < '1.7.1' < '1.7.5' < '1.7.10'. A normal string comparison would fail in the last comparison:
>>> '1.7.5' < '1.7.10'
False

The solution is to use StrictVersion from distutils.
>>> from distutils.version import StrictVersion
>>> StrictVersion('1.7.5') < StrictVersion('1.7.10')
True

Comment: What about using `django.VERSION`, which already comes as a tuple? I'm pretty sure doing `django.VERSION >= (1, 8)` will always work as intended.
Answer: There are various ways to get the Django version. You can use any one of the following given below according to your requirements.
Note: If you are working in a virtual environment then please load your python environment

Terminal Commands

python -m django --version
django-admin --version or django-admin.py version
./manage.py --version or python manage.py --version
pip freeze | grep Django
python -c "import django; print(django.get_version())"
python manage.py runserver --version

Django Shell Commands

import django
django.get_version() OR
django.VERSION
from django.utils import version
version.get_version()  OR  version.get_complete_version()
import pkg_resources
pkg_resources.get_distribution('django').version

(Feel free to modify this answer, if you have some kind of correction or you want to add more related information.)
Answer: Simply type python -m django --version  or type pip freeze to see all the versions of installed modules including Django.
Comment: no reason for this to be downvoted at all, it is one of the most concise answers.
Answer: django-admin --version
python manage.py --version
pip freeze | grep django

Comment: You'll need to use `python manage.py --version` Note the double `-`
Comment: @Shawnzam yes of course a typo.. Thanks a lot..Answer edited
Comment: I needed to make the d in Django capital for grep to find it.
Comment: The first command and the second return two different version numbers for me.
Answer: For checking using a Python shell, do the following.
>>>from django import get_version
>>> get_version()

If you wish to do it in Unix/Linux shell with a single line, then do
python -c 'import django; print(django.get_version())'

Once you have developed an application, then you can check version directly using the following.
python manage.py runserver --version

Answer: Type in your CMD or terminal:
python -m django --version

Answer: Official Documentation
First:
python -m django --version

Second:
import django
print(django.get_version())

Answer: Django version or any other package version
Open the terminal or command prompt
Type
pip show django

or
pip3 show django

You can find any package version...
Example:
pip show tensorflow

pip show numpy

etc....
Comment: I like the simplicity of this answer best. `pip freeze` shows a ton of extra crap if you've pip'd in a bunch of packages.
Answer: Run pip list in a Linux terminal and find Django and its version in the list:
Run pip freeze on cmd on Windows.
Answer: Django will use the version of Python specified by the PYTHONPATH environment variable. You can use echo $PYTHONPATH in a shell to determine which version will be used.
The module versions used by Django will be the module versions installed under the version of Python specified by PYTHONPATH.
Answer: There is an undocumented utils versions module in Django:
https://github.com/django/django/blob/master/django/utils/version.py
With that, you can get the normal version as a string or a detailed version tuple:
>>> from django.utils import version
>>> version.get_version()
... 1.9
>>> version.get_complete_version()
... (1, 9, 0, 'final', 0)

Answer: You can do it without Python too. Just type this in your Django directory:
cat __init__.py | grep VERSION

And you will get something like:
VERSION = (1, 5, 5, 'final', 0)

Comment: This is great when you don't want to activate the virtual env just to get a value, or you're using something like AWS Elastic Beanstalk and can't activate the virtual env.
Comment: @rjferguson you dont need to activate your env to do a `pip freeze` / `python -c "import ; .VERSION"`. You can simply reference it: `/path/to/env/bin/python -c ""` or if you want to install/use pip, same thing: `/path/to/env/bin/pip freeze`. I use this all the time, specially when im logged in as a root and all of my application code runs as `www-data` i do: `sudo su www-data -c "/path/to/env/bin/pip install "` and not even blink. (i know this is almost 2 years later, and you probably know about it now -- this is more for the next guy)
Comment: > without Python
>> python -c
Answer: The most pythonic way I've seen to get the version of any package:
>>> import pkg_resources;
>>> pkg_resources.get_distribution('django').version
'1.8.4'

This ties directly into setup.py: https://github.com/django/django/blob/master/setup.py#L37
Also there is distutils to compare the version:
>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("2.3.1") > StrictVersion("10.1.2")
False

As for getting the python version, I agree with James Bradbury:
>>> import sys
>>> sys.version
'3.4.3 (default, Jul 13 2015, 12:18:23) \n[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]'

Tying it all together:
>>> StrictVersion((sys.version.split(' ')[0])) > StrictVersion('2.6')
True

Answer: After django 1.0 you can just do this
$ django-admin --version
1.11.10

Answer: Type the following command in Python shell
import django
django.get_version()

Answer: Python version supported by Django version
Django version        Python versions
----------------------------------------
1.0                   2.3, 2.4, 2.5, 2.6
1.1                   2.3, 2.4, 2.5, 2.6
1.2                   2.4, 2.5, 2.6, 2.7
1.3                   2.4, 2.5, 2.6, 2.7
1.4                   2.5, 2.6, 2.7
1.5                   2.6.5, 2.7 and 3.2.3, 3.3 (experimental)
1.6                   2.6.5, 2.7 and 3.2.3, 3.3
1.11                  2.7, 3.4, 3.5, 3.6, 3.7 (added in 1.11.17)
2.0                   3.4, 3.5, 3.6, 3.7
2.1, 2.2              3.5, 3.6, 3.7

To verify that Django can be seen by Python, type python from your shell. Then at the Python prompt, try to import Django:
>>> import django
>>> print(django.get_version())
2.1
>>> django.VERSION
(2, 1, 4, 'final', 0)

Answer: If you want to make Django version comparison, you could use django-nine (pip install django-nine). For example, if Django version installed in your environment is 1.7.4, then the following would be true.
from nine import versions

versions.DJANGO_1_7 # True
versions.DJANGO_LTE_1_7 # True
versions.DJANGO_GTE_1_7 # True
versions.DJANGO_GTE_1_8 # False
versions.DJANGO_GTE_1_4 # True
versions.DJANGO_LTE_1_6 # False

Answer: You can get django version by running the following command in a shell prompt
python -m django --version
If Django is installed, you should see the version otherwise you'll get an error telling "No module named django".
Answer: you can import django and then type print statement as given below to know the version of django i.e. installed on your system:
>>> import django
>>> print(django.get_version())
2.1

Answer: Open your CMD or Terminal and run any of the following commands
django-admin --version
        or
python3 -m django --version
        or
pip freeze

Answer: From your code, you can get the version of Django by using any of the two below.
import django
print(django.__version__)
# '3.1.5'
print(django.VERSION)
# (3, 1, 5, 'final', 0)

or from your terminal, you can run
django-admin --version

Answer: It's very simple open the CLI(command line or any IDE) wherever you installed python and Django just type,
django-admin --version
see here I have installed the latest Python and Django in my system and the result is shown in fig.
Answer: There are two more methods to get the Version (of Django and other packages).
Both of them need a version variable for the package to get the version.
According to PEP-396 the __version__variable should be set for every Python module.

Method 1 - Get version from filesystem
With that in mind, you know how to get the version for almost every Django/Python package. Look inside the __init__.py of the package root.
So if you are a fast at navigating through the filesystem, this can be a very universal way of getting the Version of any package inside your site-package (virtual environment).

Method 2 - Django Debug Toolbar
There is a very helpful tool that is called django debug toolbar.
If you use it (very recommendable for Django development) you can list the versions of all apps that have a package.__version__.
Answer: These commands below get Django version:
django-admin --version

python manage.py --version

But, these commands below get error:
django-admin -v

python manage.py -v

Answer: To check the Django version installed on your Windows PC,
In a Terminal session, run:
py -m Django --version

Or in a Python REPL:
import Django
django.get_version()

To check the Django version installed in your active virtual environment (venv), run:
Django-admin --version

Note that the Django version installed on your PC might be different from the version installed in your active virtual environment.
Answer: go the setting of the Django Project. there find your Django Version.

How to check Django version


is there a true 400 amp panel rated as 400 continous amp

Question: It seems common to use 400amp (320 amp class) panels. Are there any 400amp panel rated as continuous 400amp on the market? If yes, why not use these panels?
For the 400amp (320 amp class) panel, are there 2 sub-panels and is max current for each panel 160amp? Is there a different configuration available where one panel might support max 200amp and a second panel supports 120amp?
I am in the process of upgrading to 400amp, required by the city for our addition because we are going all electric, so I want to understand a little bit before engaging the electrician.
Comment: Asking for solar panel recommendations is off-topic. I would edit that out if I were you. The rest is on-topic
Comment: A little bit of formatting and the proper use of capitalization would make this question much more readable. Additionally, the question(s) about solar ready panels should probably be asked on its own as a separate question.
Comment: I think most electrical devices are only rated at 80% of their label.
Comment: I think a reading of the question that assumes good intent is that it asks for recommendations on features and best practices for breaker panels that are solar-ready, not that it asks for brand recommendations or for recommendations on solar panels.  If read in full, the question is about whether a 400-amp-ready-for-solar panel is a realistic expectation.  The question could be written more clearly and explicitly.
Comment: You have to also remember other than code 100-400 amp restriction by the NEC  the arc flash rating. I have seen more than a few homes that the utility transformer was larger than actually allowed by code and exceeded the panels rating (the panel / meter that the utility required). Most residential inspectors don't check but I did have one that caught it and made the utility change the transformer,, (Stay with the big names for service equipment)
Comment: Note that a "400A" *meter* *cannot* handle 400 continuous amps, nor can a Class 320 meter base.  (You need either K-base or CT metering to meter a 400 continuous amp service.)
Answer: You're thinking about it upside-down.
Your logic is start with a 400A panel, and then what can you put on it?  Actually it works the other way round.
You start with the characteristics of your house, and major appliances... and punch that into a residential load calculation.  The load calculation takes into account continuous use, equipment's ability to tolerate short overloads, and the tendency to not run all appliances full-out at the same time.  That pops out a number like 274 amps, so you get a service that is larger than that, leading you to a 400A service since that's what that power company offers.
If you were using the industrial charts for continuous loads, then you derate any continuous load by 125%.  So you claim to have 400A of continuous loads, OK that's 500A derated and you need a 500A service.  600A is the next size up the power company will offer, so that's what you get.
So there is no circumstance where you will have 400A of continuous loads and expect a 400A service to be involved in that.
A 400A main breaker and main panel? If cost is no object...
Imagine someone is looking for a job in this market, and they get told "we're working from home, so you'll need your own PC".  They've never bought a PC before.  They get sold an $8000 Alienware gaming rig with dual 3090s, and don't think anything of it, because they have no idea what PCs are supposed to cost.
The same thing can happen to novices who get "target fixation" on obtaining a 400A main breaker and panel.  Yes, with enough persistence you will find vendors cheerfully willing to take $2000 for a 400A main breaker and $3000 for a 400A rated load center/service panel, all out of the industrial catalog with prices to match.
I would say this is "not common at all" owing to the extreme cost compared to the normal method.
Dual 200A panels. Cheap and simple.
Prior to NEC 2020, the typical 400A installation was a meter pan lugged for dual 250 kcmil lugs ($200), feeding two 200A main-breaker panels ($150 each) via very short, unfused service entrance wires.  Through the wall, no further.
Note that this common form of 400A meter pan cannot be used any other way, since the lugs cannot accept the 600 kcmil wire required for a 400A panel, nor is it designed nor approved for paralleling dual 250 kcmil wire.
In NEC 2020 installations, that becomes a 400A meter-main ($300)  which contains one 200A breaker with a slot for a second (+$150), which then feeds two 200A+ rated main-lug subpanels ($150).
Simple, straightforward, approved everyday, and uses kit stocked at local stores.
Each panel must have its own local load calculation which must fall within the rating of the panel.  So you can't load them 250A and 150A, because panels with 250A bus rating are uncommon.  225A is common.
Answer: Residential services are listed as 100-400 amp see 310.12.A ,   Don't want to read see table 310.12.
There are true 400 amp services but you will find these usually require CT cabinets and metering as  400 continuous falls into commercial.
This is the reason you don't find larger than 400 amp residential service panels.
They do make commercial panels in 450, 500, 600 , but as I mention now you are in commercial level power.
Answer: Don't try to redefine standard terms!  If you want 400 A continuous output, then calculate what that is 80% of, i.e. 500 A and buy a panel rated thusly.
This is similar to board measurements, where a "2 by 4" is understood to be (varies a bit by region or country)  1.5 by 3.5 , and if you want a board that's 2 inches by 4 inches, you specify "true dimension" wood.
Answer: The part of the question about rated vs continuous and about getting more than 320A continuous is answered well in the other answers.
To answer the part of your question about whether the rated 400 amps could be divided other than 50/50, I've seen 225A and 175A residential main breakers available.  There are ways you could split the service between those, putting the 225A breaker into a suitably large main panel.  I don't think there is any other  way to unequally split two-phase 400A service.  I don't think you can do 320/160.


How to plot each list element with same x axis?

Question: Reproducible example:
a <- 2
b <- 1
tau <- 2

t <- seq(1,3,1)
y <- seq(0,10,1)

G.fun <- function(x,shape,scale){pgamma(x,shape,scale)}

G <- vector(mode = "list", length = length(t))
for (t in 1:length(t)){
  G[[t]] <- G.fun(y,shape = a*t, scale = b)
}

How can I plot each element of G on a same plot given the x axis is same for all which is y <- seq(0,10,1)?
Answer: In base R, you could also use the matplot function. First you have to ensure you have a matrix from your list:
mat <- do.call(cbind, G) #or even unname(as.matrix(data.frame(G)))
matplot(y, mat, type = "b")

This can be written as matplot(y, do.call(cbind, G), type = "b")
Answer: base R
plot(y, G[[1]], pch = 16, type = "b")
for (i in seq_along(G)[-1]) points(y, G[[i]], type = "b", pch = 16, col = i)

ggplot
(I'll use tidyr to reshape it.)
dat <- cbind(y=y, setNames(as.data.frame(G), c("A","B","C")))
dat2 <- tidyr::pivot_longer(dat, -y)
head(dat2)
# # A tibble: 6 x 3
#       y name     value
#   <dbl> <chr>    <dbl>
# 1     0 A     0
# 2     0 B     0
# 3     0 C     0
# 4     1 A     0.264
# 5     1 B     0.0190
# 6     1 C     0.000594
ggplot(dat2, aes(y, value, color = name)) + geom_path()


AVCam Demo OverscanCompensation implementation

Question: I'm currently working with the AVCam demo app to present a live camera feed over airplay or apple hdmi adapter for import into a HD camera switcher.
The issue I'm having is with OverScanCompensation to remove the huge black border from the mirrored view.
The only documentation I have found is to implement the screen.overscanCompensation = 3; method someplace? I have tried to put it into viewDidLoad and it will let me, but it doesn't change anything on the external view?
I had success of sorts with the Airplay Demo (quellish) using UIImagePicker, but I would much prefer to implement AVFoundation for this exercise.
Is there a better way to achieve what I'm looking for without having to implement separate view controllers?
Answer: All you need to do is, upon setting up the external screen (via, say, if ([[UIScreen screens] count] > 1) externalScreen = (UIScreen *)[[UIScreen screens] objectAtIndex:1];), set the overscanCompensation property of the above UIScreen instance to UIScreenOverscanCompensationInsetApplicationFrame (=2). It'll entirely get rid of both the border (overscanning) and image quality-deterioating scaling.
See http://www.iphonelife.com/blog/87/tv-display-output-why-does-your-picture-have-black-border-and-how-can-it-be-fixed for more info.


How do I understand and fix error while compiling Linux kernel for embedded system

Question: While trying to compile the following file:
<code>/*
 *  linux/arch/arm/mm/proc-syms.c
 *
 *  Copyright (C) 2000-2002 Russell King
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#include <linux/module.h>
#include <linux/mm.h>

#include <asm/cacheflush.h>
#include <asm/proc-fns.h>
#include <asm/tlbflush.h>
#include <asm/page.h>

#ifndef MULTI_CPU
EXPORT_SYMBOL(cpu_dcache_clean_area);
EXPORT_SYMBOL(cpu_set_pte_ext);
EXPORT_SYMBOL(cpu_tima_set_pte_ext);
#else
EXPORT_SYMBOL(processor);
#endif

#ifndef MULTI_CACHE
EXPORT_SYMBOL(__cpuc_flush_kern_all);
EXPORT_SYMBOL(__cpuc_flush_user_all);
EXPORT_SYMBOL(__cpuc_flush_user_range);
EXPORT_SYMBOL(__cpuc_coherent_kern_range);
EXPORT_SYMBOL(__cpuc_flush_dcache_area);
#else
EXPORT_SYMBOL(cpu_cache);
#endif

#ifdef CONFIG_MMU
#ifndef MULTI_USER
EXPORT_SYMBOL(__cpu_clear_user_highpage);
EXPORT_SYMBOL(__cpu_copy_user_highpage);
#else
EXPORT_SYMBOL(cpu_user);
#endif
#endif

/*
 * No module should need to touch the TLB (and currently
 * no modules do.  We export this for "loadkernel" support
 * (booting a new kernel from within a running kernel.)
 */
#ifdef MULTI_TLB
EXPORT_SYMBOL(cpu_tlb);
#endif
</code>
I get the following error:
<code>arch/arm/mm/proc-syms.c:21:1: error: 'cpu_tima_set_pte_ext' undeclared here (not in a function)
make[1]: *** [arch/arm/mm/proc-syms.o] Error 1
make: *** [arch/arm/mm] Error 2
</code>
I am actually surprised that I get this error. This is code which I downloaded from a vendor, and I do not think it would have error in it. Is there someway to bypass this error? Is this a real error, or something which will be fixed during the link phase?
@user58697 - You d'man. Thanks. Thank you so much. This was the fastest reply and correct.
Comment: This was a known problem. A patch exists (see for example http://forum.xda-developers.com/showpost.php?p=51760869)
Comment: @user58697 do you mind putting that up as an answer? That way it will be more visible for everyone.
Answer: As requested:
This was a known problem. A patch exists (see for example here)


how to wire ceiling fixture with only black white and ground wires into box with black red green and white wires?

Question: Moving into a new building and wanting to wire a new ceiling fixture into the box built into the ceiling. The fixture has only black, white, and an uninsulated copper wire. It does have green screws which are not hooked up to anything also.
The fixture is to be operated by a wall switch—one switch only, not two—nothing else. The ceiling connection box has red, white, black and green wires. If you connect black to black, white to white, and uninsulated to green (ground I assume) the light turns on but the wall switch does not operate it; the wall switch will not turn it off. The red wire obviously is tied to the switch control. How to connect it into all this? What to do at this point? Not at all clear!!
Answer: Connect fixture black to ceiling box red instead
From what you've done so far, it's clear that the black wire in your ceiling box is an always-hot wire.  So, we can safely assume by elimination that the red wire must be the switched-hot you're looking for, since we already know what neutral and ground are as well.
Comment: It may have originally been intended for a ceiling fan with a remote control.  I agree that the red is probably the switched wire.   It would be best to verify with a voltmeter though.   +
Comment: Great and just cover the end of the ceiling box black and leave it there right?
Comment: @LarryG correct
Comment: OK So I did this and the fixture worked fine. Off and on multiple times in the last 24 hours. Now today the switch will not stay in the on position. It's like there is a spring in there now. While I hold it down the light will stay on, but as soon as I take my finger off the switch it pops back into the off position and the light, of course, goes off. Wha??
Comment: @LarryG the actual light switch?  if that's the case, then the switch broke internally and needs to be replaced
Comment: Yep. That's what I figured. No longer my job. This goes to management! There was a bit of resistance in the switch even when it did work. Thanks!


Accuracy of the System.Threading.Timers in windows service

Question: I have developed the windows service in C#.NET.
In this, I have used System.Threading.Timer.
When i have start the 10 second interval timer there is some variation between the execution timing.
//code
public void SetTimers(int timer, DataRow row)
       {
           TimeSpan dueTime;
           TimeSpan interval;
           SetTimeIntervals(row, out dueTime, out interval);
           timer1[timer] = new System.Threading.Timer(databaseTrensfer, row, dueTime, interval);
      }

public void databaseTrensfer()
{
//code
}

private void SetTimeIntervals(DataRow row, out TimeSpan tsDueTime, out TimeSpan tsPeriod)
       {
           string alarmType = Convert.ToString(row["EBase"]);
           string EType = Convert.ToString(row["EType"]);
           string EFrequency = Convert.ToString(row["EFrequncy"]);
           if (alarmType == "Milisecond")
           {
               int frquency1 = Convert.ToInt32(row["Tfrquency"]);
               tsDueTime = new TimeSpan(0, 0, 0, 0, frquency1);//frquency1=interval
               tsPeriod = new TimeSpan(0, 0, 0, 0, frquency1);
           }
           else if (alarmType == "Second")
           {
               int frquency1 = Convert.ToInt32(row["Tfrquency"]);
               tsDueTime = new TimeSpan(0, 0, 0, frquency1);
               tsPeriod = new TimeSpan(0, 0, 0, frquency1);
           }
           else if (alarmType == "Once")
           {
               tsDueTime = new TimeSpan(0, 0, 0);
               tsPeriod = new TimeSpan(0, 0, 0);
           }
           else if (alarmType == "Minute")
           {
               int frquency1 = Convert.ToInt32(row["Tfrquency"]);
               tsDueTime = new TimeSpan(0, frquency1, 0);
               tsPeriod = new TimeSpan(0, frquency1, 0);
           }
           else if (alarmType == "Hour")
           {
               int minute = 0;
               int frquency1 = 1;
               if (Convert.ToString(row["RelativeFactor"]) != "")
                   minute = Convert.ToInt32(row["RelativeFactor"]);
               if (Convert.ToString(row["Tfrquency"]) != "")
                   frquency1 = Convert.ToInt32(row["Tfrquency"]);
               tsDueTime = new TimeSpan(frquency1, minute, 0);
               tsPeriod = new TimeSpan(frquency1, 0, 0);
           }
           else
           {
               tsDueTime = new TimeSpan();
               tsPeriod = new TimeSpan();
           }
       }

I have pass the frequency to set the timer & start the number of timer simultaneously.
My o/p:
2011-08-22 13:42:08.0
2011-08-22 13:42:18.0
2011-08-22 13:42:28.0
2011-08-22 13:42:38.15
.
.
.
2011-08-22 14:28:38.984
2011-08-22 14:28:48.984
2011-08-22 14:28:59.15
2011-08-22 14:29:09.15
2011-08-22 14:29:19.15
.
.
2011-08-22 15:14:59.953
2011-08-22 15:15:09.968
2011-08-22 15:15:19.968

I got this o/p timer started at the 08 seconds of variation  then shifting to the 09 second.
Now my question is why all timers are not executing in exact timing?
Any solutions?
Comment: possible duplicate of [Most accurate timer in .NET?](http://stackoverflow.com/questions/9228313/most-accurate-timer-in-net)
Comment: [Are Timers and Loops in .Net accurate?](http://stackoverflow.com/q/11531128/1504523) may give some more thoughts.
Answer: The following attempts to resynchronize the timer with the system clock after each interval of a second or longer has elapsed.
// add these fields

private TimeSpan[] _interval;
private DateTime[] _startTime;

// when you create timer1 array, need to initialize the above arrays

int len = timer1.Length;
_interval = new TimeSpan[len];
_startTime = new DateTime[len];

// change SetTimers method as follows;

public void SetTimers(int timer, DataRow row)
{
   TimeSpan dueTime;
   TimeSpan interval;
   SetTimeIntervals(row, out dueTime, out interval);

   _interval[timer] = interval;
   _startTime[timer] = DateTime.Now + dueTime;
   object[] obj = new object[2]{row, timer};
   timer1[timer] = new System.Threading.Timer(databaseTrensfer, obj, dueTime, interval);
}

// change databaseTrensfer method as follows

public void databaseTrensfer(object state)
{
   object[] obj = (object[])state;
   DataRow row = (DataRow)obj[0];
   string alarmType = Convert.ToString(row["EBase"]);
   if (alarmType != "Milisecond" && alarmType != "Once")
   {
      int timer = (int)obj[1];
      DateTime dt = DateTime.Now;
      long elapsedMs = Convert.ToInt64((dt - _startTime[timer]).TotalMilliseconds);
      long intervalMs = Convert.ToInt64(_interval[timer].TotalMilliseconds);
      long remainder = elapsedMs % intervalMs;
      if (remainder != 0L)
      {
         timer1[timer].Change(_interval[timer] - TimeSpan.FromMilliseconds(remainder), _interval[timer]);
      }
   }
   //code
}

Comment: Why don't you use `Stopwatch` class?


How to not make the program restart after a value error?

Question: So I recently started coding and just learned about 'try' and 'except' for 'ValueError'. I made this calculator but it restarts if you don't input an int on the 'second' input. How do I make it ask for pnly the 'second' variable instead of asking for the first one again?
while True:
    try:
        first = int(input("First: "))
        second = int(input("Second: "))
        sum = first + second
        print(f"Sum: {sum}")
        break
    except ValueError:
        print("I didn't understand that")

I tried this but it just asked for the second variable then restarted the program
while True:
    try:
        first = int(input("First: "))
        second = int(input("Second: "))
        sum = first + second
        print(f"Sum: {sum}")
        break
    except ValueError:
        print("I didn't understand that")
        int(input("Second: "))

Answer: Use a separate while with try/except blocks for the two prompts. And since you are doing the same thing multiple times, put the common part in a function
def get_input(prompt, cast_to=int):
    while True:
        try:
            return cast_to(input(prompt))
        except ValueError:
            print("I didn't understand that")

first = get_input("First: ")
second = get_input("Second: ")
sum = first + second
print(f"Sum {sum}")

Answer: Make a separate function for inputting the number:
def GetNumberInput(text: str) -> int:
    while True:
        try:
            return int(input(text))
        except ValueError:
            print("I didn't understand that")

first = GetNumberInput("First: ")
second = GetNumberInput("Second: ")
sum = first + second
print(f"Sum: {sum}")

Output:
First: 123
Second: aaa
I didn't understand that
Second: 456
Sum: 579

Answer: the problem you are facing is because as you exit the try-except block, the loop reiterates which leads to the first input again. You can avoid this behavior by taking the loop in a separate function, like so:
def take_input(text):
    while True:
        try:
            return int(input(text))
        except ValueError:
            print("I didn't understand that")

You can then call this function whenever you require the input like, num = take_input("Input: "). The complete implementation of your calculator would look like this:
def take_input(text):
    while True:
        try:
            return int(input(text))
        except ValueError:
            print("I didn't understand that")

first = GetNumberInput("First: ")
second = GetNumberInput("Second: ")
sum = first + second
print(f"Sum: {sum}")

Now the loop only runs when the return value is hit, else you go through another iteration of the loop, and so on and so forth. Hope you understand the logic behind this!


what is the role of timer here

Question: here the code what is the actual role of timer,,other thing is which if(saving) will trigger first ,if modification not happened means server fail..Is there any relation with thread..
private void Dlg_Load(object sender, System.EventArgs e)
{
    // Set the message.
    if (Saving)
        eLabel.Text = Managers.ControlStrings.GetString("Saving");

    // Setup to receive events.
    Server.InfoReceived += new InfoEventHandler(Server_InfoReceived);
    Server.Received += new ServerStateEventHandler(Server_ServerStateReceived);

    // Start the timer to begin saving as soon as the dialog has completed setup.
    Timer.Start();
}

/// Handle the tick of the timer by stopping the timer and beginning the operation.  This allows
/// the dialog to come up fully before the operation is started; otherwise there are problems
/// closing the dialog.
///
/// <param name="sender">Timer.</param>
/// <param name="e">Ignored.</param>
private void Timer_Tick(object sender, System.EventArgs e)
{
    string func = "Dlg.Timer_Tick";
    try
    {
        // Stop timer
        Timer.Stop();

        if (Saving)

            if (!Server.Modify())
            {

            }
    }
}

Comment: Don't mean to be an ass, but can you go back to your question and revise to use complete sentences?
Answer: The only clue we have here is the XML comment:
/// Handle the tick of the timer by stopping the timer and beginning the operation.
/// This allows the dialog to come up fully before the operation is started;
/// otherwise there are problems closing the dialog.

Apparently there is a problem with the sequence of initialization. It smells a bit like a hack, but we don't see enough code to decide what exactly.
Answer: it's look like it is a bad way to wait for a dialog to be display in order (saving?) to do something when the dialog is displayed.
Answer: Read the comments in the code.
It is to wait for everything to be drawn correctly before doing the action in the timer event.
Application.DoEvents() is sometimes used for similar "waiting".
I guess that the timer interval is 1 millisecond.
Comment: well, it's a hacky pattern to deffer execution until the form is completely loaded.

what is the role of timer here


How to import outlook express mails into thunderbird mail client?

Question: We are in the process of converting all our windows systems into ubuntu. Is there a way to import outlook express mails into thunderbird in Ubuntu?
Comment: The easiest way is to install Thunderbird on your Windows Machine and transfer your email there see [here](http://kb.mozillazine.org/Import_.pst_files) and [here](http://www.twistermc.com/1376/outlook-thunderbird/).  You can then backup your email and restore it on your Ubuntu machine.
Answer: Install Thunderbird on a windows machine, and go to Tools menu, choose Tools --> import.  When the window opens choose mail, and then pick outlook express.  Repeat for other items.
Comment: When importing into a Thunderbird on Windows, it is important to make sure that the "bittyness" of Outlook and Thunderbird matches. Trying to import from a 32-bit Outlook into a 64-bit will result in a `Profile not found` error. See [this SO post](https://askubuntu.com/a/1440375/1118505).


Corrupt file downloads from MySQL database using PHP

Question: Every time I try to download, it produces correct filename and extension (file) but corrupt (usually 1kb in size and can't be opened, in this case my file is .docx format and around 12kb in size). I'm using XAMPP, and I use phpmyadmin to look at my sql database. The upload script works to store file from computer to database.
Here is my upload script: - edited according to answers
<?php
session_start();
include("connect.php");
$nametemp=$_SESSION['name'];
$nistemp=$_SESSION['nislogin'];
$subjecttemp=$_SESSION['subject'];
$chapter=$_POST['chapter'];

$name=$_FILES['browsefile']['name'];
$mime=$_FILES['browsefile']['type'];
$data=file_get_contents($_FILES['browsefile']['tmp_name']);
$size=$_FILES['browsefile']['size'];

mysql_query("INSERT INTO assignment (name, mime, size, data, created, uploader, subject, chapter) VALUES ('$name', '$mime', '$size', '$data', NOW(), '$nametemp', '$subjecttemp', '$chapter')");

header("location:subject.php");
die();
?>

and here's download script: -edited according to answers
<?php
session_start();
include("connect.php");
$nametemp=$_SESSION['name'];
$nistemp=$_SESSION['nislogin'];
$classtemp=$_SESSION['class'];
$subjecttemp=$_SESSION['subject'];
$idtemp=$_GET['id'];

$query=("SELECT mime, name, size, data FROM assignment WHERE id='$idtemp'");
$result=mysql_query($query);
$filename=mysql_result($result,0,"name");
$filesize=mysql_result($result,0,"size");
$filemime=$type=mysql_result($result,0,"mime");
$filedata=mysql_result($result,0,"data");

header("Content-disposition: attachment; filename=$filename");
header("Content-length: $filesize");
header("Content-type: $filemime");
header("Content-transfer-encoding: binary");
echo $filedata;
?>

In case you're wondering, here is the screenshot of 'assignment' table structure: image
Answer: $data=$_FILES['browsefile']['tmp_name'];
You assign the temp name of an uploaded file to the 'data' column, not the data itself.
The quick-fix for this is to use file_get_contents function.
Second: readfile reads a file from the disk, it does not provide an output stream from a variable. This line is not needed.
But: saving a binary file in a database is not recommended. Beter to store the file itself in an upload folder and save the name of it.
Also, change the next line
mysql_query("INSERT INTO assignment (name, mime, size, data, created, uploader, subject, chapter) VALUES ('$name', '$mime', '$size', '$data', NOW(), '$nametemp', '$subjecttemp', '$chapter')");

into
mysql_query("INSERT INTO assignment (name, mime, size, data, created, uploader, subject, chapter) VALUES ('$name', '$mime', '$size', '" . mysql_real_escape_string($data) . "', NOW(), '$nametemp', '$subjecttemp', '$chapter')");

Next to this: please consider changing to PDO instead of using the old Mysql_* functions (they're deprecated).
Comment: If I'm not mistaken, file_get_contents() is used when file is stored in the disk whereas mine is stored in database, I've tried changing echo $filedata to echo file_get_contents($filename) and what I get is a word document containing some php error code.
Comment: You upload the file to the disk (temporary), but you never insert it into the database. That's where file_get_contents() comes in: you need to use it in your upload file.
$data = file_get_contents($_FILES['browsefile']['tmp_name']);
Comment: But I see in my table structure i have one file uploaded before i asked/changed my code the size column is 12952 (which is around 12kb) and data column says [BLOB - 21 B], wasn't that file successfully uploaded?
Comment: Sorry to double post. I have changed the code according to @Blaatpraat suggestion, it still does not provide complete file (usually some error php code in the word file and the size in in bytes not kilobytes). I guess the error is in the download script.
Comment: a quick update, i have tried changing the code according to @Blaatpraat 's answer, the file fail to upload and does not stored in the database.


Throttling writes to ES from Apache Spark

Question: In our project, we are using Apache Spark to write to ES. We run multiple spark jobs that write to ES parallelly. The data volume we are dealing with too big and resulting in write throughput as high as ~5K write/sec.
We want to throttle our ES writes so as to bring it down to 500 to 1000 write/sec range. We have come across ES configs like es.batch.size.bytes and es.batch.size.entries but we are not sure how these configs can work with Apache Spark.
Comment: Kindly review the answer to the question and mark as answer if it solved your issue. [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)
Answer: Repartitioning your data in Spark using either repartition(), or more preferably coalesce() if you are lowering the number of partitions, is a simple way to throttle the rate of indexing to ES.
If you want to set the property in pyspark
esconf={}
esconf["es.mapping.id"] = "_id"
esconf["es.nodes"] = "localhost"
esconf["es.port"] = "9200"
esconf["es.batch.size.bytes"] = "1000000" //default 1mb for bulk request
esconf["es.batch.size.entries"] = "1000" //default 1000 for bulk request

df.write.format("org.elasticsearch.spark.sql").options(**esconf).mode("append").save("index_name")

Note: Note the bulk size and entries are allocated per task instance. Always multiply by the number of tasks within a Hadoop job to get the total bulk size/entries at runtime hitting Elasticsearch. This is the reason you are getting 5K write/s


How to calculate the rotation of an object wrt container, which itself is rotated wrt universe, so that the object has nil rotation wrt universe?

Question: Long subject, so I am hoping that explains what I am asking, but still let me elaborate with an example.
Let us assume we have an object as part of a container. Now the container is rotated by certain ROTATIONX, ROTATIONY, ROTATIONZ wrt the universe. Now we need to rotate the object WRT the container by rotationx, rotationy, rotationz such that the rotation of the object WRT the universe (rotx, roty, rotz) is zero. How do we do that?
Answer: There is theorem stating that in 3 dimensions, the composition of any two rotations in 3d-dimensional space is another rotations. This allows you to solve your problem as follows.
Suppose that from knowing the coordinates of the rotated container, and the coordinates of the container before rotations, you can represent $R=R_z\circ R_y\circ R_x$ by a matrix $$R=\left[\begin{matrix}a&d&g\\b&e&h\\c&f&i\end{matrix}\right]$$ where $R(1,0,0)=(a,b,c)$, $R(0,1,0)=(d,e,f)$ and $R(0,0,1)=(g,h,i)$.
Then the inverse rotation of $R$ is, in matrix form:
$$R^T=\left[\begin{matrix}a&b&c\\d&e&f\\g&h&i\end{matrix}\right]$$
So all you need is an algorithm that decomposes the matrix $R^T$ into its constituent rotations around the $x$-, $y$-, and $z$-axis. A good write-up I found via google is this blog post, along with actual computer code!.
Answer: Depending upon how you express rotations, you can just undo them in reverse order.  Rotations do not commute.  So if you did ROTATIONX, then ROTATIONY, then  ROTATIONZ, you can do rotz=-ROTATIONZ, then roty=-ROTATIONY, and finally rotx=-ROTATIONX.
Comment: The issue is that I am working with a 3-d library that applies rotation in a specific order - x, y and then z - can't change this order. So I tried the above but it does not work.
Comment: @Roopesh: I don't understand how your library limits you to a specific order? I mean, can't you just call the function three times?
Comment: @Raskolnikov - Nope.. I am using papervision3d, and it is an object property rather than a method or a function. I tried searching for solutions that let me call it in a particular order, but have not found it.


Evaluating $\int_{0}^{1} dx\frac{\log(1+x)}{1 + x^2}$

Question:
Possible Duplicate:
Evaluate the integral: $\int_{0}^{1} \frac{\ln(x+1)}{x^2+1} dx$

$$\int_{0}^{1} dx\frac{\log(1+x)}{1 + x^2}$$
I am having a hard time deriving the answer, $\frac{\pi}{8} \log(2) $.  I have tried Taylor expansion of both numerator and denominator, both seem too complicated and fruitless.
Comment: Well, it is a messy looking thing, see: [WolframAlpha - Integral above](http://www.wolframalpha.com/input/?i=Integrate%5BLog%5B1%2Bx%5D%2F%281%2Bx%5E2%29%2C+x%5D). I also verified over your integration range, and it checks out.
Comment: It is a problem from Putnam.I can't remember which.
Comment: http://math.stackexchange.com/questions/220746/integrating-frac-log1x1x2
Comment: @RichardNash, (A5 of Putnam '05)  amc.maa.org/a-activities/a7-problems/putnam/-pdf/2005s.pdf
Answer: Let $x = \tan(t)$. Then we get that
\begin{align}
I & = \int_0^1 \dfrac{\log(1+x)}{1+x^2} dx = \int_0^{\pi/4} \dfrac{\log(1+\tan(t))}{\sec^2(t)} \sec^2(t) dt\\
& = \int_0^{\pi/4} \log(\sin(t) + \cos(t)) dt - \int_0^{\pi/4} \log(\cos(t)) dt\\
& = \int_0^{\pi/4} \log\left( \dfrac{\sin(t) + \cos(t)}{\sqrt{2}} \right) dt + \int_0^{\pi/4} \log(\sqrt{2}) dt- \int_0^{\pi/4} \log(\cos(t)) dt\\
& = \int_0^{\pi/4} \log(\cos(t-\pi/4)) dt + \int_0^{\pi/4} \log(\sqrt{2}) dt- \int_0^{\pi/4} \log(\cos(t)) dt\\
& = \underbrace{\int_{-\pi/4}^{0} \log(\cos(t)) dt}_{(t-\pi/4) \to t} + \int_0^{\pi/4} \dfrac{\log(2)}2 dt- \int_0^{\pi/4} \log(\cos(t)) dt\\
& = \underbrace{\int_{0}^{\pi/4} \log(\cos(t)) dt}_{t \to -t} + \dfrac{\pi}8 \log2- \int_0^{\pi/4} \log(\cos(t)) dt\\
& = \dfrac{\pi}8 \log 2
\end{align}
Comment: From the second expression in the first line:

$\displaystyle{\int_{0}^{\pi/4}\ln\left(1 + \tan\left(t\right)\right)\,{\rm d}t = {1 \over 2}\left[\int_{0}^{\pi/4}\ln\left(1 + \tan\left(t\right)\right)\,{\rm d}t + \int_{0}^{\pi/4}\ln\left(1 + \tan\left({\pi \over 4} - t\right)\right)\,{\rm d}t
\right]={1 \over 2}\left[\int_{0}^{\pi/4}\ln\left(1 + \tan\left(t\right)\right)\,{\rm d}t + \int_{0}^{\pi/4}\ln\left(2 \over 1 + \tan\left(t\right)\right)\,{\rm d}t
\right]={1 \over 2}\int_{0}^{\pi/4}\ln\left(2\right)\,{\rm d} t={1 \over 8}\,\pi\ln\left(2\right)}$.
Comment: Very nice, I didn't see it!


Async readback storage buffer

Question: Every frame I dispatch a compute shader which write data in a storage buffer. The cpu needs to readback this data and use it. I would expect this to work :
// Dispatch compute shader
glDispatchCompute(x, y, z);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
void* data = glMapNamedBuffer(buffer, GL_READ_ONLY);

But it would introduce a sync point which I'd like to avoid. I'd like to hide the latency by reading the data written by the previous frame dispatch. If I was using textures I would have used PBOs, but I have not found a way to do this for storage buffers.
Answer: First, that's the wrong memory barrier. The barrier is for how you intend to use the memory, not how it was written to.

I'd like to hide the latency by reading the data written by the previous frame dispatch.

This is a general flaw in OpenGL: targeted synchronization of such memory operations is not possible.
In Vulkan, you can be extremely specific about both execution and visibility operations. When you start the dispatch, you can stick an event after it, which you can wait on using a specific execution and memory barrier.
In OpenGL, you only really have two tools: fence sync objects and a broad memory barrier that covers all prior commands which have executed. And sync objects don't actually ensure visibility. Yes, you can set a fence right after your dispatch, and spin on the CPU (doing actual work between checks of the fence). But even after the fence has completed, you can't guarantee visibility without firing off the barrier. And that barrier will affect all memory operations that were submitted before the barrier was called.
So if you had two dispatch operations, and call glMemoryBarrier after both of them, the barrier will wait on all of them, even if you only care about waiting for the first one.
The best you can really do is just delay the memory barrier call for as long as possible. But it's going to synchronize against all submitted commands when you call it.
You might also try... cheating. Use a persistent/coherent mapped buffer, and use a fence sync object on the CPU instead of calling the memory barrier. This is undefined behavior by the OpenGL specification, but on real systems, the fence sync should ensure execution of the operation, and the coherently-mapped buffer ought to ensure visibility.
But that doesn't mean it will. So don't expect miracles.

Async readback storage buffer


How to treat mold on a single stud?

Question: I live in a house built in 1955. While remodeling a closet, I found a single moldy jack stud, right next to a non-moldy king stud. The mold itself seems to be dry. I was able to cut a little bit off from the wood and below the surface the wood seems stable, no soft spots or similar.
This is an inside wall which connects two bedrooms, with no water lines running anywhere close. Above this is the attic (with no water leak) and below is a crawl space that has a sump pump which is also working.
When opening the closet prior to demolition, I always smelled something musty/earthy. Due to the location of the stud I only have access to one side. I have read other posts related to mold on this side and have seen the recommendation to use 3% Hydrogen peroxide.
I have multiple questions regarding my issue:

Would treatment of only one side of the stud have any chance of success?
Given that this is an old house and the mold hasn't spread to other studs or the wall, is it safe to say that this mold is "inactive"/not actively spreading?
The wood is different in this stud than in any of the other ones. Could the mold have been there originally, for example because the wood was moist?
Would the best remediation be to replace this stud?

My ultimate goal is to get rid of the smell and don't have mold spores in the air.
Comment: Did you test it for mold?  Are you sure it is not dirt/stain?  Mold usually wants damp, dead air, lack of light.  Odd for it to be only on one stud.  Spraying some bleach on it stops mold.  Mold spores are in the air anyway to some extant.
Comment: Not all studs in a house had a pampered life.
Comment: That's a good point, I am not sure. I will test it for mold next. I suspect that the wood might have been "infected" prior to installation as it looks different than the other studs.
Comment: If you're 100% sure that this isn't due to water getting on the wood, encapsulation is likely to be your best path forward unless you want to tear things apart enough to fully replace the board.
Answer: I treated the stud with bleach (a mold removal product) and later with hydrogen peroxide after it was dry. I repeated the process twice for good measure. I also exposed it completely to the subfloor and it wasn't moldy from the bottom, luckily. Here's an after picture.

How to treat mold on a single stud?


How Filter Objects what contains in FK?

Question: I have three Models, like Store, ProductsArea and Item. A Store can have many ProductsArea, and ProductsArea can have many Items.
    #models.py
    class Store(models.Model):
        name = models.CharField(max_length=64, unique=True)
        description = models.TextField(null=True, blank=True)

    class ProductArea(models.Model):
        store = models.ForeignKey(Store, related_name='productarea', on_delete=models.CASCADE)
        name = models.CharField(max_length=64,verbose_name=_('Name'))

    class Item(models.Model):
        product_area = models.ForeignKey(ProductArea, related_name='items', on_delete=models.CASCADE, verbose_name='Menu')
        name = models.CharField(max_length=64, verbose_name=_('Name'))
        price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('Price'))

In my view I'm using CBV, and I want return all Items what contains the same ProductArea, clicking  ListItems from determined ProductArea, with FK they get all items from ProductArea. The same for ProductArea in Store.
Store - Clothes Store
Product Area - Shirts, Pants
Item - Shirt Yellow(PA.Shirts), Shirt Blue(PA.Shirts)
Item - Pant Black(PA.Pants), Pants Red(PA.Pants)

If a click in Shirts, I want return a list with a Shirt Yellow and a Shirt Blue.
I tried this in my view :
def get_queryset(self):
    product_area_id = ProductArea.objects.get(id)
    product_area = ProductArea.objects.get(pk=product_area_id)
    items_in_productarea = Item.objects.filter(product_area=product_area)
    return items_in_productarea

But doesn't work,have builtin_function_or_method' object is not iterable
Can anyone help me? Thanks a lof friends.
Comment: Well first of all `id` is *not* the `id` of the URL (please post your relevant `url` as well), it is the identity function.
Answer: The problem is that you use id [Python-doc]. Now id is a builtin Python function: it maps all objects to a number that is unique. It is used for example to check if two variables refer to the same object. The details of id are not really important here, the point is that id is not the id here in the URL.
You will need to fetch the id from somewhere, for example it can be part of the URL. We can specify it in the urls.py:
#  app/urls.py

from django.urls import path

urlpatterns = [
    path('items/<int:area_id>/', MyItemView.as_view(), name='my_item_view')
]
I would advice to use an area_id here instead of id since otherwise it might give the (false) impression that it is the id of the Items.
Then we can process the URL parameter with self.kwargs:
#  app/views.py

from django.views.generic.list import ListView
from app.models import Item

class MyItemView(ListView):

    # ...

    def get_queryset(self):
        return Item.objects.filter(product_area__id=self.kwargs['area_id'])
If you the fetch localhost:8000/items/123 (with 123 the idea of the ProductArea, the URL can be different if for example the app/urls.py are included in a non-empty path), you will get a list of Items that belong in this ProductArea.
Comment: Nice solution, and great explanation...it's works, I got it and will apply in other things in my project. Thanks a lot friend.
Comment: Please, select the answer as the correct answer if it is the solution. Thanks.

How Filter Objects what contains in FK?


Where are sudo incidents reported?

Question: Attempting something devious on my machine leads to
ryan@debian:~$ sudo EAT_ALL_THE_COOKIES_BEFORE_DINNER
[sudo] password for ryan:
ryan is not in the sudoers file.  This incident will be reported.

Where is this incident reported, and how do I get the log of all the nasty attempted commands?
Answer: Nevermind, I just found the answer in the alt-text at xkcd:

Replace root with your username, in my case ryan, so the log is found with:
cat /var/spool/mail/ryan

Comment: I know this is tagged 'debian', but I came looking for Ubuntu. So for the benefit of others looking for Ubuntu's output log, I found sudo failures in: `/var/log/auth.log`
Comment: There's nothing in `/var/spool/mail` in distributions using systemd (Archlinux in my case). In this case, you can find that report in the journal by using `journalctl` command. (@shellter - due to closed topic - disagree - I had to post a comment, not another valid answer)
Comment: Shouln't it be `root` unless there is some forwarding set? The whole point should be that the email is sent to the administrator. Also, sure, once some forwarding is set, you can cat the spool file, but you can also use some mail client, like mail, nail, or something else that supports reading from the local spool (I'd say that this is usually the case except maybe for GUI clients "imported" from the Windows world).
Comment: @dmnc I can confirm this, the `journalctl` command for this is `sudo journalctl /bin/sudo`.
Comment: @CJBS In Ubuntu under WSL I had to run `sudo service rsyslog start` to start the logging service.
Comment: More specifically, to only see sudo failures in Ubuntu use `cat /var/log/auth.log | grep sudoers`.
Answer: The report is sent as an email to the root user. Many Linux distributions will automatically setup an alias for that user directing the mail to the first account created during the install process.

Where are sudo incidents reported?