System.Math.Round call works in one class, but is ambigous in the other

Question: Is this some bug in VS2022 or I'm missed something?
There is no problem with RoundPoint method this code:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Shapes;

namespace Editor.View.Controls
{
    public partial class Workspace : UserControl
    {
        public Workspace() => InitializeComponent();

        // ... some other methods

        public Point RoundPoint(Point p, int r)
        {
             return new Point(Math.Round(p.X / r) * r, Math.Round(p.Y / r) * r);
        }
    }
}

But when I move RoundPoint method to the other class (which is static or not, it doesn't matter):
using System;
using System.Drawing;

namespace Editor.View.Controls
{
    public static class UiHelpers
    {
        public static Point RoundPoint(Point p, int r)
        {
            return new Point(Math.Round(p.X / r) * r, Math.Round(p.Y / r) * r);
        }
    }

    // ...
}

It throws this error:

Error CS0121  The call is ambiguous between the following methods or properties:
'Math.Round(decimal)' and
'Math.Round(double)'  Editor\View\Controls\UiHelpers.cs
Comment: @Charlieface Yes, I just realized that. Thank you for pointing out how they differ, if you add that as answer I will accept it.
Comment: Which `Point` do you actually want? `System.Windows.Point` or `System.Drawing.Point` or `System.Drawing.PointF`?
Comment: I'm working with `System.Windows.Point`.
Answer: Your second code file has a using System.Drawing, which means that Point refers to System.Drawing.Point. This uses int not double, so it doesn't make sense to round it (don't forget there is integer division, which means the result of the division is still an int).
Either cast one side of the division to double or decimal, or use System.Drawing.PointF.
Or perhaps you are just using the wrong library altogether, as noted in @Kamil's answer.
Answer: I'm answering my own question.
So I just realized that I was using two diffrent Point structs in .NET.
One is here:
System.Windows.Point

and the other is
System.Drawing.Point

Comment: That doesn't help by itself. The difference is the first uses `double` the latter `int`
Comment: But in dotnet core, there is only a Point in `System.Drawing`
Comment: @Luuk Not sure what you mean https://dotnetfiddle.net/M3DhIu. It is a separate library now, not part of the standard framework, but all the types are still there
Comment: @Charlieface: I was talking about this: https://dotnetfiddle.net/johSIt
Comment: @Luuk That's WPF (`System.Windows`), not Winforms and GDI (`System.Drawing`). The point is that they are two different libraries, that's exactly what this answer is trying to say.
Comment: "trying to say" there is where I went wrong (or my knowledge about ".NET Framework" vs. ".NET Core" is failing)


How to apply C# equivalent rounding method in Javascript

Question: I am implementing an Hybrid mobile application in which I have to represent our Desktop application written in C#.
When rounding off a value, the value differs between Desktop and Mobile application.
Example
Code used in C#:
Math.Round (7060.625, 2); // prints 7060.62
Math.Round (7060.624, 2); // prints 7060.62
Math.Round (7060.626, 2); // prints 7060.63

Code used in JS:
+(7060.625).toFixed(2); // prints 7060.63 (value differs)
+(7060.624).toFixed(2); // prints 7060.62
+(7060.626).toFixed(2); // prints 7060.63

How can I change the JS code to represent the value as in C#.
Note:
We can make C# to represent the value as in JS, using Math.Round (7060.625, 2, MidpointRounding.AwayFromZero);
But I have no option to change in there.
EDIT 1
Rounding off decimals is not fixed. It is chosen by user in mobile application.
Comment: I don't think the linked question is the same. Sure, its about rounding, but this question isn't just about general rounding. Its trying to get it to round down a decimal that ends in 5 but still round up for 6-9. (duplicate has been removed)
Comment: @DanteTheSmith it's not that simple as up vs down. C# by default rounds toward the even, so 1.5 rounds to 2 and 2.5 also rounds to 2.  C# has two rounding modes.. toward even and away from zero. Java by contrast has seven or eight, depending on what you count as an actual rounding mode. https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html
Comment: Difference is that in case of 5 JS rounds UP and C# down. Isn't the round up in case of 5 desired. Math suggests so. https://math.stackexchange.com/questions/218299/how-to-round-0-45-is-it-0-or-1
Comment: @Igor not the same issue.. that question you referenced as a duplicate is about dealing with floating point issues and the question here is about an alternate rounding algorithm that JS doesn't support natively.
Comment: @SamuelNeff oh god I didn't realize rounding had so many confusing options! Rounding towards even, towards 0, positive infinity, down, up, etc, too much for me!
Comment: To my knowledge Javascript has no such built-in function
Comment: @BlakeThingstad - the **2nd** answer does touch on that (search on text "toFixed() also will NOT round correctly in some cases")
Comment: https://stackoverflow.com/a/35827227/4735052 maybe this will help.
Comment: @SamuelNeff - fair enough. Wouldn't the question you reference in your answer serve as a good alternate duplicate though?
Comment: @Igor In the referenced question, the person asking the question knew exactly what they were asking for, knew the term, and got an answer. In this question the OP wants something equivalent to C#. Just marking it as a duplicate would not necessarily be clear to them or anyone else that comes across it that the "duplicate" really is a duplicate. The one sentence I added clearly stating this makes it worthwhile.
Answer: You need a custom implementation of rounding to implement "banker's rounding" or to-even rounding.
From:
Gaussian/banker's rounding in JavaScript
function evenRound(num, decimalPlaces) {
    var d = decimalPlaces || 0;
    var m = Math.pow(10, d);
    var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
    var i = Math.floor(n), f = n - i;
    var e = 1e-8; // Allow for rounding errors in f
    var r = (f > 0.5 - e && f < 0.5 + e) ?
                ((i % 2 == 0) ? i : i + 1) : Math.round(n);
    return d ? r / m : r;
}

console.log( evenRound(1.5) ); // 2
console.log( evenRound(2.5) ); // 2
console.log( evenRound(1.535, 2) ); // 1.54
console.log( evenRound(1.525, 2) ); // 1.52

Comment: Glad it helped. Be sure ot also click on the link and give Tim Down a +1 since I copied the code from his original answer on a similar issue.
Comment: perfect solution
Answer: If you control both client side and server side you can follow this super simple pattern, it works fine for edge cases and regular case:
Let's look at 2.155, 2.145 (Midpoint issue) and 2.166, 2.146 (Regular).
C#:
public static decimal RoundFromJavaScript(this Decimal value)
{
    return Decimal.Round(value, 2, MidpointRounding.AwayFromZero);
}

//-Midpoint Issue
RoundFromJavaScript(2.155); --> 2.16
RoundFromJavaScript(2.145); --> 2.15
//-Regular
RoundFromJavaScript(2.166); --> 2.17
RoundFromJavaScript(2.146); --> 2.15

*I've omitted the m decimal sign, it should be 2.155m
JavaScript:
function roundToTwo(num) {
    return +(Math.round(num + "e+2") + "e-2");
}

//-Midpoint Issue
roundToTwo(2.155) --> 2.16
roundToTwo(2.145) --> 2.15

//-Regular
roundToTwo(2.166) --> 2.17
roundToTwo(2.146) --> 2.15

Comment: Will give it a try sometimes later and let you know of the result. Appreciate your effort. :)
Comment: @NaveenKumarV I'm surprised that this issue does not invite a lot more traffic...
Comment: This doesn't work. `Console.WriteLine(Math.Round(53.445, 2));` => 53.44, where as `roundToTwo(53.445)` -> 53.45
Comment: Hey @Langdon, not sure why the down-vote? the answer is about `Decimal.Round(53.445, 2, MidpointRounding.AwayFromZero)` -> 53.45 not `Console.WriteLine(Math.Round(53.445, 2));` -> 53.44
Comment: Your answer doesn't answer the original question which was how to round like C# does by default (`ToEven`).  The OP suggested Javascript's `toFixed` already behaves like C#'s `AwayFromZero`.  I can't change my vote unless the answer is edited anyway.
Comment: The OP only use the `Math.Round(...)` as an example, and I suggested him a different working solution (his question was not about the `Math.Round`).


How to bring facebook connect button in login form?

Question: For one of my projects I installed the Facebook O Auth module in my site. Now I would like to display the Connect with facebook in my login form.
Comment: It will be god if you use gigya module.
Answer: You have to alter both form using hook_form_alter and add a markup field with value fboauth_action_display('connect')
$form[fb_connect] = array(
   '#markup' => fboauth_action_display('connect'),
);


Probability of pipetting X number of cells in a solution

Question: I had a biology friend ask me this question:
Suppose I had 50 ml of solution in which exactly five red blood cells that are individually suspended (i.e., not sticking to each other).
If I collect 2 ml of that solution, what is:
A) The probability of that 2 ml having no cells
B) The probability of that 2 ml having 1 or more cells
C) The probability of that 2 ml having exactly 1 or exactly 3 cells
C) was added by me.  The biologist doesn't actually care about C :)
I assume the answer to P(B) is 1 - P(A), or P(A) = 1 - P(B) if you prefer.  I suspect P(C) is somewhat harder.
Here is what I've tried so far.  In response to the comments, let me be clear that I'm not claiming the ideas below are correct.  I wanted to show that I have put some effort into this.  I'm looking for comments, references, etc. that will lead me to a correct answer.  Also, I am assumming that the cells are independently distributed and do not interact.  My biology friend was unclear on these points.  If these assumptions are not correct, I imagine the problem is considerably more difficult and I will post another question.  I'm hoping this these assumptions are a good starting point.  Finally, let me be crystal clear that 2 ml of the solution is collected at once!  The idea of breaking it up into a 1 ml draw followed by another 1 ml draw was my own idea to help me think about the problem.   It may not be necessary or desirable.  As an aside, if the cells are uniformly distributed and do not interact, I fail to see how it makes any difference if 2 ml is taken at once or 1 ml is taken followed by another 1 ml. I would like to be enlightened!
I reasoned that this is somewhat similar to a card problem without replacement.  See for example:
Probability of getting 4 Aces
I reasoned that the concentration of cells is 1 per 10 ml or .1 cell per 1 ml.  The probability of not drawing any cells in 1 ml is .9 or 90% if you prefer.  On the second draw, you only have 49 ml and I think the correct probability for the second draw would be 5/49 ml or .102 for picking 1 or more cells.  The inverse of this is .898.  Multiply these gives .808 of not picking any cells in 2 ml.
Am I on the right track?  Something feels wrong.  I'm not sure I've taken into account that 1 ml of solution could have 0 cells, 1 cell, .... 5 cells.  I also don't know if my experience with discrete playing cards (and coins) is applicable here.  That is, can I arbitrarily break up 50 milliliters into 1 milliliter "compartments"?
Any hints or references would be much appreciated.  A name for this type of probability (so I can find more examples!) would also be appreciated.
Finally, my other concern with this whole problem is my initial assumption of ".1 cell per 1ml".  I mean I assume that either a cell is in the milliliter or it's not.  Not 1/10 of it is there!  But perhaps that's a question for my biology friend.
Comment: You might need to edit the question; do you draw 2ml or 5ml? Are you drawing all at once, or not? If you draw each 1ml at a time, then a hypergeometric distribution will be useful in determining the probability of containing 0,1,2, ..., 5 particles in the _total_ amount drawn.
Comment: "If I collect 2 ml of that solution, what is: A) The probability of that 5 ml ..." --- fix this
Comment: Glen_b and stephematician,  I've edited the question given my rudimentary knowledge of statistics/probability.  Thank you for the comments.  If there is a more appropriate site (beginning probability?), please let me know.  Thanks.
Answer: There are a few things that we're going to have to assume, even though you never posed it in the question.First of all, I will assume the cells are non-interacting. That way, each individual cell's probability of being plucked out of a sample is independent of that of any other cell. This effects the result. For example, what if these cells attracted each other? Then you either get all or none in a sample. Secondly, I will assume that they have a uniform distribution in the fluid. Often the chemical potential of cells in fluids dramatically outweighs the gravitational potential inflicted upon them, giving them a uniform distribution, but that's not always the case. (They could be massive cells that are virtually unaffected by the bombardment of H2O molecules.)
FYI, without the above two assumptions, we would just have to throw our hands up and say "not enough information to answer the question". So keep that in mind when you're posing a question.
Because of the independence assumption, this problem is identical to the problem of 5 separate test tubes, each of which have 50 mL and only one cell in them. So imagine that scenario. You draw 5mL out of each tube, and in each draw, you either got a cell or you didn't. What is the probability that none of those five samples yielded a cell? Then, what is the probability that at least one sample yielded a cell? (Your logic on discerning (B) from (A) is perfectly correct, so no need to worry about that.)
Then, what is the probability that either exactly one or exactly three of the five 5mL samples yielded a cell? To answer this question, you'll need the Binomial Distribution.
EDIT: The main reason for the equivalence of one test tube with 5 cells and five test tubes with one cell is because of the independence assumption of the position of each cell in the tube. So if you take a sample from the 5 cell tube, whether you got cell A in the sample has absolutely no bearing on whether you got cell B. (This is unlike draws from a card deck, where the position of aces are not independent.) And each cell has the same probability of being drawn. So you're essentially rolling five dice at once. (More explicitly, you're sampling from the same Bernoulli distribution five times simultaneously.) In the other scenario, where you take 5 separate samples from single-cell tubes, you're just rolling the same five dice, but in sequence rather than all together.
Comment: Thank you Bridgeburners for the response.  Based on your answer and comments, I've edited my question.  Yes, I'm assuming the cells do not interact and are uniformly distributed.  I'm confused by your stating that the problem is exactly the same as 5 separate test tubes with only one cell.  I'm just not seeing how that's the same as on 50ml tube with 5 cells.  Can you elaborate? I'm trying to relate it back to playing cards.  If I asked what is the probability of drawing 4 aces from a deck, would it be the same as asking what is the probability of drawing 1 ace from each of 4 decks? Thanks!
Comment: @Dave The card deck is a bad analogy because the positions of aces are not independent. For example, if the ace of spades takes the nn'th position in the deck then the ace of clubs cannot possibly take the nn'th position in the deck. Think of it this way. If you take 1/52 of the fluid from the test tube, it's possible that you get more than one cell from that sample. If you draw one card from the deck, is it possible that you got more than one ace? I'll edit my answer to try and give an intuition on why your original experiment is equivalent to the 5 test tube experiment.


Drupal behaviors attach to form load

Question: I am using the simpledialog module with the 'edit' tab still in it. The edit overlay for the node is displayed in the background with the simpledialog still in the way.
I have tried a bunch of ways of attaching the close call to the edit button and triggering a click on the dialog close button. None of it very successfully - all iframes. e.g.
<code>$htj2('.tabs.primary').delegate('click', 'a', function() {
    $hjt2('#simple-dialog-container').dialog("close");
</code>
I think the 'correct drupal pattern' is to attach a behavior to the form load using drupal behaviors.
<code>(function ($) {
    Drupal.bahaviors.hotTopicsResearch = {
        attach: function(context, settings) {
            // ?? What next?
            $('#hot-topic-research-node-form',context).once('load', function() {

            });
        }
    }
})(jQuery);
</code>
How do I find out what the behaviours are? How do I attach to the load event or is there an event related to clicking on the 'edit' tab? How do I get close the simpledialog?
Comment: it seems like your trying to react to the wrong thing in JS. I assume you're reffering to like this page: http://drupal.org/node/1087026. You want to hide the simpledialog if you press Edit on a node page -- before the Overlay pops up.

You would do that by attaching a simple JS event listener to look for something like `$('a[href~=edit]').clicked() ...` and then simply call simpledialog close or `$('#simplediaglo').hide()`.

my point, I think your attacking it from the wrong direction with the code you've provided
Answer: Got it after a number of days searching:
<code>(function ($) {
    Drupal.behaviors.hotTopicsResearch = {
        attach: function(context, settings) {

            $(document).bind('drupalOverlayBeforeLoad', function(event) {
                $('#simple-dialog-container', context).dialog('close');
            });
        },
        weight: 11
    }

})(jQuery);
</code>
The other events seem to have the wrong order. 'drupalOverlayOpen' almost works except that the editing overlay never 'becomes active'. This is why I was trying to work on the target editing screen events rather than the open dialog.
overlay_paths without there being'use case documentation' it looks like it only applies to menu items. How to manually use Drupal 7's admin Overlay? shows you how to add content nodes to the admin paths. This displayed my node in the admin overlay, but without the background context being visible - defeating the point - and with some further quirks.
Comment: I have exactly same problem and I'm not getting it solved :( I've tried the code you posted but the problem stays. Did you made any improvements after posting your code?

Drupal behaviors attach to form load


Android BLE API: GATT callback not received

Question: I working on an app that connects to a BLE device on a bike. The app works fine on Android 4.x but on Android 5 we don't get any callback on the writeCharacterstic() call. Any help is very appreciated since we are stuck at the moment!
All calls to the gatt seems to return true. I have made sure that the calls are in the correct order so the GATT server won't return status busy:
device.connectGatt()
onConnectionStateChange() -> gatt.discoverServices()
onServicesDiscovered() -> gatt.writeDescriptor()
onDescriptorWrite() -> sendRequest()
sendRequest() -> gatt.writeCharacteristic()

I've been testing on the following devices:

Samsung Galaxy S4 with Android 4.4.2 (working)
Samsung Galaxy S3 with Android 4.3 (working)
LG Nexus 4 with Android 5.0.1 (not working, no callback on writeCharacteristic())

Code:
private BluetoothGattCallback callback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);

        if (newState == BluetoothGatt.STATE_CONNECTED) {
            Log.i(TAG, "onConnectionStateChange() - STATE_CONNECTED");
            boolean discoverServicesOk = gatt.discoverServices();
        } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
            Log.i(TAG, "onConnectionStateChange() - STATE_DISCONNECTED");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);
        Log.i(TAG, "onServicesDiscovered()");

        BluetoothGattService service = gatt.getService(UART_UUID);
        characteristic = service.getCharacteristic(TX_UUID);

        boolean result = gatt.setCharacteristicNotification(characteristic, true);
        Log.i(TAG, "onServicesDiscovered() - setCharacteristicNotification " + result);

        if (characteristic.getDescriptor(CLIENT_UUID) != null) {
            BluetoothGattDescriptor desc = characteristic.getDescriptor(CLIENT_UUID);
            result = desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            Log.i(TAG, "onServicesDiscovered() - ENABLE_NOTIFICATION_VALUE " + result);
            result = desc.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
            Log.i(TAG, "onServicesDiscovered() - ENABLE_INDICATION_VALUE " + result);
            result = gatt.writeDescriptor(desc);
            Log.i(TAG, "onServicesDiscovered() - writeDescriptor " + result);
        }

        connectionState = STATE_CONNECTED;
    }

    @Override
    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        super.onDescriptorWrite(gatt, descriptor, status);
        mCurrentRequest = getNextRequest();
        Log.i(TAG, "onDescriptorWrite() - sending request, type: " + mCurrentRequest.getType());
        sendRequest(mCurrentRequest);
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);

        // DON'T GET HERE ON LOLLIPOP
        Log.d(TAG, "onCharacteristicChanged() - size: " + characteristic.getValue().length + ", type: " + mCurrentRequest.getType());
    }
}

public void sendRequest(AsciiRequest asciiRequest) {
    start = System.currentTimeMillis();
    if (characteristic != null && connectionState == STATE_CONNECTED) {
        Log.i(TAG, "sendRequest() - sending request, type: " + mCurrentRequest.getType());
        characteristic.setValue(asciiRequest.getData());
        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        boolean result = gatt.writeCharacteristic(characteristic);
        Log.i(TAG, "sendRequest() - result writeCharacteristic: " + result);
    } else {
        Log.e(TAG, "sendRequest() - not connected");
    }
}

Logs:
03-31 14:08:28.614: I/BikeActivity(30045): onResume() - not connected yet, trying to connect
03-31 14:08:28.616: I/BikeActivity(30045): doConnect() - connecting to device Bike 2
03-31 14:08:28.634: I/BikeActivity(30045): doConnect() - connected to device Bike 2
03-31 14:08:29.137: I/BikeActivity(30045): onConnectionStateChange() - STATE_CONNECTED
03-31 14:08:29.151: I/BikeActivity(30045): onConnectionStateChange() - connected to device Bike 2
03-31 14:08:29.164: I/BikeActivity(30045): onServicesDiscovered()
03-31 14:08:29.170: I/BikeActivity(30045): onServicesDiscovered() - setCharacteristicNotification true
03-31 14:08:29.170: I/BikeActivity(30045): onServicesDiscovered() - ENABLE_NOTIFICATION_VALUE true
03-31 14:08:29.170: I/BikeActivity(30045): onServicesDiscovered() - ENABLE_INDICATION_VALUE true
03-31 14:08:29.172: I/BikeActivity(30045): onServicesDiscovered() - writeDescriptor true
03-31 14:08:29.173: I/BikeActivity(30045): onDescriptorWrite() - sending request, type: 25
03-31 14:08:29.182: I/BikeActivity(30045): sendRequest() - sending request, type: 25
03-31 14:08:29.186: I/BikeActivity(30045): sendRequest() - result writeCharacteristic: true
03-31 14:08:34.182: I/BikeActivity(30045): doDisconnect() - disconnecting from device Bike 2
03-31 14:08:34.233: I/BikeActivity(30045): onConnectionStateChange() - STATE_DISCONNECTED
03-31 14:08:34.233: I/BikeActivity(30045): onConnectionStateChange() - disconnected
03-31 14:08:34.263: I/BikeActivity(30045): doDisconnect() - toastText: No response from bike.
03-31 14:08:34.318: I/BikeActivity(30045): onPause()
03-31 14:08:34.712: I/BikeActivity(30045): onDestroy()

Answer: I understand that it is late answer, but maybe it will help somebody other with such situation.
I have the same bug with Android 5 devices - note that you have disconnection event instead of writing characterictic.
Try to add empty callback:
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
    {
    }

it helped me with Android 5 devices.


Aliasing "Type" entry of normal JSON to "@type", when value of "Type" is a JSON object

Question: I want to store a normal JSON to a triple store. The normal JSON has its own format for Ids and Types:
<code>{
  "Id": "123456",
  "Type": {
    "Id": "7890",
    "Name": "Person",
    ...
  }
  ...
}
</code>
I am able to flatten the document and give the value of "Id" the type "@id", using a custom context. I am stuck trying to alias "Type" to "@type".
Is there a way to use the "Type" entry of the normal JSON as an "@type" keyword using only a custom context?
Answer: I am not sure what you mean by aliasing "Type" to "@type", since your example would not be valid JSON-LD if "Id" was replaced with "@id" and "Type" was replaced with "@type".
But could perhaps a context like this would be what you are looking for?
<code>  "@context": {
    "@base": "http://example.org/things/",
    "Id": "@id",
    "Type": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
    "Name": "http://www.w3.org/2000/01/rdf-schema#label"
  }
</code>
Example in JSON-LD Playground.
Or, if the different ids come from different namespaces, perhaps with scoped contexts:
<code>  "@context": {
    "@version": 1.1,
    "@base": "http://example.org/objects/",
    "Id": "@id",
    "Type": {
      "@id": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
      "@context": {
        "@base": "http://example.org/types/",
        "Name": "http://www.w3.org/2000/01/rdf-schema#label"
      }
    }
</code>
Also in JSON-LD Playground.


Unit Testing Mock Guzzle Response

Question: I'm trying to test a method that makes an HTTP request via Guzzle, so I can see if my code that filters that response is working. I have a mock json response in a json file that I want to use to test it. This is simply a saved version of an actual response.
I know you can mock methods e.g. this would override the get method to return a mock Guzzle Response. How do you mock a Guzzle response in Drupal 8?
    $this->mockHttp->expects($this->any())
      ->method('get')
      ->willReturn($mockGuzzleResponseShouldGoHere);

The mock Guzzle response needs to have a mock method getBody so I can do something like this:
$this->mockHttp->expects($this->any())
      ->method('getBody')
      ->willReturn(__DIR__ . 'Mocks/membership-classes.json');

and make sure that getBody returns my mock json file.
Method to test that makes a Http Guzzle request
<?php

/**
   * Call the GetMembershipClasses service.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   */
  public function getMembershipClasses() {

    try {
      // Load configuration for this module.
      $response = $this->http_client->get(
        $this->getBaseUrl() . '/2014/06/membershipClasses', [
          'headers' => $this->getAnonymousHeaders(),
        ]);

        $response = json_decode($response->getBody());

        // Get to the meat of the response.
        $response = $response->GetMembershipClassesResponseMessage->MembershipClasses->MembershipClass;

        // Validate returned data.
        $filtered = array();
        foreach ($response as $membership_class) {
          $membership_class->MembershipClassCode = $this->removeSpaces($membership_class->MembershipClassCode);
          if ($membership_class->IsActive === TRUE) {
            $filtered[] = $membership_class;
          }
        }
        return new JsonResponse($filtered);
    }
    catch (RequestException $e) {
      return $this->handleError($e);
    }

  }

And the test class
<?php

/**
 * Class RouteControllerAnonymousTest.
 *
 */
class AnonymousWebServicesTest extends UnitTestCase {

  /**
   * Mock of http_client service.
   *
   * @var \GuzzleHttp\Client
   */
  protected $mockHttp;

  /**
   * Mock of state service.
   *
   * @var \Drupal\Core\State\State
   */
  protected $mockState;

  /**
   * Mock of config.factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $mockConfigFactory;

  /**
   * Set up method which is called before any tests are
   * run. Mocks of the services that the class being tested rely on are
   * created.
   *
   * @return void
   */
  protected function setUp() {

    parent::setUp();
    $mockHttp = $this
      ->getMockBuilder('GuzzleHttp\Client')
      ->disableOriginalConstructor()
      ->setMethods(['get', 'getBody'])
      ->getMock();
    $this->mockHttp = $mockHttp;

    $mockState = $this
      ->getMockBuilder('Drupal\Core\State\State')
      ->disableOriginalConstructor()
      ->getMock();
    $this->mockState = $mockState;

    $mockConfigFactory = $this
      ->getMockBuilder('\Drupal\Core\Config\ConfigFactory')
      ->disableOriginalConstructor()
      ->getMock();
    $this->mockConfigFactory = $mockConfigFactory;

  }

  /**
   * Test the getMembershipClasses method.
   */
  public function testGetMembershipClasses() {

    // This needs to mock a Guzzle response from a get request
    $this->mockHttp->expects($this->any())
      ->method('get')
      ->willReturn('The mock guzzle response should go here);

    $this->mockHttp->expects($this->any())
      ->method('getBody')
      ->willReturn(__DIR__ . 'Mocks/membership-classes.json');

    $anonymousWebServices = new AnonymousWebServices(
      $this->mockHttp,
      $this->mockState,
      $this->mockConfigFactory
    );

    $membership_classes = $anonymousWebServices->getMembershipClasses();
    var_dump($membership_classes);
    // Insert some assert statement here

  }

}

Answer: Guzzle includes a mock handler that lets you provide a mock HTTP response. Docs are at http://docs.guzzlephp.org/en/latest/testing.html. Here's how you might use it in your unit test:
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;

/**
 * Test the getMembershipClasses method.
 */
public function testGetMembershipClasses() {

  $body = file_get_contents(__DIR__ . '/Mocks/membership-class.json');
  // This sets up the mock client to respond to the first request it gets
  // with an HTTP 200 containing your mock json body.
  $mock = new MockHandler([
    new Response(200, [], $body),
  ]);
  $handler = HandlerStack::create($mock);
  $this->mockHttp = new HttpClient(['handler' => $handler]);

  $anonymousWebServices = new AnonymousWebServices(
    $this->mockHttp,
    $this->mockState,
    $this->mockConfigFactory
  );

  $membership_classes = $anonymousWebServices->getMembershipClasses();
  $membership_classes = json_decode($membership_classes->getContent());

  $this->assertNotEmpty($membership_classes);
  foreach ($membership_classes as $membership_class) {
    $this->assertTrue($membership_class->IsActive === TRUE);

  }

}

You can queue multiple mock responses by adding them to your handler at creation time:
  $mock = new MockHandler([
    new Response(200, [], $body),
    new Response(400, [], 'Request malformed.'),
  ]);

Or you can add them after your client has already been instantiated, as long as you keep a reference to your mock handler around. If you have multiple test methods, this is a lot easier to read and maintain:
public function setUp() {
  $this->mockHandler = new MockHandler();
  $handler = HandlerStack::create($this->mockHandler);
  $this->mockHttp = new HttpClient(['handler' => $handler]);
}

public function testSomething() {
  $this->mockHandler->append(new Response(200, [], 'apples and bananas'));
  $responseBody = $this->mockHttp->get('http://example.com')->getBody();
  $this->assertEquals($responseBody, 'apples and bananas');
}

Answer: So this might not be best practice but it does work. I will leave it open for a while if someone has a better answer but this is what I did:
Because the guzzle get() method should return a response object and the code that I'm testing uses the getBody() method of that object I created a mock class for this response with just one method - getBody() - which returns my mock data. I then pass an instance of the MockResponse class as the return value of my mock of the get() method from the mockHttp class.
So, there's probably a more elegant way but it does the job!
  /**
   * Test the getMembershipClasses method.
   */
  public function testGetMembershipClasses() {

    $mockResponse = new MockResponse(__DIR__ . '/Mocks/membership-class.json');

    $this->mockHttp->expects($this->any())
      ->method('get')
      ->willReturn($mockResponse);

    $anonymousWebServices = new AnonymousWebServices(
      $this->mockHttp,
      $this->mockState,
      $this->mockConfigFactory
    );

    $membership_classes = $anonymousWebServices->getMembershipClasses();
    $membership_classes = json_decode($membership_classes->getContent());

    $this->assertNotEmpty($membership_classes);
    foreach ($membership_classes as $membership_class) {
      $this->assertTrue($membership_class->IsActive === TRUE);

    }

  }

}

/**
 * Class MockResponse.
 *
 * @package Drupal\Tests\hambs_api_wrapper\Controller\Unit
 */
class MockResponse {

  private $filePath;

  /**
   * @param {string} $filePath
   *   - The file path where the mock test file lives.
   */
  public function __construct($filePath) {
    $this->filePath = $filePath;
  }

  /**
   * Mocking the Guzzle getBody() method.
   *
   * @return string
   */
  public function getBody() {

    $file_location = $this->filePath;
    $file_handler = fopen($file_location, "r");
    $file = fread($file_handler, filesize($file_location));
    fclose($file_handler);

    return $file;

  }

}

Answer: use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;

// Create a mock and queue two responses.
$mock = new MockHandler([
    new Response(200, ['X-Foo' => 'Bar'], 'Hello, World'),
    new Response(202, ['Content-Length' => 0]),
    new RequestException('Error Communicating with Server', new Request('GET', 'test'))
]);

$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);

// The first request is intercepted with the first response.
$response = $client->request('GET', '/');
echo $response->getStatusCode();
//> 200
echo $response->getBody();
//> Hello, World
// The second request is intercepted with the second response.
echo $client->request('GET', '/')->getStatusCode();
//> 202

// Reset the queue and queue up a new response
$mock->reset();
$mock->append(new Response(201));

// As the mock was reset, the new response is the 201 CREATED,
// instead of the previously queued RequestException
echo $client->request('GET', '/')->getStatusCode();
//> 201

Unit Testing Mock Guzzle Response


azure vms aren't communicating anymore

Question: This is very weird. I have 2 vms: a Windows 2012 SP1 VM (with AD role) and a Ubuntu Server 14.04 LTS. They share the same vnet, that is 192.168.99.x (same region, same resource group, same vnet, same subaddr segment).
Until yesterday, they were talking to each other through it's VIP addr (192.168.99.4 and 192.168.99.5). Then, I shut down the Ubuntu VM (went to the deallocated status, I think) and created another Ubuntu VM to test some things.
But today, I started back the original Ubuntu VM, and suddenly they stopped talking to each other! I have reviewed all settings but nothing came to my help.
I'm testing connectivity this way: while sshing the Ubuntu box, i wget a site that exists in Windows 2012 Server. The site is online, no specific ip binding, I can browse it through windows console using vip ip.
Since my knowledge of Azure and it's powershell scripts is limited, I need some direction where to look!
Answer: OK, I was trying to avoid this, but couldn't wait: I removed the Ubuntu VM from the subnet (adding to another), restarted, returned to the same subnet, restarted again, and voila! The communication was restored. It's odd that you have to do this kind of nonsense movement as a last resource...
Comment: actually, there was probably something wrong with your network settings that were preventing the communication. When you redeploy the VM, the network settings reset. Same happens when you change the size of the VM, it basically deallocates from the current cluster and deploys to a new one, hence, resetting the network.

azure vms aren't communicating anymore


Is it a foul when a player calls a wrong score in badminton?

Question: In one of our tournament double matches after earning a point one of the player mistakenly called the current game point wrong. Instead of saying 6-4 he said 7-4 and the referee didn't rectify it. Then on the next serve when the cork reached the other side one player on that side grabbed the cork and said it was a foul to call a wrong score.
My question:

Was it a foul to call a wrong game point?
Was it a foul that the other player grabbed the cork even though referee didn't call a foul?

Is there a reference URL or book to verify?
Answer: The umpire (not the referee) is in charge of the scoring. Players can announce the score to their partner or even their opponents, but that is not binding in any way. It's hard to prove a negative, but you can peruse the official Laws of Badminton and won't find any mention of a fault of incorrect scoring.
The following laws could apply to a talking player:

§14.2.5 It shall be a fault if in play, a player deliberately distracts an opponent by any action such as shouting or making gestures;
§16.6.3 A player shall not behave in an offensive or inappropriate manner.
§16.6.4 A player shall not be guilty of misconduct not otherwise covered by the Laws of Badminton.

None of this applies: The shuttle wasn't even in play when the score was called, and it's neither offensive nor misconduct to make a mistake.
A case could be made if a player intentionally calls the wrong score all the time. However, even that would be dealt with by the umpire, not the opposing player. The umpire would show a yellow card (without any changes to the score) first. Awarding a point for a fault would be done by the umpire showing a red card, which requires serious misconduct.
Incorrect scoring by the players is no big deal: The umpire clearly announces the correct score after every rally. Usually there's some kind of scoreboard; at higher levels you'll find a TV at either end of the court displaying the current score in big letters. If the player thinks the umpire made a mistake, they can talk to the umpire before the start of the next rally.
However, the player who touched the shuttle did commit a fault:

§13.3.4 It shall be a fault if in play, the shuttle touches the person or dress of a player.

Therefore, the umpire will call out "Fault. 7-4." and update the scoreboard (if any) to 7-4.
Comment: Additionally, it could not possibly be a foul, because fouls do not exist in badminton. There are faults, and there are warnings/cards for various forms of conduct, but the concept of a foul simply does not exist like it does in some other sports.


Am I too old? Is it too late? Starting, Resuming, or Mastering an instrument

Question: Age is a commonly expressed concern in studying music, and there are many questions on this site addressing "late starts" from a variety of perspectives. This post is intended as Link Central for users with related or similar questions.

If you've found this question, chances are you're interested in learning to play an instrument or in some other aspect of music, like theory. But you are -- or feel you are -- getting a late start, and you have doubts: Is it even worth starting? How far can I go? You are far from alone, both in asking and in asking here. This post will help lead you to similar and related questions that have already been fielded by the community.
Comment: Does this answer your question? [Can one be too old to learn an instrument?](https://music.stackexchange.com/questions/76066/can-one-be-too-old-to-learn-an-instrument)
Comment: @Tim Indeed. There is a certain irony. :-)
Comment: I'd be for moving this to the meta, but it's not really a fit for the main site as is. It's mostly just pointing to other answers around the site which is not the point of a canonical question.  You should be able to point to a canonical question to get the answer, not have the canonical question point elsewhere. IMO, almost all questions in your answer should be closed as a duplicate of the question this is closed a duplicate of. I'm happy to talk about this more in chat if needed.
Comment: Wasn't the whole point of this question to cover any/all of the potential duplicates?  And put them all under one banner?
Comment: @BrianTowers The answer you linked to is related, but is a different question. The intent here is to compile links to all the various age-related questions to make them easier to find, rather than to answer the question itself.
Comment: @Aaron maybe a post on meta clarifying your intent might be useful, if there isn't one already? I can see why a mod might want to lock such a post, but at the moment the single "This question already has answers here" link undermines the answer.
Comment: Perhaps one approach could be to make a meta post (or posts) listing 'good answers to common questions', so that when we do get common questions we don't have to search for them anew every time. A slightly trimmed-down version of Aaron's answer here (listing the best 'am i too old' questions) could be a part of that?
Comment: @Max The option of a community wiki has been discussed. I (the OP) am not opposed, but have asked to wait to see if I can better adapt the question to fit as a canonical question. If we do go the community wiki route, it would probably also get moved to Meta, which I would also support. (For the time being, as the OP has done all of the work, the OP would like to receive the credit. However, should the question get re-opened, which is my goal, you could certainly add your own answer[s] and receive any reputation gain for it/them. For now, I'm just keeping the list of links up to date.)
Comment: As long as you haven't to start a concert or solo  career in mind ... it will never be to late!
Comment: @BrianTowers - that's the first question quoted in the answer.
Comment: @Aaron was it your intention for this to be closed? Or are people misunderstanding the intent?
Comment: @topoReinstateMonica Appreciate your checking. I was not intending for it to be closed. Short of knowing why individual close votes were cast, I certainly allow for misunderstanding.
Comment: @topoReinstateMonica Agreed about Meta. My current thinking is to see what happens over the next day or so. One advantage to being closed vs. locked is that the answer can be edited to add new links as they appear.
Comment: I support the intention of Aaron. My first thought was: oh, he might be applying for moderator. I would also support this intentions. ;)
Comment: I vote to reopen this question. It is unfair to close it and nitpicking to say it is a duplicate. It is quite clear that this isn't a problem of Aaron and the intention is very serious.
Comment: @Dom I see your points. Let me start by seeing if I can turn this into a better canonical question. Give me a few days.
Comment: @topoReinstateMonica I could definitely get behind this. Please consider adding it as an answer to the current meta discussion on canonical questions: [Should we create a FAQ about Music Theory?](https://music.meta.stackexchange.com/questions/3547/should-we-create-a-faq-about-music-theory)
Comment: Can this be made into a community wiki? I don't have a problem with rerunning a question if it would be beneficial to collect answers in one place, but I don't see why this OP should get the reputation for it.
Answer: The consensus here on SE MP&T is...
Go for it!
Among the various questions and answers linked here, you'll find a wide variety of viewpoints: encouragement, pitfalls, concerns, and so forth, but in general, you will find that the broad feeling across the site is "Yes, you can. Go for it."
NOTE: It's not always obvious from the title, but age is expressed as a concern in all of the listed questions.

What follows is a list of questions regarding beginning to learn when you feel your age is a concern. They are organized by subject matter; just know that an answer related to an area different from yours might still be the one you're looking for.
Late start as a general concern

Can one be too old to learn an instrument?

Guitar

Is it ever too late to learn guitar?
Can one be too old to learn an instrument?
Methodology to Master Guitar as an adult
Muscle Memory and Age
How realistic is it to become a professional musician when you start learning music late at life?

Piano/Keyboard

Is It too late to start learning keyboard again?
Is it too late for me to become good at piano?
What to choose? Violin or piano?
Adult learning to play popular songs on piano
Learning piano in mid 30s
Self-learning how to play the piano
Is it possible for me to learn piano very very good if I start at this age (26) ? If yes, how long would it take?
Learning piano by autodidact after getting older
Jazz piano versus classical piano
What instrument can an old guy learn if the main goal is to write music
Becoming proficient at piano at age 30?
ABRSM exams for adult beginners
Is it too late to develop foundational piano techniques?

Saxophone

I want to learn the sax. Where should I start?

Violin

What to choose? Violin or piano?
Restarting to play violin
Learning my first instrument
What is the right age to start learning to play violin?
Can I learn violin without a teacher?
What instrument can an old guy learn if the main goal is to write music

Viola

Learning my first instrument

Voice/Singing

Can one be too old to learn how to sing?
How can I improve my voice?
How to improve singing?
Should I stop practice singing and switch to fingerstyle guitar?

Theory

Is it too late to learn music theory and composition?

Composing

Is it too late to learn music theory and composition?
What instrument can an old guy learn if the main goal is to write music

Music school

Restarting to play violin
Pianist at 22 years old

Developing muscle memory

Muscle Memory and Age

Exams / Auditions

ABRSM exams for adult beginners

Going pro

How realistic is it to become a professional musician when you start learning music late at life?


Como exibir uma Lista Circular Duplamente Encadeada

Question: Como faço pra exibir os valores inseridos em uma Lista Circular Duplamente Encadeada?
Segue o meu código com minha tentativa:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <malloc.h>
#include <conio.h>

using namespace std;

int x, num;

struct lista
{
    int valor;
    struct lista * prox;
    struct lista * ant;
};

struct lista * inicio;
struct lista * fim;
struct lista * aux;

//Insere na lista o número passado por parãmetro
void insere(int valor)
{
    aux = (struct lista *)malloc(sizeof(struct lista));
    aux->valor = valor;
    aux->prox = NULL;
    aux->ant = NULL;

    if (inicio == NULL)
    {
        inicio = aux;
    }
    else
    {
        fim->prox = aux;
        aux->ant = fim;
    }
    fim = aux;
    fim->prox;
    inicio->ant = fim;
}

//Mostra todos os elementos da lista
void exibirElementos()
{
    while (1)
    {
        cout << inicio->valor;
        inicio->prox;
        if (inicio->prox->valor == fim->valor)
            break;
    }
}

int main()
{
    inicio = NULL;
    fim = NULL;
    aux = NULL;
}

O método que está responsável por mostrar os valores é exibirElementos().
Estou usando o Visual Studio 2013 para compilar.
Comment: posso postar um pseudo-código?
Comment: @EnzoTiezzi Pode sim.
Answer: Primeiro, coloque a assinatura do método exibirElementos1 logo após a declaração da struct lista
void exibirElementos1(struct lista * node);
Faça uma função recursiva que irá passar por sua lista toda da seguinte maneira.
    void exibirElementos()
    {
        exibirElementos1(&inicio);
    }

    void exibirElementos1(lista *node)
    {
        if (node != null)
        {
            cout<<node->valor
            exibirElementos1(&node->prox);
        }
    }

Dessa maneira ele começa pelo primeiro nodo na sua lista, tendo que você tem um nodo declarado com o nome inicio, e para exatamente no ultimo nodo da sua lista imprimindo todos na tela.
E de forma iterativa
    void exibirElementosIterativo(lista* node)
    {
        while (node != NULL)
        {
            cout << node->valor;
            node = node->prox;
        }
    }

Comment: Desse jeito ta dando erro, está falando que o método não precisa de argumentos. `'exibirElementos()':function does not take 1 arguments`
Comment: atualiza o código pra eu ver como você fez
Comment: eu editei ali, mudei o nome do segundo método `exibirElementos` para `exibirElementos1`.
Comment: Pergunta atualizada
Comment: continua apresentando o mesmo problema ? editei novamente, da uma olhada agora
Comment: Agora está dando outro problema: `'exibirElementos1': identifier not found`. Não está achando a função dentro do método `exibirElementos()`
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/18762/discussion-between-enzo-tiezzi-and-exception).


Redimensionar imagem e adicionar espaço branco para tamanho exacto

Question: Eu preciso de saber como posso fazer com que as imagens no wordpress em vez de fazer hard-crop ou resize simples na escala da imagem, Fique a imagem do tamanho que pretendo e caso a imagem não tenha a mesma escala do resultado pretendido que o script/plugin nao destroça ou corte a imagem.
Algo como isto:
Comment: Não sei a resposta, mas começaria minha pesquisa [por aqui](http://wordpress.stackexchange.com/search?q=wp_generate_attachment_metadata+add_image_size) e [por aqui](http://wordpress.stackexchange.com/search?tab=votes&q=image%20crop%20is%3aanswer)
Comment: Acabo de descobrir que [a partir do WP 3.9](http://bradt.ca/blog/image-crop-position-in-wordpress/) a gente vai poder marcar a posição do crop no `add_image_size`.
Answer: Com CSS é possível:
CSS:
<!doctype html>

    <meta charset="UTF-8">
    <title>Exemplo pt.stackoverflow - Pergunta 10483</title>

Lembrando que o ao alterar o tamanho padrão (no exemplo, 200px) o valor de line-height deve ser sempre 4px menor, ou seja:
Para 400x400, line-height: 396px;
Para 100x100, line-height: 96px;
O line-height é usado para permitir a centralização vertical indicada na própria imagem com vertical-align: middle;
Teste e veja. Use imagens quadradas retangulares (com altura maior que largura e vice-versa).


Repeated Bayesian inference to track a time-varying parameter online

Question: I have trouble finding the name of the problem (and algorithms to solve it) where one needs to repeatedly estimate the value of a continuous, time-varying parameter online based on incoming observations, without knowing the dynamics of the parameter changes, (which could even be random). This seems like a trivial Bayesian inference problem, but I get lost in the literature.
If the observation model is linear and the parameter normal-distributed, what would be an algorithm that computes the maximum a posteriori probability estimate? I thought this would be the Kalman filter without system dynamics, but I am not sure since this would still involve a process noise, which I don't know how to define.
Answer: After more reading, particularly the book by West and Harrison (1997), it seems that it is called a Bayesian forecasting or filtering problem.
If you don't wish to model the dynamics (or can't), the model you could use is then that of a random walk. If the variables are normally-distributed, the Kalman filter would give you the maximum a-posteriori estimate.


Calculus 2 problem

Question: evaluate the indefinite integral,
$$ \int \frac{5x-3x^{2}-17}{(x - 1)(x^2+4)} \ dx . $$
I found $ -3 \ln(x-1)+\frac{5}{2x}\ln(x^2+4)+C $ but apparently that isn't correct
Comment: Your partial fraction decomposition looks to be correct; you should have been left with a second-term integral $ \int \ \frac{5}{x^2 + 4} \ dx \ , $ giving the second term **Rana** shows below. [Now I see what your form means: the anti-derivative is not found by treating the integrand as $ \ (x^2 + 4)^{-1} \ $ and using logarithms,  as taking the derivative will show.]
Answer: The answer is $$-3ln(x-1)+\frac{5}{2}\tan^{-1}\frac{x}{2}+c$$ since $$\int\frac{5}{x^2+4} dx=\frac{5}{2}\tan^{-1}\frac{x}{2}$$

Calculus 2 problem


Finding parameter $k$ for which $\left(x-\frac{1}{2}\right)^2+\left(y+\frac{1}{2}\right)^2= \frac18k^2(x+y+1)^2$ is an equation of an ellipse

Question: I need to find the value of $k$ such that the following equation represents an ellipse:-
$$\left(x-\frac{1}{2}\right)^2+\left(y+\frac{1}{2}\right)^2= \frac18k^2(x+y+1)^2$$
I need to find the range of $k$. Is there any other way than expanding the RHS? Because that would be really tedious and quite a nightmare.
Comment: Consider the definition of an ellipse with respect to one of its foci and its respective directrix.
Comment: You can write this as a conic section with focus $\left(\frac 12, -\frac 12\right)$ and directrix $x+y=-1$
Comment: @Certainlynotadog I have tried using that but don't really get how to apply it here. Might be missing something, dunno
Comment: Also, expanding the RHS is not too bad, it is $x^2+y^2+1+2x+2y+2xy$.
Comment: Expanding isn't so bad. Note that (if you're using the discriminant test $B^2-4AC<0$ for conics of the form $A x^2+B xy+C y^2+D x+E y+F=0$ ) you're only interested in the second-degree terms ($x^2$, $y^2$, $xy$). So, when expanding $(x-1/2)^2$, you can stop at $x^2$, etc.
Comment: @Certainlynotadog Yes but there is $k^2$ multiplied so on taking them all to the left and trying to make squares would be a nightmare
Comment: @Certainlynotadog could you elaborate on how that is the case?
Comment: $k^2=4$ give parabolas, $k=0$ gives a point, my guess would be $k\in (-2,0)\cup (0,2).$
Comment: @Techie5879 see Robert Z's answer.
Comment: @Certainlynotadog Yes I did have a look. Got my answer.
Answer: Note that ellipse can be characterized as the locus of points $P=(x,y)$ whose distances to a point $F$ and a straight line $d$ are in a fixed ratio less than 1:
$$\frac{\text{dist}(P, F)}{\text{dist}(P, d)} = c < 1$$
(see also Certainlynotadog's comment above).
In your case, consider $F=(1/2,-1/2)$ and $d$ as $x+y+1=0$. Then the given equation becomes
$$\text{dist}^2(P, F)=\frac{k^2}{4}\text{dist}^2(P, d)$$
and therefore the locus is an ellipse if and only if $k^2/4<1$ that is $|k|<2$. For $k=0$ we have the degenerate case where the ellipse is the point $F$.


queria colocar dot/circle controls no meu slideshow, alguem pode me ajudar?

Question: eu gostaria de uns dots abaixo do slideshow para quando clicar no primeiro dot o slider vai direto pro primeiro slide, mas não estou conseguindo, alguem pode me ajudar?
HTML:

<meta charset="UTF-8"/>
<title> titulo </title>
<link rel="stylesheet" type="text/css" href="_css/estilo.css"/>

    ❮
    ❯

CSS3:
  *{box-sizing: border-box}

  .slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
  }

 /*prev/next controls */

  .prev, .next {
  cursor: pointer;
  position: absolute;
  top: 250px;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
   }

  .next {
  right: 0;
  border-radius: 3px 0 0 3px;
  }

   .prev:hover, next:hover {
      background-color: rgba(0,0,0,.8);
  }

JS:
var i = 0;
var images = [];
var time = 3000;

images[0] = 'imagens/img1.jpg';
images[1] = 'imagens/img2.jpg';
images[2] = 'imagens/img3.png';

function changeImg(){
document.slide.src = images[i];

if(i < images.length - 1){
    i++;
}else {
    i = 0;
}

setTimeout("changeImg()", time);
}

function nextImg(){
  document.slide.src = images[(i++)%3];
  if (i>=images.length) return true; //fim da lista
  return false;
 }

function prevImg(){
  document.slide.src = images[(i = i<0 ? 0 : i--)%3];
  if (i<=images.length) return true; //fim da lista
  return false;
}

window.onload = () => {
  let time = 3000;
  let id_interval = setInterval(() => {
    if(nextImg()) {
  clearInterval(id_interval);
}
  }, time);
 }

Comment: Olá Gustavo, sugiro que leia sobre: [criar um exemplo mínimo, completo e verificável](https://pt.stackoverflow.com/help/mcve) para poder montar um exemplo com seu código funcionando pra ajudar na análise
Answer: O que você tem de fazer nesse caso é parametrizar a imagem a ser mostrada:
Os dots você adiciona dinâmicamente via Javascript
 i

Javascript:
   var i = 0;
   var images = [];
   var time = 3000;

   images[0] = 'imagens/img1.jpg';
   images[1] = 'imagens/img2.jpg';
   images[2] = 'imagens/img3.png';

   function changeImg(){
   document.slide.src = images[i];

   if(i < images.length - 1){
       i++;
   }else {
       i = 0;
   }

   setTimeout("changeImg()", time);
   }

   function nextImg(){
     i = (++i)% images.length;
     document.slide.src = images[i];
     if (i === (images.length - 1) ) return true; //fim da lista
     return false;
    }

   function prevImg(){
     i = (i === 0 ? 0 : --i);
     document.slide.src = images[i];
     if (i === 0) return true; //fim da lista
     return false;
   }

   function setImg(img) {
         i = img;
         document.slide.src = images[i];
   }

   function createLink(img) {
     return '' + img + '';
   }

   function createDots() {
     document.getElementById('dots').innerHTML = '';
     for (j=0; j < images.length; j++) {
       document.getElementById('dots').innerHTML += createLink(j);
     }
   }

   window.onload = () => {

     createDots();

     let time = 3000;
     let id_interval = setInterval(() => {
       if(nextImg()) {
     clearInterval(id_interval);
   }
     }, time);
    }

Html:

   <meta charset="UTF-8"/>
   <title> titulo </title>
   <link rel="stylesheet" type="text/css" href="_css/estilo.css"/>

       ❮
       ❯

Css:
   *{box-sizing: border-box}

      .slideshow-container {
      max-width: 1000px;
      position: relative;
      margin: auto;
      }

     /*prev/next controls */

      .prev, .next {
      cursor: pointer;
      position: absolute;
      top: 250px;
      width: auto;
      margin-top: -22px;
      padding: 16px;
      color: white;
      font-weight: bold;
      font-size: 18px;
      transition: 0.6s ease;
      border-radius: 0 3px 3px 0;
       }

      .next {
      right: 0;
      border-radius: 3px 0 0 3px;
      }

       .prev:hover, next:hover {
          background-color: rgba(0,0,0,.8);
      }

    .dots {
       height:20px;
       text-align: center;

    }

    .dot {
      display: inline-block;
      border: 1px solid black;
      height: 20px;
      width: 20px;
      border-radius: 10px;
      text-align: center;

    }

    .dot:hover {
      cursor: pointer;
      opacity: 0.5;
    }


Riemann-integrable and boundedness

Question: If $f\in \mathcal{R} [a,b]$ and $\left| f(x) \right|\le M$ for all $x \in [a,b]$ , then
$$\left|\int_a^b f dx \right|\le M(b-a)$$ for all $x\in [a,b]$.
Is it sufficient if i just do the following to prove it?
$f$ is bounded and Riemann-integrable, so
$$-M \le f(x) \le M$$ then $$-M(b-a) \le \int_a^b f(x) dx\le M(b-a)$$
Comment: Your right-hand-side should be $M(b-a)$ of course.  repaired.
Comment: Yeah, it looks fine. I would add that you took the partition $P = \{a, b\}$ to get the last inequality.
Answer: Mh that depends on what you already know. You are using the monoticity of the integral, so when $f\geq g$ than $$
\int_a^b f\, \mathrm{d} x \geq \int_a^b g \, \mathrm{d} x$$
If you already know it, it will be fine, if not you have to prove it, to help you here I need to know how you define the integral.

Riemann-integrable and boundedness


Show vectors are linearly independent.

Question:
Let $T: \mathbb{R}^3 \rightarrow \mathbb{R}^3$, a linear operator such that $T^3(v)=0$
  Prove that $x \in \mathbb{R}^3$ isn't a linear combination of $T(x), T^2(x)$, Assuming $T^2(x) \ne 0$.

I was guided to do the following:
Let
$$y = c_1\cdot T(y) + c_2 \cdot T^2(y)$$
Therefore, $$T^2(y)=c_1\cdot T^3(y) + c_2\cdot T^3(T(y)) = 0$$
I'm not sure how it comes in handy here though
Comment: Looks like you are being asked to do a proof by contradiction. Assume $y$ is a linear combination of $T(y), T^2(y)$ and show you get $T^2(y)=0$, which contradicts the assumption in the problem of $T^2(y) \neq 0$.
Comment: Your answer is right, just mention the method, here you proved the contraposition that is equivalent to the main proposition.
Answer: Suppose
$$x=aTx+bT^2x\;,\;\;a,b\in\Bbb R\implies Tx=aT^2x+\underbrace{bT^3x}_{=0}=aT^2x\implies$$
$$T^2x=aT^3x=0\;,\;\;\text{contradiction}$$
Comment: Oh nice. I feel so stupid right now.

Show vectors are linearly independent.


Trying to understand unbiased estimator

Question: After reading this post, I still don't thoroughly understand what an estimator is. Suppose the samples $D_i={(x_1,y_1),...(x_n,y_n)}$ are drawn randomly from function $$f(x)=sin(2\pi x),$$ so my ultimate goal is to come up with an estimated function $h(x)$, which should approximate $f$ as close as possible, right? Since I don't know what the true $f$ looks like, so I might choose different models to do the approximation, here I consider the linear regression model, which is $$h(x)=\beta^Tx,$$ then I try to estimate the model parameters $\beta$ via OLS, and finally given training sample $D_i$, I have the estimates $\hat\beta_{|D_i}$, and absolutely dffierent $\hat\beta$ for different training set $D_i$.
Here is my problem,

What is the estimator here? According to the post I read, I think that the process of choosing the linear regression model and estimating $\hat\beta$ via OLS are components of the estimator, right?
How to check the estimator is biased or not? Since I chose the linear regression model $h(x)$, and now have the estimates $\hat\beta$, I think to check the estimator is biased or not, is to find out $$B(\hat\beta)=\beta_{true}-E[\hat\beta],$$ right? Now this is the thing confuses me badly, since we don't have this $\beta_{true}$, because the true $f$ is actually $sin(\theta x)$ with $\theta=2\pi$, we only have $\theta_{true}$, no such $\beta_{true}$, right?

Hope you can help me to get things right.
UPDATE
To address @whuber's comment, my question originates from this lecture note (from page 11)
1.how do you "randomly draw" values from a function?
Let's say the target function $f(x)=sin(2\pi x)$ is defined on $x\in [-1,1]$, I could randomly (via a uniform distribution over $[-1,1]$) draw $N$ points $\{x_1,...,x_N\}$, where $N$ is the size of the sample, after that I could compute the output value $y_i=f(x_i)$, no noise added. Now the sample is $\{(x_1,y_1),...,(x_N,y_N)\}$.
2.are either (or both) of the $xi$ or $yi$ measured? what is the expected statistical behavior of the measurement errors?
Here I only measure the training/test error of output value $y_i$. I mean, with different training sample, I have different $\hat\beta$, then for a fixed point $x_0$, the predicted output $\hat y_0=h(x_0)=\beta^Tx_0$ will be different, but the true value is $y_0=f(x_0)$.
3.why are you choosing a linear estimator β′x to approximate a function sin(2πx) that is a fortiori strongly nonlinear?
As what is done in the lecture note, what I have is just the sample, which looks nonlinear, maybe it's not wise to choose a linear estimator, and maybe I should choose this one $$h(x)=\beta_0+\beta_1x+\beta_2x^2$$, a polynomial estimator, but it's still far from the target $sin(2\pi x)$.
Comment: You are having trouble because your description lacks critical information.  First, *how* do you "randomly draw" values from a *function*? Related to this is concern about how those values might depart from the correct functional values: are either (or both) of the $x_i$ or $y_i$ measured?  If so, what is the expected statistical behavior of the measurement errors?  Third, how do you measure "closeness" of an approximation to a function?  Fourth, why are you choosing a linear estimator $\beta^\prime x$ to approximate a function $\sin(2\pi x)$ that is *a fortiori* strongly nonlinear?
Comment: @whuber, I just update my post to address the questions you pose, ;-)
Comment: Thanks (+1). There is a fundamental problem with those lecture notes: they appear to be from the middle of a long sequence and so they do not define or explain any of their terms. Although thanks to your edits (1) and (2) we now have an effective probability model, what is missing is any quantitative way to compare an estimator $h$ to the target $f$.  That's essential for proceeding further. Unfortunately the lecture slides have no reliable indication of how that is done. In (3) you allude to a concept of distance between $h$ and $f$ ("far from"): do you have something quantitative in mind?
Comment: @whuber, actually according to the lecture notes, it compare  th  $h$ to the target $f$ by computing the bias and variance of the predicted output $\hat y$, it even drew some graph in the note, and comparing the two selected Models $h1,h2$.
Answer: I'm not 100% sure about this either, as the post you link to mentions a lot of subtleties that I haven't considered or studied much yet...but here's an attempt to answer nevertheless.

As you've stated it, $h(x)$ is your estimator, because you're using it to approximate $f$. "The process of choosing the linear regression model" is the process of choosing the estimator function, and using it to estimate $\hat\beta$ is just that: using the estimator to produce an estimate. That is, no, these are not components of the estimator itself; these are the process from which the estimator originates, and the process it serves, respectively.
The limited way of testing estimator bias with which I am amateurishly familiar is simulation testing. In such a special circumstance as this, we may actually know $\hat\beta_{true}$ (probably should in many such cases). Furthermore, by simulating data according to predefined parameters, we can test how different values affect the errors of our estimators. As I understand it, these systematic errors are the primary concerns in considerations of estimator bias.
For example, one usually wants an estimator for which the accuracy depends minimally on sample size, or at least won't lose accuracy as sample sizes increase. I think this is sometimes a problem in significance testing, in that some tests will reject the null too often when the null is actually true and the sample size is very large (e.g., the Shapiro-Wilk test). Another example of estimator bias (I think...another place where I might be mistaken) might be your typical parametric test when used in conditions that violate its assumptions. Non-normal distributions can bias parametric tests that assume normally distributed data, whereas nonparametric tests are often relatively unbiased estimators.
Sometimes biasing is more complex and even interactive. For example, I recently read that substituting polychoric correlations for Pearson's $r$ correlations in a matrix on which confirmatory factor analysis is to be performed can inflate (bias) standard errors of parameter estimates and $\chi^2$ goodness-of-fit when using maximum likelihood estimation (Babakus, 1985). The choice of estimator really starts to get hairy in latent factor modeling...
In any case, problems like these are often discovered by simulation testing, wherein the true parameters are designated and altered systematically, random data are generated based on these settings, and estimates are found to deviate from the true values to different degrees depending on the parameters of the simulated distributions. The extent of that dependence on the distributional parameters is the estimator's sensitivity to those parameters; if the sensitivity is non-negligible, the estimator is biased when the parameters to which it is sensitive enter certain ranges. These are often not the parameters it is used to estimate! OLS multiple regression is sensitive to multicollinearity in regressors, for another example, whereas ridge regression can correct for bias somewhat when regressors are strongly related (collinear).
Comment: Thanks, but I still don't think you answer the 2nd question.
Comment: @Nick Lehman is a standard intro graduate-level textbook for courses on estimation (and the first edition has long been a classic). A more accessible introduction that covers the same conceptual material but with less reliance on the mathematical details is Kiefer's *Introduction to Statistical Inference.* The complication in your question is that it is unclear how one ought to measure the difference between an estimator of a function and the function itself (there are many ways). In particular, the lecture slides are opaque concerning what the *bias* might mean in this context.
Comment: Maybe I was a little circuitous, because I also addressed your misconception about bias (it is not usually a function of the estimand, as in your *B*(*β*) example)...but the answer I provided (one of many possible answers) is simulation testing. When you can define all the parameters for yourself, you can test the estimator's sensitivity to them across multiple simulated samples. If you find that errors change in relation to a certain parameter as you change it across simulated samples, you may have found bias. All of this info is in my answer or common practice in sim testing.
Comment: Hope I didn't sound overly indignant in the above response to your feedback BTW. My answer got rather curt as I ran into the character limit, and I don't see any element of your question I didn't answer initially, but if my comment added useful clarifications, I'd be happy to edit them in. If not, could you clarify what's missing?
Comment: Not at all, it's very kind of you to write this answer, and I read your answer over and over again. I'm just having a hard time figuring out that, the target is $f(x)=sin(\theta x)$, but I choose to approximate it using $h(x)=\beta_1x+\beta_0$, which definitely won't approximate $f$ well. But I still could compute $E[\hat\beta_1], E[\hat\beta_0]$ based on all the different samples I have. According to your answer, you mean I shouldn't measure the bias of $\hat\beta$? Why?
Comment: I think @whuber implied in [his answer](http://stats.stackexchange.com/a/7608/32036) (to the question that you linked in your OP) that picking a good estimator function is a matter of estimation theory, so to the extent you understand it and your question, you wouldn't choose $h(x)$ as you've defined it. Still, it's not a completely implausible choice, because lots of people don't understand so well, and **some** error is practically inevitable, so I don't see any problem with using it as an example of a (really bad) estimator. If you wanted a better estimator, you'd attempt to improve it.
Comment: Although I chose a bad estimator $h(x)$, can I still analyze the bias of this estimator? If so, how to measure the bias? Is it $bias(\hat\beta)$ or $bias(\hat y)$, with $\hat y$ being the predicted output value given $\hat\beta$.
Comment: I think what I suggested was to measure the bias of your estimator by finding which parameters of simulated distributions that affect the amount of error in your estimates. In most cases, you'll be estimating one parameter (e.g., relationship between an IV and a DV in multiple regression), but considering your estimator's sensitivity to many parameters as potential sources of bias (e.g., dependence, heteroskedasticity, multicollinearity). I didn't mean to say that bias in certain ranges of the estimand itself shouldn't be tested; I'm just more familiar with biasing due to other parameters.
Comment: Sure, I don't see why any estimator (good or bad) couldn't be analyzed for bias. I guess I'd formulate it as something like this (but more formal definitions might exist out there): $estimate = perfect.estimator(data) + estimator.bias(sensitive.parameter) + other.error$, where
the first term is your $f$, the second is the systematic error (bias) introduced by the sensitivity of your choice of estimator $h(x)$ to $sensitive.parameter$ of distribution $x$, and the third term is less identifiable error due to other imperfections in your choice of $h(x)$ (e.g., model misspecification).
Comment: I see from your last comment that, I should measure the bias of the predicted output $\hat y$, not the bias of the model parameters $\hat\beta$ of $h(x)$, right?
Comment: Bias in an estimator leads to systematic errors in its estimates across all samples on which it is used, so you can really only measure bias in whatever estimates your estimator produces. In a simulation test, you can *cause* bias by manipulating parameters of your simulated samples other than the estimand, but you still have to measure the bias in terms of the errors in your estimates of the simulated estimand. I'm avoiding the symbolic language in this comment because I'm afraid that might be a source of confusion. (It's beginning to confuse me, at least!)
Comment: Thank you so much, I think I'd better read more about estimator related book or lectures, any recommendation?
Comment: Can't think of one; didn't do whatever meager learning I've done with a book! @whuber [recommended](http://stats.stackexchange.com/a/7608/32036) Lehman's [Theory of Point Estimation](http://www.amazon.com/Theory-Point-Estimation-Springer-Statistics/dp/0387985026) (2003) in his answer to that post you linked in the OP though! ;)
Answer: On looking at those lecture notes, the sample size is only two - so you can hardly do better without knowing anything about f than simply averaging the two values.
The notions of "bias" and "variance" can be defined only relative to some kind of model structure.  This is clearly encapsulated by the $ E_x[.] $ and $ E_D[.] $ operators in the lecture notes.  Note though, that they are a tad clumsy in that $ E_x [E_D [.]] $ should really be written as $ E_x [E_{D|x}]] $ as D and x are related by the model.  These basically describe "how did you choose the C values" ($ E_x $) and "given the choice of X values how did you choose the Y values" ($ E_{D|x} $).  Generally speaking, the latter encspsulates the model assumptions with the former generally assumed known.
Now, it seems like you are talking about a problem with "no noise" - now if you know that $ y=f (x) $ exactly - then any estimator that doesn't interpolate the observed data is necessarily wrong.  The only source of "randomness" is which particular "X" values and "Y" values are observed.  This has a similar flavour to design based inference for sample surveys.
The notion of bias in this context depends on the "sample space" for the X values, the "sampling distribution" for the X values, and the function $ f(x) $.  I use quotes as it is entirely reasonable to consider degenerate cases where the X values are not "random" but fixed at prespecified values (as is the case for prediction of a new Y value not used to fit the model).
Now basically you can't get any further with the bias of an estimated function $ h $ unless you impose some conditions on what the function $ f$ might look like.
In fact, without the prescence of any noise this is "merely" a transformation of a random variable.  If you propose/assume a "sampling distribution " for the $ X $ values, call this cdf $ G_X(x)=Pr (X\leq x) $, then the corresponding distribution for the response is $ G_Y (y)=Pr (Y\leq y)=Pr (f (X)\leq y)=\int I\{f (x)\leq y\} dG_X (x)$.  For 1-to-1 continuous, differentiable functions you can simplify this further to state that the pdf for "y" must have the form
$$ g_Y (y)=g_X (f^{-1}(y))|\frac {\partial f^{-1}(y)}{\partial y}|$$
where $ f^{-1}(.)$ is the inverse transformation of $ f (.) $.  So for a linear function $ f (x)=a +bx $ (inverse function of $ f^{-1}(y)=b^{-1} (y-a) $ ) combined with a uniform $[-1, 1] $ pdf for $ X $ gives
$$ g_Y (y)=\frac {I[-1 \leq b^{-1}(y-a) \leq 1]}{2|b|}$$
That is, Y is uniform $[a-b, a+b] $ if $ b> 0 $ and uniform $[a+b, a-b] $ otherwise.  Now we can show that the mle for $ a, b $ is given by the same OLS  "saturated" fit , namely $\hat {b}=\frac {y_1-y_2}{x_1-x_2} $ and $\hat {a}=\frac {y_2x_1-y_1x_2}{x_1-x_2}$.  In fact these must be the exact values for $ a $ and $ b $ provided the linear function is correct - regardless of the sampling distribution for X.  Another way of saying this is that there can be only one noiseless linear relationship between two or more X-Y pairs.  This also leads to an extremely aggressive predictive distribution degenerate at $ \hat {y }=\hat {a}+\hat {b} x $ with zero margin for error (after observing x).  The aggressive prediction comes from the "no noise" assumption.
As a final remark, the observed data provides no information on what that relationship is for "X-Y" pairs that are not fully observed.  This can only come from other pieces of information - such as assumptions about smoothness, and continuity of $ f (.) $.  This makes calculating bias impossible in a general sense, because your answer will depend on some arbitrary unknown function.  You have to assume something about what it could be in order to calculate the bias of an estimator for $ f(.) $ (eg $ f (.) $ has a third order derivative, no singularities, is analytic, etc).  But these choices cannot be disentangled from the choices resulting from standard model checking (eg add a quadratic term if a plot of the residuals shows curvature).  This clouds the practical use of "bias" in a rigorous and completely general fashion, as the observed data set is analysed to decide model structure.  Different data sets get analysed in different ways, adding a "human element" to a bias calculation (and variance too) that is difficult to both automate (making Monte Carlo infeasible) and write down a formula for what happens.
Having said that, the notion of bias is still useful as part of a check of model assumptions - but is generally better thought of in terms of complexity and stability of the model IMO.  Bias is also useful as a conceptual tool to aid understanding of general model fitting issuues and the tension between explaing the observed data and predicting unobserved data.
Comment: +1, but I have to say your answer is math heavy for me,;-). Anyway, as I read into your answer, 1)bias is used with some random processes, 2)and it's just a guideline for us to analyze the model, since we don't or can't know what the bias is exactly, because we don't know what the true parameter is. Am I right?
Comment: @loganecolss - basically yes.  Bias is always with respect to a random process (what I called a model).  You can know what the bias is for some parameters in some types of models (linear regression).  But for vague models like $ y=f (x) $ you can only get a vague idea of bias.
Comment: Well, since $bias(\hat y)=E[\hat y]-y_{true}$, so if I can know what the bias is, that means I can know $y_{true}$, right? But in practice, what I have is just the sample with noise, so how could I know $y_{true}$?

Trying to understand unbiased estimator


Skip the folder names in the localhost server url?

Question: Actually I am working on a project on my local wamp server. I need to redirect the main page from this
URL ------>localhost/aftabcurrency/cpanel/main_page.php
to the following
url localhost/aftabcurrency/main_page.php
I have tried this rewriting code in m .htaccess file
RewriteEngine On    # Turn on the rewriting engine

RewriteRule ^main_page.php$     /aftabcurrency/cpanel/main_page.php [L]

and also this one
RewriteRule ^main_page.php$     aftabcurrency/cpanel/main_page.php [L]

but its giving an error of Not FOUND...
Answer: Try this code:
RewriteRule ^aftabcurrency/cpanel/main_page.php$ aftabcurrency/main_page.php [L]

You're redirecting it infinite when you only define main_page.php.
Comment: You want to direct /cpanel/main_page.php to /main_page.php? Or the other way around?


WordPress CPT Numbered Pagination

Question: I have a custom post type in WordPress.
The mobile archive page is a slider through ALL the posts.
The desktop archive page is a normal archive page, with numbered navigation and only shows 6 posts per page.
I see to have this working, however on the desktop, there should only be 3 pages, but instead, there are 4 pages, and the fourth page is empty.
I'm baffled as to what I've done wrong, so if anyone can take a look, that would be brill.
Thank you
archive-projects.php:
<?php
if ( !have_posts() ) {
    // If no posts match the query
    get_template_part( '404' );
    return;
}

get_header();
?>

            <?php
                $args = array(
                    'post_type'         => 'projects',
                    'order-by'          => 'date',
                    'order'             => 'des',
                    'posts_per_page'    => -1
                );

                $the_query = new WP_Query( $args );
                if($the_query->have_posts() ) :
                    while ( $the_query->have_posts() ) :
                       $the_query->the_post();
            ?>
                <article <?php post_class( 'entry entry-archive' ); ?>  data-aos="fade">
                    <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>

                        <a href="<?php the_permalink(); ?>">
                            <div class="post-image" style="background-image: url('<?php echo $backgroundImg[0]; ?>')">

                        <?php the_title( '
', '
' ); ?>
                        <a href="<?php the_permalink(); ?>" class="more-link">See More

            <?php
                    endwhile;
                    wp_reset_postdata();
                else:
                endif;
            ?>

            <?php
                $args = array(
                    'post_type'         => 'projects',
                    'order-by'          => 'date',
                    'order'             => 'des',
                    'paged'             => $paged,
                    'posts_per_page'    => 6
                );

                $the_query = new WP_Query( $args );
                if($the_query->have_posts() ) :
                    while ( $the_query->have_posts() ) :
                       $the_query->the_post();
            ?>
                <article <?php post_class( 'entry entry-archive' ); ?>  data-aos="fade">
                    <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>

                        <a href="<?php the_permalink(); ?>">
                            <div class="post-image" style="background-image: url('<?php echo $backgroundImg[0]; ?>')">

                        <?php the_title( '
', '
' ); ?>
                        <a href="<?php the_permalink(); ?>" class="more-link">See More

            <?php
                    endwhile;
                    wp_reset_postdata();
                else:
                endif;
            ?>

            <?php
                get_template_part( '_template-parts/page-navigation' );
            ?>

            <?php /* get_sidebar(); */ ?>

<?php
get_footer();

page-navigation.php:
<?php if ( is_singular() ) : ?>

    <?php if( get_post_type() == 'projects' ) { ?>

                <?php if ( get_next_post() ) { ?>

<?php next_post_link( '%link', 'Previous Project' ) ?>

                <?php } ?>

                <?php if ( get_previous_post() ) { ?>

<?php previous_post_link( '%link', 'Next Project' ) ?>

                <?php } ?>

    <?php } else { ?>

                <?php if ( get_next_post() ) { ?>

<?php next_post_link( '%link', 'Previous Post' ) ?>

                <?php } ?>

                <?php if ( get_previous_post() ) { ?>

<?php previous_post_link( '%link', 'Next Post' ) ?>

                <?php } ?>

    <?php } ?>

<?php else : ?>

    <?php
        aa_numeric_posts_nav();
        // located in includes > functions > theme-functions.php
    ?>

<?php endif; ?>

aa_posts_nav_function():
function aa_numeric_posts_nav() {

    if( is_singular() )
        return;

    global $wp_query;

    // $paged = 0;

    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;

    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );

    /** Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;

    /** Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }
    //
    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }

    echo '

' . "\n";

    /** Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '
%s
' . "\n", get_previous_posts_link() );

    /** Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';

        printf( '
%s
' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

        if ( ! in_array( 2, $links ) )
            echo '
…
';
    }

    /** Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '
%s
' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }

    /** Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '
…
' . "\n";

        $class = $paged == $max ? ' class="active"' : '';
        printf( '
%s
' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }

    /** Next Post Link */
    if ( get_next_posts_link() )
        printf( '
%s
' . "\n", get_next_posts_link() );

    echo '

' . "\n";

}

Comment: First of all you change `'orderby'` instead of `'order-by'` and  change `'order' => 'DESC'`  instead of  `'order'  => 'des'` in your `$args`
Comment: Thanks Sobir. I took this from online and didn't even notice that.
Still have that empty page though :(
Answer: Fixed it. I removed the WP_Query completely for the desktop version (in archive- and added it using a separate function. This is what I have now and works:
archive-projects.php
<?php
if ( !have_posts() ) {
    // If no posts match the query
    get_template_part( '404' );
    return;
}

get_header();
?>

            <?php
                $args = array(
                    'post_type'         => 'projects',
                    'order-by'          => 'date',
                    'order'             => 'des',
                    'posts_per_page'    => -1
                );

                $the_query = new WP_Query( $args );
                if($the_query->have_posts() ) :
                    while ( $the_query->have_posts() ) :
                       $the_query->the_post();
            ?>
                <article <?php post_class( 'entry entry-archive' ); ?>  data-aos="fade">
                    <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>

                        <a href="<?php the_permalink(); ?>">
                            <div class="post-image" style="background-image: url('<?php echo $backgroundImg[0]; ?>')">

                        <?php the_title( '
', '
' ); ?>
                        <a href="<?php the_permalink(); ?>" class="more-link">See More

            <?php
                endwhile;
                wp_reset_postdata();
                else:
                endif;
            ?>

            <?php
                if(have_posts() ) :
                    while ( have_posts() ) : the_post();
            ?>
                <article <?php post_class( 'entry entry-archive' ); ?>  data-aos="fade">
                    <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>

                        <a href="<?php the_permalink(); ?>">
                            <div class="post-image" style="background-image: url('<?php echo $backgroundImg[0]; ?>')">

                        <?php the_title( '
', '
' ); ?>
                        <a href="<?php the_permalink(); ?>" class="more-link">See More

            <?php
                endwhile;
                wp_reset_postdata();
                else:
                    echo '
No posts found!
';
                endif;
                aa_numeric_posts_nav();
            ?>

            <?php /* get_sidebar(); */ ?>

<?php
get_footer();

aa_numeric_posts_nav(); function
function aa_numeric_posts_nav() {

    if( is_singular() )
        return;

    global $wp_query;

    // $paged = 0;

    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;

    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );

    /** Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;

    /** Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }
    //
    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }

    echo '

' . "\n";

    /** Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '
%s
' . "\n", get_previous_posts_link() );

    /** Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';

        printf( '
%s
' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

        if ( ! in_array( 2, $links ) )
            echo '
…
';
    }

    /** Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '
%s
' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }

    /** Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '
…
' . "\n";

        $class = $paged == $max ? ' class="active"' : '';
        printf( '
%s
' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }

    /** Next Post Link */
    if ( get_next_posts_link() )
        printf( '
%s
' . "\n", get_next_posts_link() );

    echo '

' . "\n";

}

function for posts per page CPT for my desktop:
function aa_order_cpt( $query ) {

    // exit out if it's the admin or it isn't the main query
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    // order category archives by title in ascending order
    if ( is_archive() ) {
        $query->set( 'order' , 'desc' );
        $query->set( 'orderby', 'date');
        $query->set('posts_per_page', 6 );
    }
    return;
}
add_action( 'pre_get_posts', 'aa_order_cpt', 1 );

WordPress CPT Numbered Pagination


How to configure IIS7 to view an MVC3 site without interfering with Webforms Production Site?

Question: I have a client who is running his ASP.nET 3.5 webforms site on IIS7 under Default Web Site.  I've started development on his MVC3 and have the site files ready for him to review.
How do I setup IIS to serve his MVC3 site as a subdomain(?) so that his productions site continues to function while he can also view progress on the new project?
Thanks,
Sid
Answer: In IIS create a new web site which will use a different folder in inetpub.  If using http and not https, then give the new web site binding a host header and create a dns name to match it, so they both are beta.domain.com while production runs www.domain.com.  In IIS make sure new web app has it's own app pool so they don't affect each other, then you should be good to go.


Fabric and cygwin don't work with windows UNC paths

Question: I have some strange problems with fabric deployment to Windows Server 2008r2.
The thing I try to accomplish is to copy some files to a shared folder with a fabric script (this script does a lot of other things too, but only this step gives me problems).
This is the problem:
When I try to access a UNC(Universal Naming convention) path I always get access denied kind of answers if I run the script in fabric. When I run the command in an ssh prompt (same user) it works fine.
Examples:

cmd: robocopy f:/.... //share

result: in ssh this works fine, in fabric I get "Logon failure: the user has not been granted the requested logon type aat this computer."

cmd: cd //share

result: in ssh this works fine, in fabric I get "//share: Not a directory"

Further information:
uname -a and whoami return exact the same thing in fabric and ssh.
I also tried things like mount, net use, but these commands all have kind of the same problem.
Answer:
Go to: Administrative Tools -> Local Security Policy -> Security
Settings -> Local Policies -> User Rights Assignment
Add the user to the Log on as a service policy and try again.


Why set the whole `hints` variable to 0?

Question: I am reading Beej's guide to network programming and in chapter 5.1, in the showip.c program I see the following line of code:
 memset(&hints, 0, sizeof hints);
After a discussion on the ##c channel on freenode I deducted that the reasoning of that memset call could be to set the value of hints.ai_flags to 0(note that the program works fine I remove that line and I explicitly initialize hints.ai_flags to 0). If this is true, why does he need to set the whole struct to 0?
This is the full source:
/*
** showip.c -- show IP addresses for a host given on the command line
*/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
    struct addrinfo hints, *res, *p;
    int status;
    char ipstr[INET6_ADDRSTRLEN];

    if (argc != 2) {
        fprintf(stderr,"usage: showip hostname\n");
        return 1;
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
    hints.ai_socktype = SOCK_STREAM;

    if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
        return 2;
    }

    printf("IP addresses for %s:\n\n", argv[1]);

    for(p = res;p != NULL; p = p->ai_next) {
        void *addr;
        char *ipver;

        // get the pointer to the address itself,
        // different fields in IPv4 and IPv6:
        if (p->ai_family == AF_INET) { // IPv4
            struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
            addr = &(ipv4->sin_addr);
            ipver = "IPv4";
        } else { // IPv6
            struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
            addr = &(ipv6->sin6_addr);
            ipver = "IPv6";
        }

        // convert the IP to a string and print it:
        inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
        printf("  %s: %s\n", ipver, ipstr);
    }

    freeaddrinfo(res); // free the linked list

    return 0;
}

Answer: It's because you are only going to fill/use/initialize some of the fields of the struct, giving 0 to the other fields prevents reading an uninitialzied variable, and sometimes 0 is the default value for those variables.

note that the program works fine I remove that line and I explicitly initialize hints.ai_flags to 0

Not necessarily, if you are on linux, I suggest using valgrind to detect reads to uninitialized variables, since that causes undefined behavior, the behavior could be that nothing wierd happens.
Answer: It's required by getaddrinfo() function documentation (where you pass your hints variable as parameter). From man getaddrinfo:

All the other fields in the structure pointed to by hints must contain either 0 or a NULL pointer, as appropriate.


How can I adjust the position of a cancel button added with hook_form_alter()?

Question: Based on this answer, I added a cancel button to my user picture upload form like this:
  $types = array(
    'profile_picture',
  );

  foreach($types as $type) {
    if($type.'_node_form' == $form_id) {
      if(arg(1) == 'add') {
        // If adding node link to node/add screen
        $link = l(t('Cancel'), 'account/manage-pictures', array('attributes' => array('class' => array('form-submit','cancel'), 'id' => 'edit-cancel')));
      }
      elseif(arg(2) == 'edit') {
        // If editing node, link to node view screen
        $link = l(t('Cancel'), 'node/'.arg(1), array('attributes' => array('class' => 'form-submit, cancel', 'id' => 'edit-cancel')));
      }
      $form['cancel'] = array(
        '#type' => 'markup',
        '#markup' => $link,
        '#weight' => 0,
      );
    }
  }

However, this causes the red cancel button to be placed at the top of the form instead of the bottom of the form next to the purple save button as shown in the screenshot below.

When I examined the CSS in Firebug, I saw that the save button is under this div:
, while the cancel button is not.  Is there a way to place the cancel button under the same div as the save button?
Comment: Which buttons are the red, and purple ones?
Comment: I should have been clearer. I see that the top button is red, and the one at the bottom is purple. What I meant is what buttons are those, and which module adds them. Also, your code shows a "Cancel" link, but the screenshot is not in English. It's not clear where in the screenshot that link is.
Comment: The top red button is the cancel button, which is provided by my custom code.  The bottom purple button is the save button for a new content type, which is provided by Drupal by default.
Answer: Use the following code.
$form['actions']['cancel'] = array(
 '#type' => 'markup',
 '#markup' => $link,
);

If it doesn't work, check with print_r() where the submission buttons are added in the form array. Usually, it's $form['actions'], but sometimes can be a different array index.
Answer: Use $form['buttons']['cancel'] = /* … */;.
buttons is just an example; it depends on how the form was created. Some forms call it actions or something else. Inspect the form variable to find out where to put your button.
Sometimes the save button won't be in a special div. In that case you only need set the weight to something high in order to get it last.