Is there a way to check if others are logged into server when you are?

Question: I am logged into Ubuntu server via ssh and I would like to know if another user is logged in via SSH as well. Is there a command that I can run to accomplish this?
Answer: Just type who:
~$ who
(unknown) tty7         2013-12-06 13:37 (:0)
john      pts/0        2013-12-08 00:16 (192.168.0.100)
jane      pts/1        2013-12-08 00:17 (192.168.0.101)

EDIT
Regarding your bonus question :)
To see login history for users you can use last -i. This will show all logins and IP addresses since start of current logfile /var/log/wtmp.
Depending on your logrotate you can show previous logs with last -f /var/log/wtmp.1, too.
To only show the very last login for each user use last -i | sort -r | uniq -w 16
~$ last -i | sort -r | uniq -w 20
wtmp begins Sun Dec  1 16:54:49 2013
john    pts/0        192.168.0.100    Sun Dec  8 18:49   still logged in
jane    pts/1        192.168.0.101    Sun Dec  8 00:17 - 00:34  (00:16)

Comment: When I type it it doesn't give me the ip address. Is there  a way to force the ip address?
Comment: You can use `who --ips`. I manually changed the output above to hide my internal network structure :)
Comment: Can I ask one more bonus question? Is there a way to get a list of ip addresses with the last time users have logged in from these ip addresses?
Comment: take a look at my edit
Answer: who is good, but simply w is better.
Comment: It would be nice if you explained the difference :-)
Comment: Please edit your answer accordingly - I myself know what I am using :-))
Comment: Only answers are kept here - comments will vanish some time - so what you say in a comment will get lost eventually.
Comment: It's a personal taste thing. But if I had to convince someone I would say that `w` is shorter than `who` but prints out more. So we get more for less. :) Or I would just quote from the manpages: **who - show who is logged on** but **w - Show who is logged on and what they are doing.** And it is obvious that we want to see what others are doing :D
Comment: Why? For me the answer is good. Simple question simple answer.
Answer: and in realtime:
$ watch -n 1 w


How to make a launcher that will first navigate to a folder and then execute a command that resides in normal  /usr/bin/

Question: Okay this Question is basically directed for using GRIVE the linux client for Google Drive
Details on how to do it are Here.
The thing is that,evrytime i want the folder to sync,I have to navigate to the google drive folder and then execute the grive commnd.
I want to make it simple..I want to make a launcher(I know how to make a *.desktop file).
But in a .desktop file you always give path to executable file(generally .sh).
Here,there is no script in the Grive folder.The app is as usual in /usr/bin/grive
Now how do I make the launcher to first navigate to the grive folder and then execut the grive command..
Thanx :)
Comment: @virpara..Plz have a look at this..I belive you have the solution.. ;) thanx.!
Comment: @virpara..Got the answer.. :p izx help me.. ;)
Answer: In the .desktop file, set
Exec=sh -c "cd /path/to/directory/to/sync && grive"
and set Terminal=true
Comment: Not working...It says `Exec=sh` no such file or directory
Comment: oops...sorry...it worked...my rong...i cpied the `Exe=` along with the other thing and added it afte `Exec=` again.. :p...sorry..n thanx..!! ;)
Comment: yup...will be allowed to do it in 2min ;P


Ajax features broken across browsers (on one machine)

Question: I have built a CMS system using jQuery and PHP, it has worked consistently for multiple users across different platforms over the past year or so.
Today as I was presenting it to a potential customer over the phone he ran into a problem in Internet Explorer 8, for some reason he was not able to log in to the system so I created a dirty hack to allow him in without authorizing, this allowed him to see the interface, but again, all features were still broken when it came to XMLHttpRequests, this puzzled me so I guided him through a Firefox 3.6 install over the phone with the same result, I have since checked with friends and family at remote locations and across platforms and they seem to be able to do everything he could not I have run out of ideas, so here is the question:
Has anyone ever run into this same problem and how did you solve it?
Update: I know JavaScript works, some of the other features works as intended, I have also checked for lingering console.log etc that could screw up the results, its all clear.
Comment: Maybe the customer had javascript turned off?
Comment: The customer is not available over the weekend I will follow up on this as soon as I know more
Answer: There are thousands of possible reasons, 2 that immedatly come to my mind are:

His/His companies Firewall might block those requests
He might have disabled scripts in IE8 and maybe firefox imported this setting (don't know about that)
Answer: Javascript and/or some of outbound requests may have been disabled completely or partially filtered by your customer's firewall/IPS/IDS.
Disable JavaScript and try to reproduce the problem on your machine. If result is the same - that's your problem.
Comment: I will try and figure out if the firewall is blocking, but doesnt that seem unlikely considering its all running on port 80?
Comment: Some Firewalls might block if the javascript url is i.e. www.example.com/js/foo.js and the page is on example.com. Another possibility might be bad words in the script path (=> ad, banner, tracking, ...). You'd be suprised of how creative some sysadmins are when it's about blocking the "evil javascript" preventing them from using their favourite lynx browser making them ban all javascript.
Answer: It turned out that the issue was with an aggressive anti-virus program and he had checked the option to "Secure my privacy", part of that "Security" was to delete new cookies.


Is there anyway to increase my dedicated VRAM on HP laptop

Question: I am planning to buy 'The Talos Principle' game. The minimum VRAM for this game is 526 MB and my laptop has 4 GB RAM, but the dedicated VRAM is only 128 MB. Is there anyway to increase my dedicated VRAM on an HP laptop? I have DirectX12.
Also, is it possible or would it help to run the game by connecting to the TV with HDMI cable?
Comment: Have you checked BIOS to see if there's a setting there you can update (to 768 perhaps?)
Comment: This isn't really a gaming question, seems more a generic hardware upgrade question. You might get better results if posting in a group specific to your laptop maker or hardware upgrades.
Comment: Low-end specs are often estimates, and usually based on recommendations that will give a pleasant user experience. In other words, the game will probably run, just not as fast as on a more powerful system. Sometimes a faster CPU can compensate for a slower GPU or storage. YMMV.
Answer: Dedicated memory (aka VRAM), no, but...
The only way to increase that, is to replace the graphics adapter, which is typically not possible on laptops. Fortunately, you can just connect an eGPU (external GPU) instead. The caveat is that eGPUs aren't as mobile, and not all laptops are compatible to them.
According to HP:

When it comes to upgrading your gaming setup, detail is everything. Most eGPU docks require the host computer to have a Thunderbolt™ 3 port to connect to the external graphics dock. Thunderbolt 3 is a high-speed input/output port from Intel® that allows the eGPU to communicate with the laptop to provide accelerated graphics.
[...]
In addition to compatibility with your laptop's connection, you'll also want to consider an eGPU's compatibility with the graphics card of your choice. Some eGPU docks have graphics cards pre-installed, while others give you the freedom to choose the right graphics card for you.

Shared GPU memory, maybe.
Windows 10 will let the GPU use roughly 50% of your RAM should the GPU not have enough VRAM. Whether you can upgrade your RAM depends on whether your notebook supports it.
However, for the GPU, RAM access is much slower than VRAM access, so your FPS will suffer a lot. This will likely make the game unplayable, no matter how fast your GPU is. With only 128 MB VRAM, it's very likely your GPU isn't fast enough to play this game anyway.
If your GPU is an IGP (integrated GPU), its VRAM will come from RAM. Your UEFI/BIOS will assign part of the RAM to be used exclusively for the IGP. If your UEFI/BIOS supports it, you can change how much RAM will be assigned to the IGP. Whether you can assign 526 MB or more is a different matter, however.

Also, is it possible or would it help to run the game by connecting to the TV with HDMI cable?

No. The screen only displays what your PC tells it to. A person without hands won't be able to play poker any better if he got an extra pair of eyes either.
Comment: My graphic card is DirectX12, on windows 10, the game did RUN on my laptop even though I have only 128 MB VRAM and the minimum VRAM for this game is 526 MB. Thanks everyone for your kind help.


How to install driver of HL-5450DN in Ubuntu 18.04

Question: I want to install the driver of HL-5450DN brother printer in Ubuntu 18.04. There are two driver files: hl5450dncupswrapper-3.0.0-1.i386.deb and hl5450dnlpr-3.0.0-1.i386.deb. It is no problem to install hl5450dncupswrapper. However, hl5450dnlpr can not be installed. I always get this error:
/var/lib/dpkg/info/hl5450dnlpr.postinst: 3:
/var/lib/dpkg/info/hl5450dnlpr.postinst:
/opt/brother/Printers/HL5450DN/inf/braddprinter: not found

So, what shall I do next?
Comment: I wish I could upvote this question even more. I find myself googling to find this specific question whenever I want to install a Brother printer. Finding the [installer link](http://support.brother.com/g/b/downloadend.aspx?c=us⟨=en∏=hl5450dn_all&os=128&dlid=dlf006893_000&flang=4&type3=625) (mentioned in the answer below) is nigh impossible through Brother's own website. It asks all sorts of irrelevant things first, like your location and printer model, and then presents the .deb files on their own, which aren't enough.
Answer: The driver tool didn't work for me either, but here is how I solved it:
Printer HL1210w, ia32-libs is not available to install normally, braddprinter file is there but I can't execute it, dpkg --force-all install not working)
file braddprinter

you will see a dynamic library (.so),  use it in the next command (mine was ld-linux.so.2)
apt-file search ld-linux.so.2

this will show one ore more packet names. You are interested in ones that have -i386 (mine libc6)
sudo apt-get install libc6:i386

this will give the libraries that you probably miss.
Now run the
dpkg install --force-all

Comment: Works! Thank you. I had to change : to - in the line "sudo apt-get install libc6:i386"
Answer: perhaps you let the Brother Installer Tool see if it can sort things for you; if you go here http://support.brother.com/g/b/downloadend.aspx?c=us&lang=en&prod=hl5450dn_all&os=128&dlid=dlf006893_000&flang=4&type3=625 and click to download and SAVE what will be linux-brprinter-installer-2.2.0-1.gz
If you open a terminal; copy each command in line by line; paste each line into the terminal; (hit the ENTER key after each paste;) then on to the next command;
cd Downloads

gunzip linux-brprinter-installer-2.2.0-1.gz

sudo bash linux-brprinter-installer-2.2.0-1 HL-5450DN

and see if that does any better
Comment: Perfect! It works very fine. Thank you very much!
Comment: THANK YOU.  My specific case was (first" "gunzip linux-brprinter-installer-2.2.1-1.gz" then (second) "bash linux-brprinter-installer-2.2.1-1 DCPL2540DW"   .. Note, I skipped the "Will you specify the Device URI?" in the command line interactions, but then I (using the "Printers" UI component in ubuntu) .. just deleted the printer and re-added, but it found the driver this time.  Been working on this for 2 hours.  Thanks!!


Polygonal Gradients

Question: I am working on a project that uses the Juce library to display graphics.
So far I have been using the library's API functions to generate linear and radial gradients, however that's the only two types of gradients that this library supports. I am now in need of generating a different type of gradient, one that follows the shape of a regular convex polygon. The key word here is REGULAR, meaning a polygon with all edges of the same length and with all vertices lying on a single circle.
For the case of a pentagon, here is a picture to better show the result I would like to get:
http://www.filterforge.com/wiki/index.php/Polygonal_Gradient
For my application, I want to be able to specify a polygonal gradient with any number of edges. (pentagon, hexagon, octagon, etc...)
Given the limitations of the API, the only way I can produce the desired result is to fill a surface matrix pixel by pixel, mathematically calculating the values of the R, G, B, A components for each pixel.
Here is the code I have so far:
void render_surface(unsigned char *surface_data,
                    int width, int height, int linestride,
                    int num_vertices, t_rgba *color1, t_rgba *color2)
{
    const double center_x = 0.5 * width;
    const double center_y = 0.5 * height;
    const double radius = 0.5 * MIN(width, height);
    int x, y;

    for (y = height; --y >= 0;) {

        uint32_t *line = (uint32_t *)data;
        data += linestride;

        const double dy = y - center_y;

        for (x = width; --x >= 0;) {

            const double dx = x - center_x;

            double rho = hypot(dx, dy);
            rho /= radius;    // normalize radius

            // constrain
            rho = CLIP(rho, 0.0, 1.0);

            // interpolate
            double a = color2->alpha + (color1->alpha - color2->alpha) * rho;
            double r = color2->red   + (color1->red   - color2->red  ) * rho;
            double g = color2->green + (color1->green - color2->green) * rho;
            double b = color2->blue  + (color1->blue  - color2->blue ) * rho;

            // premultiply alpha
            r *= a;
            g *= a;
            b *= a;

#if LITTLE_ENDIAN
            *line++ = ((unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * a) << 24) // alpha
                    | ((unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * r) << 16) // red
                    | ((unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * g) <<  8) // green
                    |  (unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * b);       // blue
#else
            *line++ = ((unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * b) << 24) // blue
                    | ((unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * g) << 16) // green
                    | ((unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * r) <<  8) // red
                    |  (unsigned int)((256.0 * (1.0 - DBL_EPSILON)) * a);       // alpha
#endif
        }
    }
}

The above code produces a radial gradient, the same type of gradient I could produce using one API function. However it seems to be a good starting point to tackle the problem.
surface_data - is a matrix of 8 bit values representing the pixel intensities of the Red, Green, Blue and Alpha components.
num_vertices - is the number of vertices (equally spaced on a single circle) that we want our polygonal gradient to have.
color1 - starting color of the gradient.
color2 - ending color of the gradient.
I would like to know how I can fill a surface in the same fashion, creating a polygonal gradient as opposed to radial.
Thanks for any help.

Luigi

Rethinking about this problem a little bit...
if we consider the origin of our coordinate system the center of the polygon, it boils down to finding an equation such that for any input point in cartesian coordinates, the output is the distance from the closest side of the polygon.
My intuition tells me that there must be some kind of closed form solution because:
for a circle,
rho = sqrt(dx*dx + dy*dy);

gives us the radial distance from the center of the circle, which could be considered as a polygon with infinite sides.
For a square,
fmax(fabs(dx), fabs(dy));

gives us the Chebyshev distance from the closest side of the square, which could be considered as a polygon with 4 sides.
So, I am thinking that some kind of combination of the two formulas should give the intermediary cases, which would solve the initial problem.
Am I totally off thinking along these lines?

Luigi
Answer: This is roughly how I'd approach it ...

Place the center of the polygon at the origin 'O'.
For a given point 'P' within a given segment of a regular polygon, let the line through
'O' & 'P' be 'Line1' and
let the line through the outer edge of the
containing polygon segment be 'Line2'
Find the intesection point 'IP' of these 2 lines.

Now the color fraction at P is defined by the distance of P to the origin relative to the distance of IP to the origin.

Edit: I've implemented the algorithm above and this is the output ...

Edit2:
Here's the (Delphi) code
const
  vertical: TFloat = 3.4e38;

function Slope(const pt1, pt2: TFloatPoint): single;
begin
  if (pt1.X = pt2.X) then result := vertical
  else result := (pt2.Y - pt1.Y)/(pt2.X - pt1.X);
end;
//---------------------------------------------------------------------------

procedure GetLine(const pt1, pt2: TFloatPoint; out m, b: TFloat);
begin
  m := Slope(pt1, pt2);
  if m = vertical then
    b := pt1.X else
    b := pt1.Y - m * pt1.X;
end;
//---------------------------------------------------------------------------

function GradientColor(const clr1, clr2: TColor32; fraction: TFloat): TColor32;
begin
  if fraction <= 0 then result := clr1
  else if fraction >= 1 then result := clr2
  else
  begin
    TColor32Entry(result).B :=
      trunc(TColor32Entry(clr2).B * fraction + TColor32Entry(clr1).B * (1-fraction));
    TColor32Entry(result).G :=
      trunc(TColor32Entry(clr2).G * fraction + TColor32Entry(clr1).G * (1-fraction));
    TColor32Entry(result).R :=
      trunc(TColor32Entry(clr2).R * fraction + TColor32Entry(clr1).R * (1-fraction));
    TColor32Entry(result).A :=
      trunc(TColor32Entry(clr2).A * fraction + TColor32Entry(clr1).A * (1-fraction));
  end;
end;
//---------------------------------------------------------------------------

function PointInTriangle(const pt, tr1, tr2, tr3: TFloatPoint): boolean;
begin
  result := false;
  if ((((tr1.Y <= pt.Y) and (pt.Y < tr3.Y)) or
    ((tr3.Y <= pt.Y) and (pt.Y < tr1.Y))) and
    (pt.X < (tr3.X - tr1.X) * (pt.Y - tr1.Y) /
    (tr3.Y - tr1.Y) + tr1.X)) then result := not result;
  if ((((tr2.Y <= pt.Y) and (pt.Y < tr1.Y)) or
    ((tr1.Y <= pt.Y) and (pt.Y < tr2.Y))) and
    (pt.X < (tr1.X - tr2.X) * (pt.Y - tr2.Y) /
    (tr1.Y - tr2.Y) + tr2.X)) then result := not result;
  if ((((tr3.Y <= pt.Y) and (pt.Y < tr2.Y)) or
    ((tr2.Y <= pt.Y) and (pt.Y < tr3.Y))) and
    (pt.X < (tr2.X - tr3.X) * (pt.Y - tr3.Y) /
    (tr2.Y - tr3.Y) + tr3.X)) then result := not result;
end;
//---------------------------------------------------------------------------

function GetSegmentIndex(vertex: TFloatPoint; vertices: TArrayOfFloatPoint): integer;
var
  i, highI: integer;
  prev: TFloatPoint;
const
  origin: TFloatPoint = (X: 0; Y: 0);
begin
  highI := high(vertices);
  prev := vertices[highI];
  result := -1;
  for i := 0 to highI do
  begin
    if PointInTriangle(vertex, origin, prev, vertices[i]) then
    begin
      result := i;
      break;
    end;
    prev := vertices[i];
  end;
end;
//---------------------------------------------------------------------------

procedure RegularPolygonFill(bmp: TBitmap32; const origin: TPoint;
  radius: TFloat; vertexCount: integer; InnerColor, OuterColor: TColor32);
var
  i,j,d,q: integer;
  dist1,dist2: TFloat;
  vert, intersetPt: TFloatPoint;
  verts: TArrayOfFloatPoint;
  edgeMs, edgeBs: TArrayOfFloat;
  angle, angleDiff, m, b: TFloat;
  sinAngle, cosAngle: extended;
const
  orig: TFloatPoint = (X: 0; Y: 0);
begin
  if vertexCount < 3 then exit;
  setlength(verts, vertexCount);
  setlength(edgeMs, vertexCount); //edge slopes  (ie y = M*x +b)
  setlength(edgeBs, vertexCount); //edge offsets (ie y = m*x +B)
  angleDiff := pi *2 / vertexCount;
  angle := angleDiff;
  vert.X := radius; //vert used here as prev vertex
  vert.Y := 0;
  for i := 0 to vertexCount -1 do
  begin
    SinCos(angle, sinAngle, cosAngle);
    verts[i].X := cosAngle * radius;
    verts[i].Y := sinAngle * radius;
    GetLine(vert, verts[i], edgeMs[i], edgeBs[i]);
    angle := angle + angleDiff;
    vert := verts[i];
  end;

  d := floor(radius);
  for i := -d to d do
    for j := -d to d do
    begin
      vert := FloatPoint(i,j);
      GetLine(orig, vert, m, b);
      q := GetSegmentIndex(vert, verts);
      if q < 0 then continue;
      //simultaneous equations to find intersection ...
      //y = m * x + b; y = edgeMs[q]* x + edgeBs[q];
      //edgeMs[q]* x + edgeBs[q] = m * x + b;
      //(edgeMs[q] - m) * x = b - edgeBs[q]
      //x = (b - edgeBs[q])/(edgeMs[q] - m)
      if m = vertical then
      begin
        intersetPt.X := b;
        intersetPt.Y := edgeMs[q]* intersetPt.X + edgeBs[q];
      end
      else if edgeMs[q] = vertical then
      begin
        intersetPt.X := edgeBs[q];
        intersetPt.Y := m* intersetPt.X + b;
      end else
      begin
        intersetPt.X := (b - edgeBs[q])/(edgeMs[q] - m);
        intersetPt.Y := m * intersetPt.X + b;
      end;

      //get distances from origin of vert and intersetPt ...
      dist1 := sqrt(vert.X*vert.X + vert.Y*vert.Y);
      dist2 := sqrt(intersetPt.X*intersetPt.X + intersetPt.Y*intersetPt.Y);

      bmp.Pixel[i + origin.X, j + origin.Y] :=
        GradientColor(InnerColor, OuterColor, dist1/dist2);
    end;
end;

Comment: yes, I haven't tried to directly implement your solution, but at least theoretically it should work. However it involves quite a bit of computation. I was hoping for some kind of closed form equation, simpler and more concise. The input to the equation would be a point in cartesian coordinate and the output the distance from the closest side.
Comment: For polygons with an even number of sides, this can be sped up considerably by only calculating pixels for one half of the polygon and then mirroring the colors across the midline. Likewise, for polygons with multiples of 4 sides, this can be sped up even more by only calculating pixels for just one quarter of the polygon and then mirroring the pixel colors across the both horizontal and vertical midlines.
Comment: Yes, it looks totally right. Thank you. Would you mind sharing your implementation? I would be very interested in seeing some actual code. (the language doesn't matter)
Comment: Sure, but I want to tidy it up a bit first. But before that I need some sleep :).
Answer:
My intuition tells me that there must be some kind of closed form solution

There is...
Anaylsis
For this I've taken the formula for the distance from the center to the edge of a hexagon (here) and noticed it can be generalised to any polygon. In that particular formula, the constant sqrt(3) is used (which I'll now call z). This number is equivalent to twice the ratio of the distance between the polygon midpoint and the midpoint of one of its edges compared to the distance between the midpoint and one of its vertices (this distance is 1 in a unit length polygon).
So, this constant (which is sqrt(3) for hexagons) is given by:

This ratio, which I described before, is given by:

Notice the 2s cancel out, so the general function to derive this constant for any polygon is:

SIDES is the number polygon sides (e.g. 6 for hexagon)
Now we simply plug this constant into the formula for the ratio of a where a point lies on a given unit length polygon compared to where it would lie on a unit length circle:

Example
How this works out is show below for a hexagon (so SIDES=6 and z=sqrt(3)). We get d as 0.866 for a θ=30° and d as 0.897 for θ=45° (also equivalent to θ=15°).
Note that d is only defined properly for 0 <= θ <= segmentAngle (which is given by 2PI/SIDES in radians).

Implementation
Now we have all we need to code a solution.
The following function maps a 2D (pixel) coordinate to a number between 0 and 1; this number specifies at which point (the step) in the colour gradient each pixel occurs.
Ultimately, this is fairly similar to a radial gradient, where the euclidean distance between the pixel and circle midpoint is used to define the step of the pixel. With polygonal gradients however, we want to scale the euclidean distance between a pixel (x,y) and the midpoint of the polygon by d, such that colours are "pushed" towards the edges of the polygon (a.k.a chord of the circle).
When it comes to rendering, the only thing is multiplying d by a denominator so that the polygon renders at an appropriate scale.
Code
public void polygonGradient(colour[][] pixels, Gradient gradient, Vector2 midPoint, float angle, float zoom, int sides) {

    final double z = Math.tan(HALF_PI - (PI / sides)); // z, as derived in answer
    final double SEGMENT_ANGLE = (2 * PI) / sides; // max angle of polygon segment in radians

    angle %= SEGMENT_ANGLE; // mod angle to minimise difference between theta and SEGMENT_ANGLE in loop (less while calls)

    final double denominator = 1 / ((Math.max(pixels.height, pixels.width)) * zoom); // calc here once, not in loop

    double yDist; // y distance between midpoint and a given pixel
    double xDist; // x distance between midpoint and a given pixel

    for (int y = 0, x; y < pixels.height; ++y) {
        yDist = (midPoint.y - y) * (midPoint.y - y);

        for (x = 0; x < pixels.width; ++x) {
            xDist = (midPoint.x - x) * (midPoint.x - x);

            double theta = Math.atan2((midPoint.y - y), (midPoint.x - x));
            theta += (TWO_PI - angle); // TWO_PI - angle, so we rotate clockwise
            theta = Math.abs(theta); // abs() here to simplify while loop

            // polygon is split into N segments; restrict theta to angle of one segment
            while (theta > SEGMENT_ANGLE) { // effectively modulo (faster than using % operator)
                theta -= SEGMENT_ANGLE;
            }

            final double pointDistance = Math.sqrt(yDist + xDist); // euclidean dist between (x,y) and midpoint

            double d = z * (z * Math.cos(theta) + Math.sin(theta)); // d, as derived in answer

            // now calculate the position of the pixel on the gradient
            double step = d  * denominator * pointDistance; // multiply euclidean distance by d

            if (step > 1) { // clamp to 1
                step = 1;
            }

            pixels[x][y] = gradient.colourAt(step); // get the colour of the gradient at the step given by dist
        }
    }
}

Output
Sides = 6

Sides = 9

Sides = 3; zoomed a bit; midpoint off centre

Sides = 5; non-linear colour interpolation

Polygonal Gradients


package containing stb_image.h?

Question: Have just moved some development from a Fedora system to Ubuntu, but I'm having a few problems.
I cannot find which package provides stb_image.h. On Fedora it was something starting stb or stbi, but nothing like that seems to exist with the synaptic package manager.
Can anyone point me to the right thing.
Thanks.
Comment: May [libsoil-dev](https://packages.ubuntu.com/search?suite=xenial&arch=amd64&mode=filename&searchon=contents&keywords=stb_image) package be related (it has */usr/include/SOIL/stb_image_aug.h*)?
Answer: It doesn't look like it's been packaged by anybody, but you can always clone from source:
git clone https://github.com/nothings/stb.git
sudo cp stb/stb_image.h /usr/local/include/

Comment: Ok. Thanks done that. Works. Just a little suprised it's not available on Ubuntu, whereas it is with Fedora. Fedora are usually very picky about what they package.
Comment: Cool! If you wouldn't mind, please [accept my answer](https://stackoverflow.com/help/accepted-answer) since it worked for you.
Answer: There is a package now.
sudo apt install libstb-dev

package containing stb_image.h?


Syntax message given when i submit a def command

Question: I'm following a tutorial from my internal work training (similar to online school),and there is this project that tells you to write some code following the instructions on the videos given, and there is one that gives me a syntax error but, since I'm am very new to programming I don't understand why is it, I've used different combinations but no success.
I'm learning Python 3 IDE to write the code
Code:
class Bot:
    def __init__(self):
        self.age = 1
        self.name = "Bot1"
        print (self.name, "has been created ", ", age", self.age)

    def talk (self, words = ("I dont know what to say :("))
        print self.name, ":", words

Bot1 = Bot()
Bot1.talk()
Bot1.talk("Hello, im talking")

This is the error message I received:
"
Traceback (most recent call last):
File "python", line 7
   def talk (self, words = ("I dont know what to say :("))
                                                      ^
SyntaxError: invalid syntax
"

Comment: You are missing a colon `:` at the end of your function signature
Comment: Python code needs to be properly indented or it will not work. A `def` line needs a colon at the end. The arguments to `print` need to be in parentheses.
Comment: You really should check out a basic online Python tutorial or text book before attempting to write Python code. An IDE isn't in and of itself a learning tool.
Answer: Your code is missing a colon : at the end of your function signature, and is also lacking indentation (which is required in Python). The corrected code is as below-
class Bot:
    def __init__(self):
        self.age = 1
        self.name = "Bot1"
        print (self.name, "has been created ", ", age", self.age)

    def talk (self, words = ("I dont know what to say :(")):
        print self.name, ":", words

Bot1 = Bot()
Bot1.talk()
Bot1.talk("Hello, im talking")

Comment: I appreciate all your help, i was able to make it work! :)
Answer: You need a colon at the end of line 7.
Note: Then every line in the function should be indented.
Answer: Change your code to the following:
class Bot:
    def __init__(self):
    self.age = 1
    self.name = "Bot1"
    print (self.name, "has been created ", ", age", self.age)

    # This should have been indented to be inside of the class
    # You didn't need brackets around your "words" parameter.
    def talk(self, words="I dont know what to say :("): # You needed a semi-colon here
        print(self.name, ":", words) # You needed to add brackets here.

Bot1 = Bot()
Bot1.talk()
Bot1.talk("Hello, im talking")


Allow UILabel to grow dynamically using auto layout

Question: I have a label which is going to contain a big description. I want the label to continue growing on new lines. In the image, its the label which starts with event_venue.....
The even_venue.. label has 3 constraints for now:

Vertical space with eventt_title
a horizantal space with the leading of the superview
a width constraints which defines that the label width is always less than the superview.width.

What I want to acheive is to make the event_venue.width less than superview.width, but if it has more text, it should display in new lines. Is this possible using autolayout?
Comment: It sure is possible but I would actually use `UITextView` with `editable = NO;`
Comment: Just need to set number of lines to zero.
Answer: Yes, this totally is possible. I see answers here that are close to solution but not complete. Here is a solution which works with auto layout in Storyboard, no coding of sizeToFit or anything. Your modified steps would be:

Vertical space with eventt_title
A horizontal space with the leading of the superview
A horizontal space with the trailing of the superview
Set UILabel's Line Breaks as Word Wrap.
Set UILabel's lines property as 0.
Answer: This are possible steps which can create expandable UILabel

Set layouts for UILabel fixing its position
Set number of lines = 0
Set content vertical compression resistance to 1000 (this will allow text to push the label)
Since you want UILabel to expand you cannot give it fixed height constraint or its parent fixed height constraint. Sometimes depending upon condition giving height constraint is necessary to avoid error then you need to set its priority lower than vertical compression resistance
Answer: I had a similar question about label resizing, and the answer that I found that was useful to me is here: UILabel Auto Size Label to Fit Text. This is a good starting source for code on how to resize your label programmatically.
I would recommend that you also add a horizontal trailing auto layout constraint from the label to the edge of the superview. Do that and you can then get rid of your current width constraint.
Answer: I have solved a similar problem. I had to make a label that had a variable amount of text.  Here's what I did:

In the storyboard, place your label with the origin where you want it.
In the Attributes Inspector, "Label" section, set the Line Breaks = Word Wrap
Fill the label with random placeholder text to the maximum shape you want.  For example, if you wanted to fill the whole width and have room for a maximum of three lines of text, you could do:
abcdefghijklmnopqrstu
abcdefghijklmnopqrstu
abcdefghijklmnopqrstu
In the code, set the text of the label using setText:
[self.myLabel setText:@"MyLabelText"];

This did it for me.  Your situation may be a little different in that I wasn't changing the width of the superview and it sounds like you might be.  But if the width constraint is set on the label then I would expect this to work in your case, too.
Answer: AutoLayout facilitate you for orientation purpose. I don think it will give you automatic expansion. You have to define label with width and height completely, otherwise you will see dots at the end of label. So you may use UITextView expanding it all over the screen. And set textView.backgroundcolot = clearColor.


Number of pairs linearly independent vectors in vector space of dimension 3

Question: Suppose V is a real vector space of dimension 3. Then what will be the number of pairs of
linearly independent vectors in V?
Cani say it should be infinity? Because there exist infinite number of basis of a vector space of dimension 3?
Answer: This depends on the ground field. If the ground field is infinite, this is in fact true and not all that hard to prove (just take two linearly independent vectors $v$ and $w$ and consider the pairs $(v,\lambda w)$ for any scalar $\lambda \neq 0$). If the ground field is finite, the vector space itself is finite as well, so your claim does not hold.
Edit: I missed that you specified it was a real vector space. In that case, the ground field is obviously infinite, and the argument above works. Thanks to Jonathan Taylor for noticing.
Answer: Since your question specifies that we are talking about a real vector space, then yes. There are an uncountably infinite number of such pairs.
Answer: There are only 3 linearly independent vectors e1,e2,e3 in real vector space V of dimension 3 . V is spanned by 3 L.I vectors. So pairs are only 3
Comment: you did not understand the question.


Host file redirect for download another file

Question: I edited my host file like this.
example.com/abc/a.zip example.com/abc/b.ziP

So what I need to do is when I enter example.com/abc/a.zip url in browser it should be redirected to example.com/abc/b.zip. But that doesn't work. So where is the fault?
And are there any other ways to do this?
Comment: /etc/hosts file doesn't do redirection. Apache VirtualHosts have a syntax for specifying redirects.
Comment: @muru Could you please tell me how to redirect using apache virtualhosts?
Answer: Remapping URL
If you want to remap url to a different location, but clients still access and know original url, you should use RewriteRule directive.
Try to add this lines in VirtualHost section:
  RewriteEngine on
  RewriteRule ^/abc/a\.zip$ /abc/b.ziP [PT]

Here is RewriteRule syntax:
  RewriteRule Pattern Substitution [flags]

where, according to apache mod_rewrite manual:
  Pattern: In VirtualHost context, The Pattern will initially be matched
       against the part of the URL after the hostname and port, and
       before the query string (e.g. "/app1/index.html").
  Substitution: A DocumentRoot-relative path to the resource to be served.
       Note that mod_rewrite tries to guess whether you have specified a
       file-system path or a URL-path by checking to see if the first
       segment of the path exists at the root of the file-system.
       For example, if you specify a Substitution string of
       /www/file.html, then this will be treated as a URL-path unless
       a directory named www exists at the root or your file-system
       (or, in the case of using rewrites in a .htaccess file, relative
       to your document root), in which case it will be treated as a
       file-system path.
       If you wish other URL-mapping directives (such as Alias) to be
       applied to the resulting URL-path, use the [PT] flag as described below.
  flag: special action

In this case flag value is PT tha means:
  passthrough|PT    Forces the resulting URI to be passed back to the URL
      mapping engine for processing of other URI-to-filename translators,
      such as Alias or Redirect. details ...

Here is useful link with examples.
There is Alias directive that remap content location too. This one is useful if content location is outside of DocumentRoot.
Redirect request
If you want to inform the client that the requested content is located at a different URL, and instruct the client to make a new request with the new URL, you should use Redirect directive.
try adding this line in VirtualHost section:
  Redirect permanent /abc/a.zip http://example.com/abc/b.ziP

This is useful to inform robot that contents are moved in other location, and prevent errors of indexing in search engines.
Answer: For simple redirects, the RewriteEngine is overkill. Just add this to your site definition:
Redirect /abc/a.zip http://example.com/abc/b.zip

See the example in the Apache documentation.


Have Angular re-scan the DOM

Question: I am inserting some new html into my Angular 2 app after a server call and I would love to have a way to "refresh" or "re-scan" so that things like (click)="myMethod()" are evaluated. All my searches for this turn up AngularJS documentation and not for the newest (version 6) of Angular.
Here is an example:
I have this tag in my html template to open a popper.

    My Content

Angular takes that and it ends up looking like this in the DOM:

My Content

So how I can inject the top one into the innerHTML of a tag and have it refresh into the bottom one?
Answer: Whenever you try to modify DOM by html, some javascript, external url, url to resource like img you need to tell angular that you actually know what you doing, therefore you need to use DomSanitizer.
Comment: I handled that with a custom pipe and bypassSecurityTrustHtml(). It still isn't assessing my inserted tags for angular bindings.
Answer: I was able to get it working like I needed using this tool:
https://www.npmjs.com/package/ng-dynamic

Have Angular re-scan the DOM


Enlarge/Shrink element on click in JQuery

Question: I'm trying to create an unordered list where each li is a little "tile" that expands and collapses (using animate() )  with a click. I've got it to where the li will enlarge, but I can't figure out how to shrink it back down again.
Here's the code:
<!DOCTYPE html>

Open
Lorem ipsum dolor sit amet

Open
Lorem ipsum dolor sit amet

Open
Lorem ipsum dolor sit amet

Open
Lorem ipsum dolor sit amet

Open
Lorem ipsum dolor sit amet

Open
Lorem ipsum dolor sit amet

Comment: Is something like Accordion implemented in jQuery UI?
Answer: Check the text to decide whether to open or close it:
$(document).ready(function() {
    $("li.closed a").click(function(){
        if($(this).text() == "Open"){
        $(this).parent()
            .animate({height:"300px"},{duration: 400, queue: false })
            .animate({width:"300px"},{duration: 400, queue: false })
            .animate({backgroundColor:"#fff"},{duration: 400, queue: false })
            .attr("class","open")
        ;
        $(this).text("Close");
        } else {
        $(this).parent()
            .animate({height:"72px"},{duration: 400, queue: false })
            .animate({width:"72px"},{duration: 400, queue: false })
            .animate({backgroundColor:"#09f"},{duration: 400, queue: false })
            .attr("class","closed")
        ;
        $(this).text("Open");
      }
    }); // closes click on "li.closed a"
}); // closes document ready function

JSFiddle
Answer: Your function can be completely optimized in this way:
$(document).ready(function () {
    $(document).on("click", "li.closed a", function () {
        $(this)
            .parent()
            .animate({
               height: "300px",
               width: "300px",
               backgroundColor: "#fff"
            })
            .attr("class", "open");
        $(this).text("Close");
    }); // closes click on "li.closed a"
    $(document).on("click", "li.open a", function () {
        $(this)
            .parent()
            .animate({
               width: "72px",
               height: "72px",
               backgroundColor: "#09f"
            })
            .attr("class", "closed");
        $(this).text("Open");
    }); // closes click on "li.closed a"
}); // closes document ready function

Note the followings:

animate() also accept an object of properties to animate
400 milliseconds is the default timing (usually identified by "normal"), so it can be omitted

You can run the code here: http://jsfiddle.net/4QmLV/
Comment: That's beautiful! I knew I had to use .on, but I had my syntax wrong. Now, I also want all the other "tiles" to close when I open a new one. How do I do that? Thanks!
Comment: Hint: Let's retrieve all li different from the current one :)
Comment: @PatrickJ.Riepe I initially had `on` as well in my answer but then i revised it since you don't have to use it at all. Just one handler is enough and you can generalize a lot of your code. Also if at all going with `on` do not bind it to the document, instead bind it to the container eg id of the ul `#tiles` that exists in DOM at any time.
Comment: Aurelio you have to give me a bit more than that...I'm totally new at this one ;-)
Comment: I know, I know, but I'm still not seeing it. I tried running the "close" code again inside the block where you open the tile, but that, of course, closed the tile you just opened. Aaack!


Integrability of a family of functions, parameterized by the points of the compact

Question: For any $\theta \in \Theta$, let $g(t;\theta)$ be integrable in $t$ over, say, the half line $\mathbb{R}_+$. Then suppose $\Theta$ is a compact set, then can we say $\sup_{\Theta}g(t;\theta)$ is also integrable?
To me, intuitively speaking it should be but I am having a bit of trouble proving why? If it is not, what are some of the conditions on $g$ such that it is?
Answer: Suppose that $\Theta = [0,1]$.
Consider $g(t,\theta) = 1$ for $t \in [n-1, n)$ where $n = [\theta^{-1}]$ and $g(t,\theta) = 0$ otherwise. Hence, for example $g(t,0)=0$ for all $t$. In this case $sup_{\theta}g(t,\theta)=1$ isn't integrable. According to this scheme, it is easy to make a counterexample with smooth functions $g$.
If $\Theta$ is infinite, then there is a subset $ \{ \theta_m \}$ which is infinite, so we may consider $g(t, \frac{1}{m})$ for $\theta = \theta_m$ and put all other $g(t,\theta) = 0$.
If $\Theta$ is finite then the statement holds true, because  $g(t, \theta_0) \le sup_{\theta}  g(t,\theta) \le \sum_{\theta} g(t,\theta)$.
One more trivial condition:
If $ \int_M^{\infty} \sup_{\theta} g(t,\theta) dt < \infty$ for some $M$ and if $g(t,\theta)$ are unformly bounded then the statement holds true.
Comment: That makes a lot of sense actually. Thanks! I suppose intuitively speaking, if we want $\sup_{\theta \in \Theta} g(t;\theta)$ to be integrable, then by the Dominated convergence theorem, if there exists an $f(t)$ such that $\sup_{\theta \in \Theta} g(t; \theta) \le f(t)$ for any $t$, (in say, $\mathbb{R}$) and $f(t)$ is integrable, then $\sup_{\theta \in \Theta} g(t; \theta)$ is also integrable (by the Dominated convergence theorem).
Comment: @JeffreyKwan In dominated convergence theorem there is convergence in case $n \to \infty$, and here we have situation that is a bit different.


PHP APC apc.shm_size cant be set above 39

Question: Hi I am having some problems with apc caching.  For some reason when I set the apc.shm_size to any value above 39 I am unable to load any php files.  There are no entries in the apache error logs.
My set up is as follows:
PHP 5.3.5
Apache 2.2.17
Loaded apache modules:
core mod_win32 mpm_winnt http_core mod_so mod_actions mod_alias mod_asis mod_auth_basic mod_authn_default mod_authn_file mod_authz_default mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_vhost_alias mod_php5
Comment: Yes i do, although the unit is not required.
Answer: This may be a library limitation of whatever APC was compiled with for its Win32 version.  While the manual doesn't mention Win32, it does note that the BSD operating systems have a fairly low limit for shared memory segment size.
Having said that, APC allows you to create multiple shared memory segments using the apc.shm_segments setting to get around shared memory segment size limits.
The default is 1 segment, 32MB in size.


Quick search to find active urls

Question: I'm trying to use cURL to find active rediractions and save results to file. I know the url is active, when it redirects at least once to specific website. So I came up with:
<code>if (( $( curl -I -L https://mywebpage.com/id=00001&somehashnumber&si=0 | grep -c "/something/" ) > 1 )) ; then echo https://mywebpage.com/id=00001&somehashnumber&si=0 | grep -o -P 'id=.{0,5}' >> id.txt; else echo 404; fi
</code>
And it works, but how to modify it to check id range from 00001 to 99999?
Answer: you'll want to wrap the whole operation in a for loop and use a formatted sequence to print the ids you'd like to test. without know too much about the task at hand i would write something like this to test the ids
$ for i in $(seq -f "%06g" 1 100000); do curl --silent "example.com/id=$i" --write-out "$i %{response_code}\n" --output /dev/null; done
Comment: Thx, i figured it out, but your solution is much cleaner.

Quick search to find active urls


Paginate results from a multi variable query mysql database

Question: I have a mysql database and use a multi variable search page, find.php, to input variables. The results come out correctly (count is correct and so is page 1 of the results) but when I try and go to the next page I get an error :: Undefined index: term1 line 60 ::Undefined index: term2 line 61 and so on.
Search2.php is as set below:
<?php

include "db.inc.php";

if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 15;

$term1 = $_POST['term1'];
$term2 = $_POST['term2'];
$term3 = $_POST['term3'];
$term4 = $_POST['term4'];

$sql ="SELECT * FROM cdrequests WHERE pname  LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%' LIMIT $start_from, 15";

$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM cdrequests WHERE pname  LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'");
$number=mysql_num_rows($query);
print "CD Requests
";
?>

pagination structure
<?php

$sql = "SELECT COUNT(id) FROM cdrequests WHERE pname  LIKE '%$term1%' AND date LIKE '%$term2%' AND date LIKE '%$term3%' AND dept LIKE '%$term4%'";
$rs_result = mysql_query($sql);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 15);

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($page > 1) {
   // show << link to go back to page 1
   echo " First ";
   // get previous page num
   $prev = $page - 1;
   // show < link to go back to 1 page
   echo " « ";
} // end if

// loop to show links to range of pages around current page
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $total_pages)) {
      // if we're on current page...
      if ($x == $page) {
         // 'highlight' it but don't make a link
         echo "  $x  ";
      // if not current page...
      } else {
         // make it a link
         echo " $x ";
      } // end else
   } // end if
} // end for

// if not on last page, show forward and last page links
if ($page != $total_pages) {
   // get next page
   $next = $page + 1;
    // echo forward link for next page
   echo " » ";
   // echo forward link for lastpage
   echo " Last ";
} // end if
/****** end build pagination links ******/

echo '
';

?>

Somehow going to page 2 fails to carry over proper info of variable term 1, term2 etc.
Any idea/help appreciated
Comment: www.petefreitag.com/item/451.cfm
Answer: Your page links do not pass term1, term2, etc. back to the server. Also if you are going to pass them in the link then you need to check $_REQUEST['term1'], $_REQUEST['term2'], etc. to cover both GET and POST requests.
The code of the links should be like this:
echo " » ";

If you have too many parameters to pass to the server then you should probably consider sending POST requests when clicking on the links using JavaScript.
Comment: makes sense, so being the noob I am, where would I insert the $_REQUEST['term1'] etc? thanks
Comment: Start with :::   $term1=$_REQUEST['term'] instead
Comment: thanks, so how do I implement this section in my code to ensure passing of the terms?  :::: "you need to check $_REQUEST['term1'], $_REQUEST['term2'], etc"
Comment: Notice: Undefined index: term1 , still getting this message, doesn't seem to work, all I did was change the link code as you suggested above, I didn't change anything else...still getting the Undefined index error.
Comment: So I need to save the session variable, session_start() , seems like the best way to do it, any tips on this?


Make SHA1 encryption on Android?

Question: Can you suggest me about how to encrypt string using SHA1 algorithm ?
I've searched about it. But no luck.
Thanks in advance.
Comment: SHA1 is not an encryption algorithm, it's a hash algorithm. Once you hash your message, it's impossible to "dehash" it. Just so you know. More info here: http://en.wikipedia.org/wiki/Hash_algorithm.
Comment: IMHO, it is not enough to simply hash the string once. Consider salting the string with a random seed and "recursively" hashing the salted string at least 1000 times. You will then need to store the random seed.
Comment: A simpler SHA-1 method: (updated from the commenter's suggestions, also using a massively more efficient byte->string algorithm)    See  this link http://stackoverflow.com/questions/5980658/how-to-sha1-hash-a-string-in-android
Answer: binnyb's convertToHex method is not working properly. A more correct one that works for me is:
private static String convertToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
        int halfbyte = (data[i] >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            if ((0 <= halfbyte) && (halfbyte <= 9)) {
                buf.append((char) ('0' + halfbyte));
            }
            else {
                buf.append((char) ('a' + (halfbyte - 10)));
            }
            halfbyte = data[i] & 0x0F;
        } while(two_halfs++ < 1);
    }
    return buf.toString();
}

public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException  {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] sha1hash = new byte[40];
    md.update(text.getBytes("iso-8859-1"), 0, text.length());
    sha1hash = md.digest();
    return convertToHex(sha1hash);
}

use the SHA1 method to get your sha1 string.
Update: providing a complete answer
Comment: You are simply awesome
Answer: here are 2 methods i have found while searching for a sha1 algorithm implementation:
private static String convertToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    int length = data.length;
    for(int i = 0; i < length; ++i) {
        int halfbyte = (data[i] >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            if((0 <= halfbyte) && (halfbyte <= 9))
                buf.append((char) ('0' + halfbyte));
            else
                buf.append((char) ('a' + (halfbyte - 10)));
            halfbyte = data[i] & 0x0F;
        }
        while(++two_halfs < 1);
    }
    return buf.toString();
}

public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException  {
    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] sha1hash = new byte[40];
    md.update(text.getBytes("iso-8859-1"), 0, text.length());
    sha1hash = md.digest();
    return convertToHex(sha1hash);
}

use the SHA1 method to get your sha1 string.  I have not confirmed that this is indeed a sha1, but it works for my apps.
Comment: The problem is this convertToHex method is skipping every other converted character in the result.  For example, the has of "Have a nice day!" should be 56cb5d30886e7715f9861220e940758abcbe5473 but is 5c538671f812e478bb57.
Comment: Also keep in mind that byte[] is a more compact format then a hex string and therefore its probably more efficient to store it as a byte[] until you need to present the data to the user, in which case the user expects hexadecimal.
Comment: A working method to convert to hex from byte[] array is posted at http://forums.xkcd.com/viewtopic.php?f=11&t=16666&p=553936
Comment: Your indentation came up looking a little inconsistent, so I made it more consistent. If you don't like it, just roll back. :)
Comment: about the indentation.. i just copy and pasted from Eclipse.  i can't seem to get it into a good format after copy/paste. Am i doing something wrong? ha
Comment: Guys' I've compared code with online encoder. But no luck: http://ratfactor.com/sha1  There is an issue encoding ?
Comment: Thank you! One line of above method should be while(two_halfs++ < 1);
This works for me.
Answer: I've answered this before (How to SHA1 hash a string in Android?) but it fits here, as well:
Android comes with Apache's Commons Codec so you can simply use the following line to create a SHA-1 hexed String:
String myHexHash = DigestUtils.shaHex(myFancyInput);

That is the old deprecated method you get with Android 4 by default. The new versions of DigestUtils bring all flavors of shaHex() methods like sha256Hex() and also overload the methods with different argument types.
Of course, there is more functionality in DigestUtils and the rest of Commons Codec. Just have a look.
http://commons.apache.org/proper/commons-codec//javadocs/api-release/org/apache/commons/codec/digest/DigestUtils.html
EDIT:
If you get a ClassNotFoundError you will have to explicitly add commons-codec as dependency (even though it should come with Android as transitive dependency), in Maven e.g.:
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.7</version>
    </dependency>

And also, you will have to change the call to:
String myHexHash = new String(Hex.encodeHex(DigestUtils.sha512(myFancyInput)));

(My humble guess is that this is probably due to a ClassLoader issue (class name collision) in the Android VM - which would actually prove that the commons-codec classes are already present...)
See also:
https://stackoverflow.com/a/9284092/621690
Answer: binnyb set me on the right track, but I found some more, easier to understand code here:
http://www.coderanch.com/t/526487/java/java/Java-Byte-Hex-String
private static String convertToHex(byte[] data) {
    StringBuilder sb = new StringBuilder(data.length * 2);

    Formatter fmt = new Formatter(sb);
    for (byte b : data) {
        fmt.format("%02x", b);
    }

    return sb.toString();
}

Make SHA1 encryption on Android?


Creating smaller size file of png file

Question: After conversion, the new file size is even bigger. ??
Why is that?
andy@7 ~/Downloads> convert Screenshot_1360x768.png -resize 1024x578! smaller.png
andy@7 ~/Downloads> ls

-rw-rw-r--  1 andy andy 135725 Sep  7 19:45 Screenshot_1360x768.png

-rw-rw-r--  1 andy andy 154448 Sep  7 20:17 smaller.png

Comment: Try `convert Screenshot_1360x768.png -resize 680x384! smaller.png` for fun.
Answer: ImageMagik's convert function will sometimes do things like this when there isn't a great deal of room for compression. If you work with a lot of PNGs, then you may be interested in optipng which offer a bit more flexibility when optimising PNG files.
Using the following command, a full-screen capture of this AskUbuntu question has the following result:
-rw-r--r--  1 jason jason 1371805  9月  8 10:35 Screenshot_20220908_103518.png

optipng -o7 Screenshot_20220908_103518.png

-rw-r--r--  1 jason jason  480525  9月  8 10:37 Screenshot_20220908_103518.png

You can adjust the optimisation level with the -o option, with values between 5 and 7 generally returning the better results. Values of 8 and 9 may result in some pixellation of photos with a wide colour range.
Comment: This doesn't explain _why_ the smaller image is bigger though (which I suspect is caused by anti-aliasing of previously sharp features).

Creating smaller size file of png file


TBindScope missing in XE6 IDE

Question: TBindScope component exist in XE4 and XE5 IDE but is missing in my XE6's tool palette.
Is this component deprecated?
Comment: It's not deprecated but it seems odd that it's no longer on the palette.
Comment: It is documented in XE3, and removed from docwiki documentation in XE4 and onwards, yet still on the palette in XE4 and XE5?
Comment: @WarrenP: TBindScope is in XE4, XE5 and XE6's docwiki.
Comment: Reported to [QC#126947](http://qc.embarcadero.com/wc/qcmain.aspx/qcmain.aspx?d=126947)
Comment: Ok found it. http://docwiki.embarcadero.com/Libraries/XE6/en/Data.Bind.Components.TBindScope
Comment: Tomohiro Takahashi replied in QC#126947 that TBindScope is no longer available for design time.  If this is the case, any workaround solution if I want to use TBindscope.
Comment: @ChauCheeYang:
1. it seems QC#126947 has not been reported on https://quality.embarcadero.com/ -> ?
2. any news on the TBindScope workaround?
3. in the RAD Studio 10.4, TBindScope declared in Data.Bind.Components.pas, but the component is not installed
Answer: No, it's not deprecated. It disappeared for some reason, until Embarcadero put it on again in RAD Studio 10.4.1.
Go there, and search TBindScope.

TBindScope missing in XE6 IDE


Netty 4 - in-vm ephemeral channels

Question: I'm looking to migrate from our current Netty 3.x to the new Netty 4.x, however I don't see an equivalent to the 3.x's (org.jboss.netty.channel.local.LocalAddress) ephemeral addresses.  There is an equivalent class in the new package structure however it looks like it is used for a different purpose, not to mention a package-private constructor.
Does anyone know how I can migrate 3.x ephemeral address to 4.x?  There doesn't seem to be anything in the migration documentation either. http://netty.io/wiki/new-and-noteworthy.html
Client connection:
<code>    int port = 10000;
    ClientBootstrap clientBootstrap = new ClientBootstrap();
    clientBootstrap.connect(new LocalAddress(port));
</code>
Server connection:
<code>    int port = 10000;
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.bind(new LocalAddress(port));
</code>
Thanks
Comment: Can you show me the code you want to "migrate" ? It should be all in the io.netty.channel.local package
Comment: Apologies, have updated the question now
Answer: Apologies.  I didn't realise that the LocalAddress constructor had changed from a LocalAddress(int) to LocalAddress(String).  So in Netty 4.x it is now
<code>int port = 10000;
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.bind(new LocalAddress(Integer.toString(port)));
</code>

Netty 4 - in-vm ephemeral channels


Kill the process if start time is less than 2 hours

Question: I need to kill the process if start time is less than 2 hours.
I have written the below cmdlet to find out the starttime but how to find out if is it less than 2 hours:
get-process process1 | select starttime

There is also a possibility that on some hosts process1 is not running. so I need to check first if the process1 is running
Comment: You can use `Where-Object` to filter for that given the date, by using the `.AddHours()` method and seeing what time is greater than that of 2 hours ago: `Get-Process -Name notepad | Where-Object -Property StartTime -GT (Get-Date).AddHours(-2) | Stop-Process -PassThru`
Answer: You can use a loop of your choice, in this example ForEach-Object in addition to an if condition to check if the StartTime value is lower than 2 hours.
If you need to check first is the process is running then you would need to get all processes and filter by the process name you're looking for. Then check if the returned value from Where-Object is $null or not.
$procName = 'myprocess'
$process = Get-Process | Where-Object Name -EQ $procName
if(-not $process) {
    Write-Warning "$procName not found!"
}
else {
    $process | ForEach-Object {
        if($_.StartTime -lt [datetime]::Now.AddHours(-2)) {
            try {
                'Attempting to stop {0}' -f $_.Name
                Stop-Process $_ -Force
                '{0} successfully stopped.' -f $_.Name
            }
            catch {
                Write-Warning $_.Exception.Message
            }
        }
    }
}

Comment: thanks! Please note that I want to kill the process only if `starttime` is less than `2 hours`.
Comment: @meallhour woops, my bad. so lower than 2 hours it is
Comment: There is also a possibility that on some hosts `process1 is not running.` so i need to `check first if the process1 is running.` I have updated my question too.
Comment: @meallhour should be covered with the last update
Comment: I need some modification to the script and created another question for it.
can you please help to answer? https://stackoverflow.com/questions/71412590


Turning water off to house for a vacation, does furnace need to go off as well?

Question: I am going away for a week, I want to shut off all water to my home. I have an oil furnace, with a separate water boiler (connected to the oil furnace - there is no gas in the house). It is summer in my area. Do I need to turn my furnace or water boiler off? What could go wrong if I leave the furnace / boiler on?
Thanks
Comment: why are you asking?  ....questions that seek an opinion are frowned upon here.
Comment: @jsotola I don't understand your confusion - I want to know if one is supposed to turn off their water boiler if turning off water to the entire house - is this such a strange thing to ask?
Comment: i thought that a water boiler for house heating is a closed loop .... anyway, something could always go wrong .... if the furnace is turned off then that is one less thing to go wrong
Comment: Hello, and welcome to Stack Exchange. It looks like "Reg" and "user3203425" are both your accounts; please pick one and use it. And, @jsotola is trying to help you, and asked for clarification, which is a helpful thing to do. You should check out our Help section to learn more about how we work.
Answer: If the water is shut, should water level drop, e.g. if an outside faucet were turned on, it's likely a water heater or boiler would be damaged.
If plumbing is sound, I'd not shut the water for just one week in summer, since it's unlikely pipes would freeze. For a long-term winter vacation, if turning off heat, you'd need to drain the plumbing, dish- and clothes-washer, flush toilets, put potable antifreeze in drains, etc.


how will you handle the exception for overridden method

Question: class Parent{

public void m1() Throws Exception{

         //m1
      }
}

class Child extends Parent{
    public void m1() {
   }
}

The above program compiles successfully. But how will we handle exception thrown by the overridden method, Since overridden method is not throwing any exception.
Comment: same as any other method that is not throwing an exception - since posted code is doing nothing, strictly speaking, there is no exception to handle - and we have no idea what this method is supposed to do and what exceptions are involved, nor we know anything about context (GUI, logging, ...).
Answer: You must read about checked and unchecked exceptions & exception handling when overriding.
Basics rules are:
1. If SuperClass does not declare an exception, then the SubClass can only declare unchecked exceptions, but not the checked exceptions.

2. If SuperClass declares an exception, then the SubClass can only declare the child exceptions of the exception declared by the SuperClass, but not any other exception.

3. If SuperClass declares an exception, then the SubClass can declare without exception.

You can refer to https://www.geeksforgeeks.org/exception-handling-with-method-overriding-in-java/ for better understanding.


Jump through blocks of lines in a file based on a conditional

Question: I have a .bedGraph file which looks like this:
chr     start   end     score
chr1    3000305 3000306 0.006
chr1    3000306 3000307 0.01
chr1    3000307 3000308 0.014
chr1    3000308 3000309 0.017
chr1    3000309 3000310 0.019
chr1    3000310 3000313 0.021
chr1    3000313 3000314 0.029
chr1    3000314 3000315 0.027
chr1    3000315 3000316 0.02
chr1    3000316 3000317 0.011

I have to write a script which will traverse through this file and look for score >0.02, grab the start value for that score, and continue searching until it reaches a score <0.02 at which point it should grab the previous end position. So in this case the program should traverse from the beginning of the file, identify the first score>0.02, grab the start position=3000310 for that score and continue searching until the score falls below 0.02 at which it should grab the previous end position=3000316. After this, it should continue searching the file for such blocks and grab the start and end positions of blocks containing score>0.02. Again, it should not grab all the starts and ends of a block containing a score>0.02 but only the first start and last end of such a block.
I have written part of the code but don't know how to proceed further:
open BEDGRAPH, $ARGV[0] or die print $!;

my $thresh=0.5;
my $j=1;
my $i=1;
my @arr = <BEDGRAPH>;
my @tmp;
for $i (0 .. $#arr)
{
my ($chr, $start, $end, $score) = split('\s',$arr[$i]);
if($score>=$thresh)
{
    push(@tmp,$chr);
    push(@tmp,$start);
    $j=$i+1;
    my ($chr1, $start1, $end1, $score1) = split('\s',$arr[$j]);
    while($score1>=$thresh)
    {
        $j=$j+1;
    }
    my ($chr2, $start2, $end2, $score2) = split('\s',$arr[$j-1]);
    push(@tmp,$end2);
    $i=$j+1;
    print @tmp;
}
elsif($score>=$thresh)
{
        $i=$i+1;
}
}

close(BEDGRAPH);

Here I am trying to push the required start & end positions in @tmp and print it.
Comment: What's the output?  If your program is just "grabbing" data, then what's the point?  Do you want to output everything you "grab"?
Comment: The output is a file with each line containing a start and end position that the program grabs each time it encounters such a block of scores>0.02.
Comment: Your description says `> 0.02` but your code says `> 0.5`. You should store that value in a variable anyway.
Comment: I have updated my code, I actually have to find it for score>0.5 but I could only paste a subset of my file here so had to change the score.
Comment: When making such a substantial edit to a question that you already marked as answered, you should really open a new question for the new, specific issue you're facing. I updated my answer for your new code.
Comment: I did make a new question, but one of the users marked it as duplicated, and he asked me to edit this question. When I told him that I am making a different change and that this question has already been answered, he told me you should mark it as "unanswered" so that people get your question in the new questions' list.
Comment: The new question you asked was not a duplicate, but it was hard to tell because large parts were word-for-word identical. Just because one user thinks your post is a dupe does not mean the community will agree. See [this post](http://meta.stackexchange.com/questions/96560/significantly-edit-existing-question-or-ask-a-new-question-after-answer-accepte) on meta.
Answer: Some suggestions to get you started.
First, why loop through your file twice? You do it once when you read it into an array and again when you process the array. Why not just do the processing as your read the file line by line?
# Use a lexical filehandle and test `open` for failure
my $file = $ARGV[0];
open my $fh, "<", $file or die "Failed to open file '$file': $!";

while (<$fh>) {
    my ($chr, $start, $end, $score) = split;
...

Note that instead of referring to the columns with array indexes, I'm using meaningful variable names.
Also, avoid magic numbers like the plague and put your threshold in a variable. This way if it does change from 0.02 to 0.5, you only have to update it in one place in your code. Variable names also tend to be more meaningful than magic numbers to the people reading your code.
my $threshold = 0.02;

There are a few pieces of information you need to keep track of as you read through your file.

Are you inside a block (i.e. a section where the scores are greater than your threshold)?
If you are inside a block, what is the value of start at the beginning of the block?
If you are inside a block, What is the value of end from the previous line? You need this because you don't find out you've left a block until the following line.

If you think about how you can get these pieces of information, you should be able to figure out the rest.

EDIT: You completely changed your code with your latest edit. This should really be a new question.
Immediate issues with your updated code:
open BEDGRAPH, $ARGV[0] or die print $!;

Use lexical filehandles (open my $fh) instead of typeglobs (open FILE), which are global in scope.
my @arr = <BEDGRAPH>;

You mentioned in the comments that you're working with really large files, and yet you're reading them into memory with @array = <$fh>. You should really use while (<$fh>) ...
while($score1>=$thresh)
{
    $j=$j+1;
}

And finally, you never change the values of $score or $thresh in the body of your loop, so it runs forever.
Comment: You could drop the delimiter from `split` with the same result (it'll use the default `" "` as in the question).
Comment: Thanks for the suggestion, I have been already trying to think of a way to enter the block and do something like **next until** it reaches a score below the threshold. But I am still stuck. Thanks for the input though.
Comment: @user2703967 Did you try `next if $score <= $threshold`? You would of course only want to run that test if you were already inside a block.
Comment: @ThisSuitIsBlackNot I have figured out this problem in R, I will try to implement the same in Perl too. Thanks!
Comment: @ThisSuitIsBlackNot Is there a way to loop through a file in perl using a for loop where a variable i iterates and reads the next line?
Comment: @user2703967 When you use a `for` loop, the entire list you're iterating through is in memory. To do this with a file requires reading the entire file into memory, which can be done with `my @array = <$fh>;`. This is fine if your file is small, but can eat up a significant chunk of RAM with large files. However, nothing says you can't use a counter with a `while` loop: `my $line = 1; while (<$fh>) { do something; $line++; }`
Comment: @ThisSuitIsBlackNot Thanks, I have added my implementation in R above. So based on this logic, I will have to have a i and j variable to traverse through parts of my file. I will try what you have suggested. I am hesitant to use R because my files are really large, and I think perl will handle it better.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38195/discussion-between-user2703967-and-thissuitisblacknot)
Comment: @ThisSuitIsBlackNot I don't understand. How will I loop through the file if I use while(<$fh>) instead of for $i...; Also, what is the change with while($score1>=$thresh){}? I have the same thing in my code.
Comment: Am I not changing the value of $score each time it reads the next line in the for loop -> my ($chr, $start, $end, $score) = split('\s',$arr[$i]);
Comment: @user2703967 When `$score` is greater than `$thresh` and you enter the `while` loop, what happens? Say `$score` is 0.021 and `$j` is some number. In the first iteration, you increment `$j` by one. `$score` is still 0.021, so you go through the loop again. Increment `$j` again. `$score` is *still* 0.021, so go through the loop again. And so on, forever.
Comment: But it is not even going past the if statement! After the if statement and before the while loop, if I try to print something, it doesn't happen.
Comment: @user2703967 You need to do some basic troubleshooting here. If you're not entering the `if` statement, check the value of `$score` you get from your first `split` and make sure it is really greater than your threshold.
Comment: Which I did. I printed the $score before the if statement, infact I printed the entire line before the if statement, I tried to print the $score & $thresh inside the if statement and even print $i and $j. I have tried printing every variable in every loop, before and after. Thanks.
Answer: I think you need to make changes to your program as noted by ThisSuitisBlackNot. I thought I'd post a possible solution.
Update: If the chr name can change, this program may not work and need to be adjusted.
#!/usr/bin/perl
use strict;
use warnings;

my ($prev_chr, $prev_start, $prev_end);
my $thresh = .02;

while (<DATA>) {
    my ($chr, $start, $end, $score) = split;

    if ($score >= $thresh) {
        $prev_chr   //= $chr;
        $prev_start //= $start;
        $prev_end = $end;
    }
    else {
        if ($prev_chr) {
            print "$prev_chr $prev_start $prev_end\n";
            ($prev_chr, $prev_start, $prev_end) = (undef) x 3;
        }
    }
}
print "$prev_chr $prev_start $prev_end\n" if $prev_chr;

__DATA__
chr1    3000305 3000306 0.006
chr1    3000306 3000307 0.01
chr1    3000307 3000308 0.014
chr1    3000308 3000309 0.017
chr1    3000309 3000310 0.019
chr1    3000310 3000313 0.021
chr1    3000313 3000314 0.029
chr1    3000314 3000315 0.027
chr1    3000315 3000316 0.02
chr1    3000316 3000317 0.011

Comment: I am clueless about what are you trying to do here
Comment: @user2703967 Output is `chr1 3000310 3000316`, which is the result you said you wanted. The statement, for example, `$prev_chr   //= $chr;` is equivalent to `$prev_chr = $chr unless defined $prev_chr;`.
Comment: Pardon me, I am not that good at Perl. You can see how much difference there is between your code & mine. I will try to understand what this code does and implement into mine, although I would be honest to say that have never seen terms like (undef)*3 and so on. Thanks.
Comment: `($prev_chr, $prev_start, $prev_end) = (undef) x 3;' sets the three variables to `undef'. The `(undef) x 3` creates a list of three values == undef and assigns them to the 3 variables on the left side. They remain undefined until the score is >= to the threshold and then assigns to them (if their previous value is undefined).
Comment: I made 1 edit to the program, undefining the previous values after printing out the desired record.
Answer: #!/usr/bin/perl
use warnings;
use strict;

open my $fh, '<', 'bedgraph.txt' or die "cant open bedgraph.txt $!";

my $thresh = 0.02;

my @start_pos;
my @end_pos;
my $previous_end;

my $header = <$fh>;

ABOVE:
while (<$fh>){
    my ($chr, $start, $end, $score) = split;
    if ($score > $thresh){
        push @start_pos, $start;
        $previous_end = $end;
        BELOW:
        while (<$fh>){
            my ($chr, $start, $end, $score) = split;
            if ($score < $thresh){
                push @end_pos, $previous;
                next ABOVE;
            }
            $previous = $end;
        }
    }
}

close $fh;

print "Start positions found: @start_pos\n";
print "End positions found: @end_pos\n";

#Start positions found: 3000310
#End positions found: 3000316

Brief Explanation:

ABOVE loop: scan file looking for a score greater than treshold. When/if a value is found it stores the value from the start column of the current line in the array @start_pos . and then it passes control to the loop indentified by BELOW. let's say the value was found on line number six.
BELOW loop: start scanning file at line number seven looking for values below the threshold. When/if a value is found it store the value from the end column of the previous line in the array @end_pos . and then it passes control to the loop indentified by ABOVE. let's say the value was found on line number ten.
ABOVE loop: start scanning the file at line eleven and the proccess repeat itself until  every line of the file has been read.
Answer: Consider the following:
use strict;
use warnings;

my $startFound = 0;
my $priorEnd;

while (<>) {
    $. > 1 or next;    # Get past the header
    my ( undef, $start, $end, $score ) = split;

    if ( $score > .02 and !$startFound ) {
        $startFound = 1;
        print "Start: $start\n";
    }

    if ( $score < .02 and $startFound ) {
        $startFound = 0;
        print "End  : $priorEnd\n";
    }

    $priorEnd = $end;
}

Usage: perl script.pl inFile [>outFile]
The last, optional parameter directs output to a file.
This script sets a flag ($startFound) to signal the beginning of a block, and then checks for a score below .02 and that flag to find that block's end.  The var $priorEnd just holds that last 'end' value, for the start/end pair.
Hope this helps!


GPU short circuit when multiply by 0?

Question: So I am trying to make my shader efficient by lowing the amount of texture lookups. If I had a line of code with something like.
step(1.0, x) * texture2D(pic1, uv);

Where x is a value that ranges from 0 to 2 based on the fragment position.  Would the GPU see when step evaluates to 0 and thus not ever calculate texture2D? Or would it still lookup the texture because the 0 is not constant?
BTW I use the term "short circuit" because I have been told that is what happens when you have false && (bla) the computer sees the false and ignores the right.
Answer: There is a difference between being able to determine value at compilation time and at runtime.
false && bla
Gets eliminated because of C/C++ lazy operand evaluation rule which is standardized with left to right order.
The compiler generates no code so the machine has no overhead.
step(1.0, x) * texture2D(pic1, uv);
That will depend if x is coming from a uniform value, in which case the drivers will compile an adjustment of the shader (and put it in a combinator cache). At some point before starting to render.
(this can cause hiccups in framerate when new uniform values are encountered that cause massive shader rebuild)
Now, if x is dependant, which means it comes from a previous calculation that comes from varying values or system values, the compiler will cut your expression in 2 parts, the lerp calculus and the sample call.
It will move the sampling of the texture in the first instructions of the shader. (provided it's unconditional in the shader flow).
So you're basically screwed when it's 0, you'll pay the sampling anyway.
In your case (0-2 wrt frag pos), I would recommend using if (inrect(0,0,1,1)) because this is a low frequency "step" function, which means very good branch elimination in 3 quarters of the screen.

GPU short circuit when multiply by 0?


Moving threads across CPUs with clock_gettime(CLOCK_MONOTONIC)

Question: I've heard people complain that the WinAPI functions QueryPerformanceFrequency() and QueryPerforamnceCounter() can behave erratically and unstably when the OS decides to move the calling thread to a new physical CPU.
Does anybody know if clock_gettime(CLOCK_MONOTONIC) suffers from similar issues? Or is it more guaranteed to be stable?
Also, are the worries about QPF/QPC on WinAPI just a thing of the past? Or are they still concerns even today?
Answer: OP:

I've heard people complain that the WinAPI functions QueryPerformanceFrequency() and QueryPerforamnceCounter() can behave erratically and unstably when the OS decides to move the calling thread to a new physical CPU.

I'm not sure what you mean by "erratic" or "unstable."  If you mean drift, or variance between cores, these concerns are probably based on computers that shipped 12-15 years ago (XP and Win2000-based OS).  From Microsoft:

QPC is available on Windows XP and Windows 2000 and works well on most systems. However, some hardware systems' BIOS didn't indicate the hardware CPU characteristics correctly (a non-invariant TSC), and some multi-core or multi-processor systems used processors with TSCs that couldn't be synchronized across cores. Systems with flawed firmware that run these versions of Windows might not provide the same QPC reading on different cores if they used the TSC as the basis for QPC.

That has pretty much become a non-issue for most current hardware (see link, below).
OP:

Does anybody know if clock_gettime(CLOCK_MONOTONIC) suffers from similar issues? Or is it more guaranteed to be stable?

Well, any high-frequency clock has to come from somewhere.   On a Windows box (since you asked about QPC), where is that value going to come from?  Adding an additional layer to any call to QueryPerformanceCounter essentially guarantees less precision, as there will be more CPU instructions in the mix between "now" and "now as reported back to you by the OS" (and, although extremely unlikely, there would be a small increase in the possibility of preemption, contributing further loss of precision).
This applies equally to any Intel-based Linux/BSD/whatever boxes, as they have to run with the same hardware characteristics.  In the Intel-architecture world, the highest frequency you'll be able to get is going to be a value based on RDTSC and the operating system's best effort to keep any TSC values as close as possible across cores or processors (at least in the absence of specialized hardware).
This is why any benchmarking should be an average performance expectation based on a large number of data points.
Microsoft actually has a pretty good document outlining the implementation characteristics of high-frequency timers, including HPET and ACPI power management times, and touches briefly on multi-clock and virtualization: http://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx.
OP:

Also, are the worries about QPF/QPC on WinAPI just a thing of the past? Or are they still concerns even today?

For most of the world, yes.  I work on server-based code where microseconds count (high frequency market data), but most people who think a few hundred microseconds are going to make or break their program are kidding themselves.  Do you know how long it takes to serve a web page?  The CPU itself gets bored with all that waiting, even with thousands of users.


Cannot get ruby optparse to output opts

Question: I'm trying to learn how to use optparse to take in command line options however I am having a hard time getting it to function as it shows in the class documentation and any examples I can find online. Specifically when I pass the -h option nothing is coming up. I can output ARGV and its showing that it receives -h but it wont display opts.banner and or any of the opts. What am I missing here?
class TestThing

def self.parse(args)
    options = {}
        options[:time]        = 0
        options[:operation]   = :add
        options[:input_file]  = ARGV[-2]
        options[:output_file] = ARGV[-1]
            optparse = OptionParser.new do |opts|
                opts.banner = "Usage:[OPTIONS] input_file output_file"

                opts.separator = ""
                opts.separator = "Specific Options:"

                opts.on('-o', '--operation [OPERATION]', "Add or Subtract time, use 'add' or 'sub'") do |operation|
                    optopns[:operation] = operation.to_sym
                end

                opts.on('-t', '--time [TIME]', "Time to be shifted, in milliseconds") do |time|
                    options[:time] = time
                end

                opts.on_tail("-h", "--help", "Display help screen") do
                    puts opts
                    exit
                end

                opt_parser.parse!(args)
                options
            end
end
end

Answer: You need to hold onto the results of OptionParser.new and then call parse! on it:
op = OptionParser.new do
  # what you have now
end

op.parse!

Note that you'll need to do this outside the block you give to new, like so:
class TestThing

def self.parse(args)
    options = {}
        options[:time]        = 0
        options[:operation]   = :add
        options[:input_file]  = ARGV[-2]
        options[:output_file] = ARGV[-1]
            optparse = OptionParser.new do |opts|
                opts.banner = "Usage:[OPTIONS] input_file output_file"
                # all the rest of your app
            end
            optparse.parse!(args)
end
end

(I left your indentation in to make it clearer what I mean, but on a side note, you'll find the code easier to work with if you indent consistently).
Also, you don't need to add -h and --help - OptionParser provides those for you automatically and does exactly what you've implemented them to do.
Comment: Ive already got that in line 8 and the 5th line from the bottom, did I implement this incorrectly?
Comment: You need to call it outside the block you gave to new - updated my answer to show what I mean (hopefully)

Cannot get ruby optparse to output opts


A better way to properly implement string 'in' array

Question: suppose you have an array with a number of strings in ActionScript3 and you want to test if a test string is "in" that array. "in" only works against the index with Arrays in AS3 (which is totally retardo if you ask me), though it does work with ojects, but we're not talking about objects.
Can someone improve (reduce) on this code I'm using now? I'm hoping to avoid defining a utility function - I'd like a nice elegant one-liner.
myArray.filter(function(item:*, i:int, a:Array) { return (item == testString); }).length

Since 0 == false we can use it in a test. Do note that testString's scope is defined in the containing function, encapsulated by the closure.
if (allowedProfiles.filter(function(item:*, i:int, a:Array) { return (item == name); }).length){ // yay! }

Comment: You have 500 rep and don't know how to properly format code in a question. Think about it for a moment.
Comment: @Tomalak. Point taken. I was rushed.
Answer: Use the Array.indexOf() method to see that the index of the string in the array is not -1 (not found):
var myArray:Array = ["hello", "world"];
trace(myArray.indexOf("hello")); // == 0;
trace(myArray.indexOf("goodbye")); // == -1

Answer: Why not just use indexOf()?
if(myArray.indexOf("testString") != -1) { // it's in there


WCF Service: Call first function, return from it, then call second function to work in background

Question: I am writing a WCF Service in which I have to call two functions to update the database but I want to return after first table update so that client should not wait longer and then second table will update in background.
The thing I want to do is like this:
public bool myMainFunction(){

    bool result = updateTable1();

    return result;

    updateTable2();

}

How can I achieve this?
Thanks
Answer: Try this
using System.Threading.Tasks;

public bool MyMainFunction()
{
    bool result = UpdateTable1();

    Task.Run(() => UpdateTable2());

    return result;
}

Task.Run(Action action)
From : https://msdn.microsoft.com/en-us/library/hh195051(v=vs.110).aspx

Queues the specified work to run on the thread pool and returns a Task object that represents that work.

Basically, Task.Run queues your item on the threadpool - which allows it to run asynchronously. Usually you would pair this with the task's Wait or Result methods to block the calling thread until the task has finished - for example :
using System.Threading.Tasks;

public bool MyMainFunction()
{
    Task<bool> task = Task.Run(() => UpdateTable1());

    Task.Run(() => UpdateTable2());

    return task.Result;
}

In the previous example - both methods are now queued on the Threadpool - which means they can executed in parallel. (In the first example - UpdateTable1 had to finish before UpdateTable2 began - but we fired and forgot about UpdateTable2 - so it was inconsequential). The new example now allows UpdateTable2 to begin executing before UpdateTable1 has finished. However - we would now have a problem - as we need to wait for the result of UpdateTable1 to return the bool value required.
When you call either, task.Wait() or task.Result, your method basically pauses until the task has finished - in this case, it waits until table1 has updated.
Now - you'll notice we don't have a variable to store the state of UpdateTable2's tasks - this is because you don't care about the result. Since there is no variable stored we don't ever block the calling thread to view the result - which means that you've effectively got a "Fire and Forget" method.
Hopefully this helps clear it up a bit - but if not there are plenty of resources out there to help, look into Asynchronous and Parallel programming as there will be people out there who can explain more clearly than I.
The following has been useful to me :
mcsd-certification-toolkit-exam-70-483
I have also converted your method names from Camel Case to Pascal Case, as this is standard practice.
Comment: Thanks a lot. Hats off to you!


Get rid of XML root node in XSL template output

Question: I am using XSL templates to serve as web page templates for a web framework, the end output being XHTML 1.0 Strict; it takes XML input and outputs the XHTML. It works perfectly except for one problem - the end output is also outputting a XML node instead of just the contents. Here is the basic XML (missing some items, but the overall design is the same):
<Page>
    <PageScript>

    </PageScript>
    <PageCSS>
        <CSS>./css/mycss.css</CSS>
    </PageCSS>
    <PageContent>Blah blah blah</PageContent>
</Page>

Here is the XSL Template
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:response="http://www.ntforl.com/"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:xhtml="http://www.w3.org/1999/xhtml"
    xmlns:lang="en">

    <xsl:output
        method="xml"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
        doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN"
    />

    <xsl:template match="//PageCSS">
        <xsl:for-each select="CSS">
            <link type="text/css" rel="stylesheet">
                <xsl:attribute name="href">
                    <xsl:value-of select="." />
                </xsl:attribute>
            </link>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="//PageScript">
        <xsl:for-each select="Script">

        </xsl:for-each>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/" disable-output-escaping="yes">

                <title>
                    <xsl:value-of select="//PageTitle" />
                </title>
                <meta http-equiv="content-type" content="text/html;charset=utf-8" />
                <link type="text/css" rel="stylesheet" href="template/style/globalStyle.css" />
                <link type="text/css" rel="stylesheet" href="template/style/standards.css" />
                <xsl:apply-templates select="//PageCSS" />

                <xsl:apply-templates select="//PageScript" />

                                <xsl:value-of select="//PageTitle" />

                                <xsl:apply-templates select="//PageContent" />

    </xsl:template>
</xsl:stylesheet>

The problem resides in the PageContent, and it only happens with the PageContent. When the transformation is run, the template outputs
<PageContent xmlns=""> node content </PageContent>

in the XHTML. I need to know how to get rid of it so I can have a valid XHTML 1.0 Strict document.
The weird thing is that the PageContent node is the only node to do this, no other node gets it content wrapped with the node name in the output. What is the reason for this behaviour?
Answer: You call apply-templates on the PageContent node:
<xsl:apply-templates select="//PageContent" />

The only template that matches this is this one, so the PageContent node gets copied:
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

Probably you should add another template that matches PageContent and just processes the child nodes, without copying PageContent itself:
<xsl:template match="//PageContent">
  <xsl:apply-templates/>
</xsl:template>

Comment: Thank you all, these are very helpful. I have one other question though. These get rid of the parent node problem, but the first node inside of the PageContent gets a `xlmns=""` attribute, and I was curious if that could be left of in any way.

If this helps, the PageContent node holds xhtml - it is basically the main part of the page in xhtml - the result of running whatever process the user requested.
Answer: I would try replacing <xsl:apply-templates select="//PageContent" /> with:
<xsl:apply-templates select="//PageContent/node()" />

Answer: As already pointed out by  @sth and @molf, you get the node copied by your identity template (<xsl:template match="@*|node()">), because no other template in your stylesheet matches <PageContent> nodes.
As an alternative to the solutions already presented by the other two, you could change the identity template to:
<xsl:template match="@*|node()[not(self::PageContent)]">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()" />
  </xsl:copy>
</xsl:template>

When <PageContent> is encountered now, the identity template does not match anymore. The implicit default template for elements will be used instead, which is:
<xsl:template match="*">
  <xsl:apply-templates />
</xsl:template>

This means that templates are going to be applied to <PageContent>'s children automagically, and the node itself is not going to be copied - just what you want.


Define API routes in ZF3 having more than one parameters

Question: I wanna create an API route in zend framework 3 that has two parameters. I have defined my routes as follows:
<code>'api' => [
    'child_routes' => [
    /* api/users/<id> */
    'users' => [
        'type'    => Segment::class,
        'options' => [
            'route'       => '/users[/[:id]]',
            'constraints' => [
                'id' => '[0-9]+',
            ],
            'defaults' => [
                'controller' => Api\Controller\UserController::class,
            ],
        ],
        'may_terminate' => true,
        'child_routes' => [
            /* api/users/<uid>/documents/<id> */
            'documents' => [
                'type'    => Segment::class,
                'options' => [
                    'route'       => '/documents[/:id]',
                    'constraints' => [
                        'id'   => '[0-9]+',
                    ],
                    'defaults' => [
                        'controller' => Api\Controller\DocumentController::class,
                    ],
                ],
            ],
        ]
    ]
]
</code>
The routes I expects to be supported are:
<code>api/users
api/users/<user_id>
api/users/<user_id>/documents
api/users/<user_id>/documents/<document_id>
</code>
Following above rules, when I send an HTTP Get to api/users//documents, it refers to method "get" in "DocumentsController.php", while it is expected to call method "getList".
The question is how should I change my routes, and is my resource definition follows API design principals?
Comment: I would agree with your general expected route setup. I don't with the optional parameter before required parameters though. `api/users//documents` works as intended because the user id parameter is optional. I would suggest you create a required child route `/:id` for the single user. Give that the child construction for documents. Mind: you can always have more than one route go to the same endpoint, so you could do: `/api/users/id/documents` but also: `api/documents` and have both use `DocumentController::class->index` function (and then handle (not) having an id in the function)
Answer: You should also add action name, you can add your action name along with controllers.
So, controlls will be goto to "getList" for "api/users/documents" and "index" "api/users"
As in below updated code:
<code>'api' => [
    'child_routes' => [
    /* api/users/<id> */
    'users' => [
        'type'    => Segment::class,
        'options' => [
            'route'       => '/users[/:id]',
            'constraints' => [
                'id' => '[0-9]+',
            ],
            'defaults' => [
                'controller' => Api\Controller\UserController::class,
                 'action'    => 'index',
            ],
        ],
        'may_terminate' => true,
        'child_routes' => [
            /* api/users/<uid>/documents/<id> */
            'documents' => [
                'type'    => Segment::class,
                'options' => [
                    'route'       => '/documents[/:id]',
                    'constraints' => [
                        'id'   => '[0-9]+',
                    ],
                    'defaults' => [
                        'controller' => Api\Controller\DocumentController::class,
                        'action'    => 'getList',
                    ],
                ],
            ],
        ]
    ]
]
</code>