Swift translating coordinates in UIView Coordinate System

Question: I am currently building an app that controls a robot with joytstick interface; however, I want to plot lidar data; initially, I did this using SpriteKit but I realized the performance was too slow:
How to draw 720 data points using Swift
Now, I am using UIKit
My lidar sensor returns 360 data points i.e. distances; these distances are values of how far it detected an object
I am trying to plot circles on a UIView but the coordinate system is very confusing to me;
here is what I am doing currently: I am translating the distances to cartesian coordinates but this doesn't map nice to UIView's coordinate system since the origin (0,0) is on the top left
How can I translate my coordinate system so that the origin is at "(bounds.width/2, bounds.height/2)"?
As you can see in the picture the dots are displaced

[![import Foundation
import UIKit

@IBDesignable
public class Contours: UIView {

    public var gridColor: UIColor = UIColor.black // { didSet { setNeedsDisplay() }}
    public var gridSize: CGSize = CGSize(width: 100, height: 100) // { didSet { setNeedsDisplay() }}
    public var gridView = UIView(frame: CGRect(origin: .zero, size: .zero))

    public var dataSize: CGSize = CGSize(width: 10, height: 10) // { didSet { setNeedsDisplay() }}
    public var dataColor: UIColor = UIColor.blue // { didSet { setNeedsDisplay() }}
    public var dataView = UIView(frame: CGRect(origin: .zero, size: .zero))

    public var fade: CGFloat = 0.5 { didSet { setNeedsDisplay() }}

    public var distances: \[Int\] = \[2601, 2600, 33, 2608, 2601, 2594, 2625, 2633, 2637, 2651, 2656, 2666, 2683, 2690, 2705, 2712, 2712, 2739, 2752, 53, 1103, 1060, 1019, 980, 944, 911, 33, 851, 826, 801, 777, 757, 737, 718, 701, 683, 667, 654, 53, 486, 470, 457, 448, 440, 432, 424, 416, 409, 403, 396, 389, 383, 378, 372, 367, 362, 357, 353, 348, 344, 340, 336, 333, 329, 326, 323, 319, 317, 314, 311, 309, 307, 305, 303, 301, 299, 298, 297, 295, 294, 293, 292, 291, 290, 290, 290, 290, 291, 293, 295, 303, 386, 383, 53, 350, 53, 53, 53, 53, 53, 3, 364, 362, 360, 356, 358, 355, 353, 351, 350, 349, 347, 345, 53, 53, 53, 308, 3, 309, 309, 312, 313, 315, 316, 319, 321, 53, 329, 332, 335, 332, 53, 53, 53, 53, 53, 53, 53, 3, 53, 53, 53, 53, 53, 53, 670, 33, 706, 728, 750, 772, 799, 825, 856, 887, 925, 755, 749, 744, 739, 734, 730, 727, 722, 719, 716, 714, 634, 709, 706, 704, 703, 701, 699, 700, 695, 697, 697, 338, 696, 697, 696, 698, 698, 700, 702, 703, 705, 707, 710, 712, 714, 718, 53, 53, 53, 53, 53, 53, 53, 53, 3, 53, 53, 53, 53, 53, 53, 53, 53, 3, 53, 53, 53, 53, 53, 53, 53, 3412, 3397, 3384, 53, 3538, 3603, 53, 2426, 2412, 2363, 2330, 2288, 2262, 2214, 2190, 2162, 2130, 53, 53, 53, 2807, 2631, 2408, 2638, 2607, 2601, 2562, 2534, 2515, 2496, 2478, 2462, 2445, 53, 53, 53, 1751, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 3, 53, 53, 53, 53, 53, 2643, 2643, 53, 2660, 53, 2528, 2523, 2221, 1955, 1684, 1677, 1684, 1694, 1705, 1202, 1204, 1211, 1217, 1225, 1233, 1239, 1249, 1259, 1270, 1280, 1289, 1280, 1011, 991, 977, 968, 966, 964, 968, 975, 984, 1003, 2, 53, 1297, 53, 53, 33, 1321, 1299, 1274, 1254, 1233, 1232, 1264, 1293, 3802, 53, 53, 53, 53, 53, 53, 53, 3, 53, 2878, 2870, 2848, 2821, 2803, 2788, 2769, 2753, 2740, 2708, 2711, 2701, 2682, 2656, 2664, 2644, 2644, 2631, 2626, 2616, 2610, 2604, 2605, 2605, 2600, 2598, 2603\]

//    public var circleViews: \[UIView\] = \[\]
    public var distx: \[Double\] = \[\]
    public var disty: \[Double\] = \[\]
    public var scalex: \[Double\] = \[\]
    public var scaley: \[Double\] = \[\]

    override public init(frame: CGRect) {
        super.init(frame: frame)
    }

    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    public override func draw(_ rect: CGRect) {

        alpha = 1
        layer.backgroundColor = gridColor.cgColor

        for index in 0...356 {
            let radians = Double(index) * M_PI / 180.0
            let x = Double(distances\[index\]) * cos(Double(radians))
            let y = Double(distances\[index\]) * sin(Double(radians))
            distx.append(x)
            disty.append(y)
        }

        let xmin: Double = Double(distx.min()!)
        let xmax: Double = Double(distx.max()!)
        let ymin: Double = Double(disty.min()!)
        let ymax: Double = Double(disty.max()!)

        let scale = max(xmax - xmin, ymax - ymin)

        var circles = \[UIView\]()
        circles.reserveCapacity(360)
        for _ in 0...356 {
            circles.append(UIView(frame: CGRect(origin: .zero, size: .zero)))
        }

//        CGSize(width: 30, height: 30)
//        circles\[index\].alpha = 1
//        circles\[index\].frame = CGRect(origin: CGPoint(x: bounds.width/2, y: bounds.height/2), size: dataSize)
//        circles\[index\].center = CGPoint(x: x, y: y)
//        circles\[index\].layer.backgroundColor = dataColor.cgColor
//        circles\[index\].layer.cornerRadius = circles\[index\].bounds.width / 2

        print("width: \(bounds.width), height: \(bounds.height)")

        for index in 0...356 {
            let radians = Double(index) * M_PI / 180.0
            let x = ((Double(distances\[index\]) * cos(Double(radians)) / scale) * Double(bounds.width))
            let y = (Double(distances\[index\]) * sin(Double(radians)) / scale) * Double(bounds.height)

            circles\[index\].alpha = 1
            circles\[index\].frame = CGRect(origin: .zero, size: dataSize)

//            circles\[index\].frame = CGRect(origin: CGPoint(x: bounds.width/2, y: bounds.height/2), size: dataSize)
            circles\[index\].center = CGPoint(x: x, y: y)
            circles\[index\].layer.backgroundColor = dataColor.cgColor
            circles\[index\].layer.cornerRadius = circles\[index\].bounds.width / 2

            print("x: \(x), y: \(y)")
//            print("zero: \(layer.anchorPoint)")

            if let superview = circles\[index\].superview {
                superview.bringSubview(toFront: circles\[index\])
            } else {
                addSubview(circles\[index\])
            }

//            scalex.append(x)
//            scaley.append(y)
        }

    }

    private func reset() {
        UIView.animate(withDuration: 0.25) { () -> Void in
            self.gridView.center = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
        }
    }

}][1]][1]

Answer: Your code is currently using addSubview within the Contours class. Therefore the circles will be relative to the bounds of the contours view. I assume the contours view has an origin at the top left of the screen, whereas you need to set its frame to be like that for however you're drawing the red rectangle.


No fields in appearing ssrs dataset - dynamic SQL

Question: I'm trying to run this through SSRS using the database name as  @CATALOG parameter but the field list won't populate. Any advice would be much appreciated.
DECLARE @SQLScript AS NVARCHAR(4000)

SET @SQLScript =
'USE ' +@CATALOG + CHAR(13) +
'SELECT
    LD.ProvSpecMon_A AS Dept,
    LD.ProvSpecMon_C AS SubjArea,
    LD.ProvSpecMon_B AS CourseCode,
    L.LearnRefNumber AS PersonCode,
    CASE
        WHEN L.PlanEEPHours + L.PlanLearnHours >= 540 THEN 'FT'
        ELSE 'PT'
    END AS LearnerType,
    LD.AimType,
    LD.LearnAimRef AS LearningAim,
    AIM.LearnAimRefTitle AS LearningAimTitle,
    EFA.OnProgPayment,
    EFA.StartFund
FROM Valid.Learner L
INNER JOIN Valid.LearningDelivery LD
    ON LD.LearnRefNumber = L.LearnRefNumber
LEFT JOIN Rulebase. DV_Learner AGE
    ON AGE.LearnRefNumber = L.LearnRefNumber
LEFT JOIN Rulebase.EFA_LEARNER EFA
    ON EFA.LearnRefNumber = L.LearnRefNumber
LEFT JOIN Rulebase.EFALearningDeliveryLARSInput AIM
    ON AIM.AimSeqNumber = LD.AimSeqNumber
    AND AIM.LearnRefNumber = LD.LearnRefNumber
WHERE
    EFA.StartFund = 1
    AND LD.AimType = 5
ORDER BY
    L.LearnRefNumber'

EXECUTE sp_executesql @SQLScript

Comment: What's the error? What tables are you using and what are their structures? What output are you expecting?
Comment: Try running the query with a hardcoded catalog, check if it works to discard parameter population error.
Comment: It works fine with a hardcoded catalog. I'm not getting error message but the field list won't display in the dataset.
Comment: Catalog must be set at datasource not dataset level.
Comment: I have a couple of other ssrs reports that work with the Catalog as a datasource but they don't use the EXECUTE sp_executesql just EXEC @SQLScript. I've tried this with this report and still can't get the field list to appear.  I've just slightly amended these reports as some of the field names had changed.
Comment: Recommended reading: [How to use dynamic data sources in your SSRS report](http://www.keepitsimpleandfast.com/2012/08/how-to-use-dynamic-data-sources-in-your.html)
Answer: If you want to parametrize your catalog you have to parametrize your connection string.
In datasource properties select Embedded connection and put a connection string expression with your parameter.

You can use parameters in the connection string:
="Data Source=" & Parameters!ServerName.Value & ";Initial Catalog=" & Parameters!Catalog.Value


Discord.py - How to make people wait some time to use a command again?

Question: I want to make a command "beg" but I don't want people to use it always and earn money, so is it possible to make people wait some time to use the command again?
Comment: Have a dictionary of people and the last time they used the function.
Answer: discord.ext.commands has a decorator function cooldown. Takes 3 parameters:
per => after how many uses to occur
rate => how seconds to wait
type => cooldown type. can be guild, user, channel, role
In Cogs
@commands.command(name="ping")
@commands.cooldown(per=1, rate=3.0, type=commands.BucketType.user)
async def ping(self, ctx):
  await ctx.send("Pong!")

Not in cogs
@bot.command(name="ping")
@commands.cooldown(per=1, rate=3.0, type=commands.BucketType.user)
async def ping(ctx):
  await ctx.send("Pong!")

Comment: For what **self** is needed?


Supervised Learning validation Set - ANN

Question: I have implemented a Neural Network in Processing using Supervised Learning method.
What I'm actually doing is training some circles to move on their target position.
My code works perfectly however, I found that many people split their code into 3 sets,
in order to find the validation error in relation to training error. (performance of network).
 1.Training Set
 2.Validation Set
 3.Test Set

My program includes a set of training inputs and training outputs. My network is trained (loop) until it has achieved a specific target.
For example I have 5 inputs and 5 target outputs.
Input values  {0.2, 0.1, 0.15, 0.11, 0,01}
Target values {1,1,1,1,1}

Set Learning rate = 1
Set momentum = 1
Set bias     = 1

A) Create 5 random weights between 0-1 and 5 bias Weight from 0-1.
random_Weight = random (0-1)
Bias_Weight = random (0-1)

B) Calculate sum
Sum = (input_data  * random_Weight) + (Bias * Bias_Weight)

c) Input data into exponential Function
Output  =  1.0 /(1.0 +exp(-1 * sum)

d) Calculate Error:
Error = Target values - output

e) Adjust new weights
Change = (learning rate * weight * input values) + (momentum * change)
weight = weight + change

f) Repeat until Target position = current position
I don't know how many times my train function will repeat until the expected target is achieved. How can I divide the data into the 3 sets? (train, validation, test).
If I understood correctly I have implemented the training set only.
My question is [a] how to create validation set in this specific problem?
[b] What is the data set and [c] how can I split it for the validation set in this case?
[d] How to calculate validation error?
[e] Is there any suggested documentation in this procedure where I could start?
Answer: Ad "performance of network"
Let's first demystify the terms. Network has no "performance" per se. Any predictor, derived from a functional minimiser ( classical ANNs are such case ) has some "mathematically formulated" error of how well is it modelling the Reality, however the main issue is not how "close" the model simulates the observed ( and ad-hoc emulated ) Reality ( having been trained by the example-result pairs [observations] used in training )
BUT
how "well" the "trained"-model will handle the not yet observed ( thus not pre-trained ) examples.
Thus the ANN-model ability to "generalise", not to suffer from "bias" and "overfitting" are the main qualitative signs of the predictor's "performance" ( quality of predictions ).
Ad [a]+[b]+[c]
For the sake of the SUPERVISED learner, your chances are quite high. Prepare, develop or otherwise acquire a reasonable amount of examples ( observations ) from your problem domain.
As [e] will teach you, there is a certain rationale for the problem domain, what a reasonable amount is ( and in brief: it depends on the intrinsic behaviour of the Reality,  your ANN is trying to simulate, thus it is not known a-priori, so no need to panic prematurely ).
Take responsible SUPERVISED learning / data-sanity efforts to make sure, your ANN-learner will not train against wrong/noisy [ example, correct_result ]-pairs in any row of your available DataSET. This is more important than one may expect on first sight. Yes, it is human to err, however the Hell is not forgiving and getting any AI/ML-learner pre-trained to repeat and repeat and repeat and repeat your errors is anything but a waste of a chance to use the powers of AI.
Having a DataSET of say 2000 observations ( [x_1.1, x_2.1, x_3.1,...,x_n.1],[y_1] ) available, classics recommend to split the DataSET (row-wise) into three sub-sets:

aTrainingDataSET: having some 60%-70% of the records ( observation pairs )
aTestingDataSET: having some 20%-30% records
aCrossValidationDataSET: having some 20%-30% records ( not seen in the training phase )

This gnostically-fair method allows you to assume, how well the trained-ANN "generalised" it's ability to handle not only the examples it was trained for, but also to handle the not-in-data examples ( where you know a-priori the correct result, otherwise you were not able to fulfill your SUPERVISED learning role ), which detects your AI-learner's ability to survive the real world "evolution(s)" not contained in your first few examples ( from aTrainingDataSET ).
So, feed your ANN-learner with the training part of the DataSET to find the ( ideally convex ) minimiser-driven optimum/threshold output ( ANN-settings ).
Test the pre-trained ANN-learners with different [C,gamma] non-DataSET-related settings against aTestingDataSET to find "how precise" are the ANN-model predictions over [C,gamma] landscape of the ANN-model.
Finally, evaluate the "best"-tuned [C,gamma]-adjusted learners ( so far the candidates, that best reflect both aTrainingDataSET & aTestDataSET ) how well these will predict answers on aCrossValidationDataSET, which neither of 'em was exposed to smell so far [ this part of your SUPERVISED ( pre-rated ) experience was not shown to 'em  just for this very important possibility ].
This way you may manage your ANN-model to escape from the traps of both "high-bias" / "overfitting", the two principal black-holes a trivial (mathematically) formulated "penalty"-based minimiser will have no other chance but to run your ANN-model into.
Ad [d]
In the sense of the above methodology, a CrossValidation prediction errors ( a penalty function ) is calculated from any pre-trained, [C,gamma]-adjusted ANN-learner once being exposed to aCrossValidationDataSET.
Ad [e]
There are many marvelous hands-on courses on ANN/ML, so do not hesitate to join and visit.

If you ever would have a chance to re-run any lecture / course from prof. Andrew NG, be it from his Stanford, Coursera or his recent AI/ML-Lab phase of his immense efforts in popularisation of this practical use of the ANN-learners, there would go my choice No.1 to follow.

UPDATE

Ad an Add-On question on sizing of aTrainingDataSET

Supposing the statement about having -5- training examples ( in the question/comment below ) available for a training process of the ANN is correct, there seems to be a problem in case, there are some principal restrictions to have more potent DataSET ( larger base of SUPERVISED learning examples ).
Typical ANN "consumes" a lot of training samples so as to allow it's minimiser-based algorith evolve and stabilise it's best performing internal settings ( the operating principle of the ANN-s ), thus maximising it's ability to answer ( predict ) questions as close to the correct answer as possible.
While there might be some value in just -5- [example-answer] pairs, it is too few to train an ANN-based learner so as to serve it's future task ( predictor-role ).
Try to acquire / generate / prepare a more robust DataSET for this initial process of developing a solid ANN-based predictor.
Comment: Thank you for your answer. It's the first time I've done something with ANN I'm not sure If I understand correctly. My program includes a set of training inputs and training outputs. My network is trained (loop) until it has achieved a specific target. For example I have 5 inputs (x1,y1) and 5 target outputs (tx1,ty1). I don't know how many times my train function will repeat until the expected target. How can I divide the data into the 3 sets? (train, validation, test).
Comment: I need reputation 15 to give an upVote.
Comment: Be patient, George, you will have it soon. Enjoy the subject in the meantime -- what ANN-architecture do you employ { inputNODEs : hiddenLayer1NODEs : hiddenLayer(2+)NODEs : outputNODEs } w/wo biasNODEs and how does a sample of your SUPERVISED learning examples/answers look like?
Comment: My program is very simple and I'm not using Hidden layers. I'm using a learning rate to control the training process. (Lower value avoid  overfitting but increases the number of training loops). Moreover I'm using the "momentum" variable to smooth the training process by adding a portion of the previous backpropagation into the current backpropagation
Comment: Is there any specific formula to calculate validation error?


THe correct way to install wordpress on ec2 instance Amazon like BiTnami package

Question: I've searched and tested multi-tutoriels about installing wordpresson ec2 instance in amazon AWS, but i always find problems with the final product, first MySQL it does not accept utf8_unicode_ci, than the sample data (.xml files) i upload them but dont extract instead the files goes to media as (sampledata.xml_.txt) !!!
So i am hoping to find a solution here to install wordpress the correct way like the package of Bitnami that worked perfectly with no problems but the fees are to much for me so i prefer to do it automaticly.
Regards.
Answer: What fees? :) You can launch the Bitnami AMIs for free directly from your account or from the AWS marketplace


Mathematical curve to represent a contour plot of a bimodal distribution in two dimensions

Question: I am attempting to find a mathematical curve $f(x,y)$ that describes approximately the contour plot of a bimodal constructed from two Gaussian distributions centered at $(0, \pm y_0)$ and $\sigma = 1$.
The curve $f(x,y)$ should resemble an ellipsis for points near and far away from $(0, \pm y_0)$ and transform into a type of Lemniscate for points in between.
As an example, see the following picture with $y_0 = 1.3$:

Code to generate the image:
<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter

#Draw the bimodal distribution
N = int(1e8)
y_0 = 1.3
rng = np.random.default_rng(1)
x_g = rng.normal(size=2*N)
y_g = np.concatenate([rng.normal(loc = y_0, size=N), rng.normal(loc = -y_0, size=N)])

#Bins
x_max = 3
Bins_x =  np.linspace(-x_max, x_max, 100)
Bins_y =  np.linspace(-x_max, x_max, 100)
binCenter_x = (Bins_x[1:]+Bins_x[:-1])/2
binCenter_y = (Bins_y[1:]+Bins_y[:-1])/2

#Construct histogram
z_counts, edges  = np.histogramdd((x_g, y_g), bins = [Bins_x, Bins_y])

#Plot
im = plt.pcolormesh(binCenter_x, binCenter_y, z_counts.T, cmap = 'plasma_r', zorder = -1,rasterized=True)#,  norm = LogNorm(vmin=1, vmax=np.max(z_counts)))
plt.contour(binCenter_x, binCenter_y, gaussian_filter(z_counts, sigma=0.5).T, levels=10)
plt.colorbar(im, label = 'Counts')
plt.gca().set_aspect(1./plt.gca().get_data_ratio())
plt.xlabel('x')
plt.ylabel('y')
plt.savefig('bimodal.png', dpi = 300)
</code>
Comment: Why $\sigma=0$? From the code it looks like $\sigma=1$
Comment: @Andrei You are right, is $\sigma = 1$. I changed it now.
Answer: The curves you are describing are conceptually identical to the Cassinian oval, as described in A Catalog of Special Plane Curves, J. Dennis Lawrence, Dover, 1972, pp. 153-154. A description can also be found here.
The Cartesian equation of these curves is given by
$$
(x^2+y^2+a^2)^2=b^4+4a^2x^2
$$
and the polar equation is
$$
r^4-2a^2r^2\cos2\theta=b^4-a^4
$$
These curves have the property that if $a=b$ the oval is lemniscate of Bernoulli. If $a<b$, there is one loop, and if $a\ge b$, two loops. The only difference between your curves and these is a $90^{\circ}$ rotation.
Comment: Amazing, thank you!
Comment: @Cye Waldman: Cassinian Ovals are loci of constant product of distances from two foci. How are they related to  bimodals of two Gaussian distributions?
Comment: @Narasimham That's a good question, but, unfortunately, beyond my ken. I was merely giving the OP an opportunity to fit the data to a known curve set with the correct behavior.


how to rewire 3 way switch

Question: I just moved into this house. There's a 3 way switch that I can't figure out how to rewire it.When I turn it on at the bottom of the stairs, I can turn it off at the top of the stairs. But after doing that it won't be able to turn back on at the bottom of the stairs unless I switch it back on at the top of the stairs. I included a picture of how previous owner wired it, also a picture of all the  wire combinations I tried.
"Not Work" - lights won't turn on.
"Worked"- light will turn on but still the same problem. So I hope someone can tell me how to rewire it. Thanks
Comment: How did you identify the common wire? Actually seeing a black screw, or inference based on screw position?  Wire colors are semi-meaningless ..  but very meaningless in 3-ways.
Comment: Have you tested both switches? the comm should connect to one terminal in one position and the other terminal in the other position.
Comment: T: top switch  B: bottom switch   Isn't the Black wire always suppose to be on the common terminal?
Comment: Use a multimeter.
Comment: Do you have a multimeter?
Comment: No I don't have a multimeter. Basically you can say I played musical chairs with the wires. First Idisconnected both switches, then I just rewired one switch to see which wire is the HOT wire.  Then I rewired both of them. The results was both light switch will only turn on when the RED wire is directly across from the BLACK wire.
Comment: The Big Yellow wire in Switch 1, I know for sure that is the wire from the light. So the HOT wire on the common screw should be correct.   I'm guessing this, is the problem lying on the  wire on the right side where the black and red wire is wire nut to the black wire. That wire on the Right side should be the wire for the 2nd switch
Comment: I think it's time to check all other junction boxes that could possibly be related to this circuit, to see what the other end of these /3 cables might be doing.
Answer: Several wires in a sheath is called a cable.  The difference gets important fast.
Traveler wires
First, it's time to stop the dizziness and confusion with the travelers.  You should not have to play musical chairs with travelers.  (It's not hazardous so as long as you are only exchanging the wires which belong on the 3-way, but it's a stupid waste of time).  And to save us trouble later, let's mark the travelers; I recommend yellow tape, but if that color is already assigned, just use blue.  Mark both travelers the same color, there is no need to distinguish them from each other.
This will always be true about travelers:

There is no wire-color standard. Really. That's why we mark them!
Both traveler wires are in the same /3 cable
Both traveler wires go to the 3-way switch
In the same /3 cable, travelers stay the same color. We don't have "crossover cables" in mains electrical.
However if the /3 cable is spliced somewhere, all bets are off.

So. In box 2, all 3 wires go to the switch, so that's no help at all.  However in box 1's left /3 cable, red and white go to the switch.  Gotcha!
Red and white get marked yellow (or blue if you prefer).  In switch #1 box, and also switch #2 box, unless you have reason to believe the cable is spliced somewhere else.
Identifying the common screw terminal
You've talked a lot about screw positions and never about screw colors.  On 3-ways, screw positions are meaningless. Screw colors matter.  The common screw is black, the traveler screws are brass/yellow.
Now we've identified the traveler positions by logic, and identified the traveler screws by color.  There is only one way this can possibly connect, and it must work. Unless:
A third 3-way (4-way), or splice in a lamp box?
Remember the part where I said "if the /3 cable is spliced in another box, all bets are off"?   That could happen in a lamp box, or the site of a current or former 4-way switch. There's no substitute but to search every possible box for this.  You'll recognize it when 2 wires from a /3 cable are spliced to 2 wires from another /3 cable. (Not counting grounds).
In that case, the traveler principles still apply, but you have to figure out which cable is which amongst several white /3 cables coming into that intermediate box.  ...and this, this is why I advocate marking travelers with colored tape.
There's one more possibility.  Here, we presume the left /3 cable connects to box 2.  What if it's actually the right /3 cable??? That would make this whole thing a bodge job of considerable proportion, but it would explain a lot. The troubleshooting here might be beyond you, and it might be time to bring in a handyman.
Comment: I added a clearer picture, you mention splicing.  Box 1 The cable on the right, the black and red wire is that considered spliced?
Comment: @oliveoil10 splicing is any joining of 2 or more wires.  You showed 3 splices in your earlier diagram and four in your latest, since you are showing the red/black tape join as separate from the wire nut.   The tape join is illegal and unsafe, and should be undone and redone with a wire nut.  Tape has no place in splices.  It may hide something that is not a splice, like the capping off and termination of the red wire and merely taping it against the insulated black wire. Tape clumps are illegal *least* because they're hard to inspect. But mainly, they make poor connections.
Comment: I think previous owner taped the wires together because they were too short so that is why another black wire was attached to it then to the wire nut.
Comment: Assuming  switch 1 the connection of the wires is correct, If the cable on the left is connected to switch 2, is the placement of the wires correct?
Comment: @oliveoil10 I cannot possibly say, because I don't know which screws are black and which are brass.  Position means absolutely nothing on 3-ways.  Every make and model of switch randomizes where they put common vs travelers, even two switches of the same SKU may be different.
Comment: I labeled it in the picture. The common screw is on the bottom right.
Comment: ***How do you know that?*** Not to be obtuse, but this whole problem  turns on the proper identification of common, and nothing you have said suggests that you have any idea how to do that.  Even if it's an "of course/obviously" I'd really like to hear it from you, to make sure we are on the same page.  Also, in the "unmentioned" department... are these smart switches, dimmers, anything other than a plain old $1.30 3-way?
Comment: I know that is the Common because the screw is black and when I took out the light switch "common" was written on the back behind  the black screw. Anyways thanks for your help, but  my guess was right, the cable on Right does lead to switch 2, I swapped the wires and now everything is working
Comment: @oliveoil10 thanks, that's the "obviously" I just needed to make sure of, and yeah... That cable on the right *has* been lingering in this story like Chekhov's Gun, I'm not surprised it's the crux of the problem.  The too-short issue is very worrisome. The wires need to come out beyond the wall 3" to be Code.

how to rewire 3 way switch


Stealing my own powerarmor

Question: Ok, so I got a powerarmor suit from far harbor, a few hours later I put Nick in it, and about 2 hours have past since he got in. Now whenever I tell him to get out and he does, it says "Steal", I dont understand why. It's not like i stole it from anyone else, so I don't get why it says that.
Answer: There are only a handful of unclaimed power armors in the game, and those are usually locked up or hidden. You can also buy an unlimited frames from vendors.
You can't loot it from dead bodies.
If you shot the fusion reactor (bandit or BoS), it is still "owned" by whoever that was using it, and stays that way permanently. Even if they were forced to leave their power armor via the console, the armor is still owned by them.
It most likely was stolen to begin with and you didn't notice. It is best to use another power armor frame and let Nick keep that stolen one. You can, however, "steal" the parts off the frame and if they were not stolen, it doesn't register as stolen parts.

Stealing my own powerarmor


Wordpress post image (details) default class

Question: I want to set a default class for all images in a single post eg. they have a red border. How do i do that? Something like on http://net.tutsplus.com
Answer: You can apply the div containing the post an id attribute equal to the id of the post and use
#post-[id] img { border:1px solid red; }

Comment: That will only work for that specific post. It will not work for all posts. If you want to use it for all psots, then maybe add a div container that wraps the post and give that an ID.
Answer: There's a filter named get_image_tag_class that should give you the access you need if you're using built in functionality to place images.


Codeigniter database error using between clause

Question: I am getting a database syntax error from codeigniter and its generating this sql query.
SELECT `code`, `latitude`, `longitude` FROM (`postcodes`) WHERE `latitude` `BETWEEN 55`.`8616 AND 56`.`1508` AND `longitude` `BETWEEN '-3`.`9507' AND '-3`.`6131'` AND `code` LIKE 'FK%'

I think I can see the problem its adding '' where they should not be in the longitude and lqatitudes.
The code thats generating this query is:
 function get_zips_in_range($zip, $range, $sort=1, $include_base=true)
{
    //get base postcode details
    $details = $this->get_zip_point($zip);

    if( ! $details)
    {
        return false;
    }

    //get the first 2 letters of the postcode
    $str = substr($zip, 0, 2);

    //find max - min lat / long for radius and zero point and query
    //only zips in that range.
    $lat_range = $range/69.172;
    $lon_range = abs($range/(cos($details->latitude) * 69.172));
    $min_lat = number_format($details->latitude - $lat_range, "4", ".", "");
    $max_lat = number_format($details->latitude + $lat_range, "4", ".", "");
    $min_lon = number_format($details->longitude - $lon_range, "4", ".", "");
    $max_lon = number_format($details->longitude + $lon_range, "4", ".", "");

    //build the sql query
    $this->CI->db->select("code, latitude, longitude");

    if( !$include_base)
    {
        $this->CI->db->where("code <>", $zip);
    }

    $this->CI->db->where("latitude BETWEEN '$min_lat' AND '$max_lat'");
    $this->CI->db->where("longitude BETWEEN '$min_lon' AND '$max_lon'");
    $this->CI->db->like('code', $str, 'after');
    $result = $this->CI->db->get("postcodes");

    if($result->num_rows() < 1)
    {
        $this->set_last_error("SQL error in get_zips_in_range");
        return false;
    }

Comment: it seems to be adding single quotes around the points in the lon/lats like so
Comment: See also the canonical: [using BETWEEN in WHERE condition](https://stackoverflow.com/q/9941521/2943403)
Answer: There is a bug in CI 2.1.1 https://github.com/EllisLab/CodeIgniter/issues/1469
Reverted to 2.1.0 is the best solution until 2.1.2 comes out
Answer: Well, check out following thing,
$this->CI->db->where("latitude BETWEEN $min_lat AND $max_lat");
$this->CI->db->where("longitude BETWEEN $min_lon AND $max_lon");

apart from syntax, it will be rendered as where latitude BETWEEN $min_lat AND $max_lat AND longitude BETWEEN $min_lon AND $max_lon
Now you will ask what is the problem..
The problem is in query the way we are making it
It can be done as follows
$this->CI->db->where("(latitude BETWEEN $min_lat AND $max_lat)");
$this->CI->db->where("(longitude BETWEEN $min_lon AND $max_lon)");

So it will be rendered as where (latitude BETWEEN $min_lat AND $max_lat) AND (longitude BETWEEN $min_lon AND $max_lon) and hopefully this will solve the problem.
Even there is no need to quotes.
Answer: CodeIgniter automatically adds backticks to make safer queries. If you want to disable this, you can add the parameter FALSE as follows:
$this->CI->db->where("latitude BETWEEN '$min_lat' AND '$max_lat'", FALSE);

Answer: $this->CI->db->where("latitude BETWEEN '$min_lat' AND '$max_lat'");
$this->CI->db->where("longitude BETWEEN '$min_lon' AND '$max_lon'")

remove the simple '
$this->CI->db->where("latitude BETWEEN $min_lat AND $max_lat");
$this->CI->db->where("longitude BETWEEN $min_lon AND $max_lon")

Comment: your query looks ok, can you put the tables structure and some data in sqlfiddle.com to make test?
Comment: Just tried it the error remains: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`BETWEEN 55`.`8616 AND 56`.`1508` AND `longitude` `BETWEEN -3`.`9507 AND -3`.`61' at line 3

SELECT `code`, `latitude`, `longitude` FROM (`postcodes`) WHERE `latitude` `BETWEEN 55`.`8616 AND 56`.`1508` AND `longitude` `BETWEEN -3`.`9507 AND -3`.`6131` AND `code` LIKE 'FK%'
Comment: can you print the complete query to see how it looks like?
Comment: SELECT `code`, `latitude`, `longitude` FROM (`postcodes`) WHERE `latitude` `BETWEEN 55`.`8616 AND 56`.`1508` AND `longitude` `BETWEEN -3`.`9507 AND -3`.`6131` AND `code` LIKE 'FK%'
Comment: The query is ok as it works a direct sql query the problem is that ci is putting single quotes around the point in the numbers but its not showing that when I paste the query in here instead of 56.1508 the ci query is 56"."1508.
Comment: Have you recently upgraded to 2.1.1? There was a bug in the DB_driver, fix available here: http://codeigniter.com/forums/viewthread/219130/
Comment: Note 2.1.1 has been re-released with this bug fixed: https://github.com/EllisLab/CodeIgniter/issues/1469 so just download and update!
Comment: just wondering, do you fixed? is nice to know that there are a lot of bugs and how to solve it ;)


How to rowwise select random elements in a tibble via dplyr in R?

Question: I'm having some DNA data (alleles) for say 3 people, each row representing a SNP. In order to get some shareable test data, I would like to rowwise randomly sample data into a new tibble to get some fake DNA data which doesn't represent a real person.
For example, my initial tibble, data, could looks like this:
person_1,   person_2,   person_3

AA,         AG,         GG (i.e. data from person_1   person_2   person_3)

AC,         CC,         AC (i.e. data from person_1   person_2   person_3)

..         ..         ..

I would like the result to be like this:
random_1,  random_2,  random_3

GG,         AA,        AG (i.e. randomly assigned to person_3, person_1, person_2)

CC,         AC,        AC (i.e. randomly assigned to person_2, person_3, person_1)

...

I'm already able to do this with the following code:
data %>%
  split(f = 1:nrow(.)) %>%
  purrr::map_dfr(~ .x[,sample(1:ncol(.x),ncol(.x))] %>%
                   rename( setNames(object = names(.),
                                    nm = paste0("test_",sprintf("%02d", 1:length(.))))
                   )
  )

However, my challenge is that my tibble has more than 700.000 rows, which makes the code above extremely slow. I have tried to do the operation via mutate(), rowwise() and across from the dplyr package, but I have been unsuccessful.
Any suggestions for other approaches that are faster?
Comment: By elements do you mean observations/rows?
Comment: I mean observations in each row - so I wish, for each row in my tibble, to return a new row of the same length as the original row, but where the observations in the new row is randomly sampled from the old row. And then repeat this for every row in the tibble. Hope this makes sense (I have tried to clarity this via the example above)
Answer: We can use pmap (from purrr) with sample.
library(dplyr)
library(purrr)
library(stringr)
df1 %>%
    pmap_dfr(~ sample(c(...))) %>%
    rename_all(~ str_c('random_', seq_along(.)))

-output
# A tibble: 2 x 3
#  random_1 random_2 random_3
#  <chr>    <chr>    <chr>
#1 AG       AA       GG
#2 CC       AC       AC

Or another option is to reshape to 'long' format, do a group by slice_sample and then reshape back to 'wide'
library(tidyr)
df1 %>%
   mutate(rn = row_number()) %>%
   pivot_longer(cols = -rn) %>%
   group_by(rn) %>%
   slice_sample(prop = 1) %>%
   mutate(name = str_c('random_', row_number())) %>%
   ungroup %>%
   pivot_wider(names_from = name, values_from = value)
# A tibble: 2 x 4
#     rn random_1 random_2 random_3
#  <int> <chr>    <chr>    <chr>
#1     1 AG       GG       AA
#2     2 CC       AC       AC

There is an option to use rowwise, but, it would be less efficient assuming the number of rows are 700000
df1 %>%
   rowwise %>%
   transmute(col1 = list(sample(c_across(everything())))) %>%
   unnest_wider(c(col1), names_repair =  ~ str_c('random_', seq_along(.)))
# A tibble: 2 x 3
#  random_1 random_2 random_3
#  <chr>    <chr>    <chr>
#1 AG       AA       GG
#2 CC       AC       AC

In base R, this can be done using apply
out <- as.data.frame(t(apply(df1, 1, sample)))
names(out) <- paste0('random_', seq_along(out))

data
df1 <- structure(list(person_1 = c("AA", "AC"), person_2 = c("AG", "CC"
), person_3 = c("GG", "AC")), class = "data.frame", row.names = c(NA,
-2L))

Comment: @aleksandereiken You could make it faster if you can split the data into multiple chunks based on some `n` number of rows and use `foreach` on each of those chunks in parallel
Comment: Thanks a lot. The purrr solution is very elegant! And it does for sure run faster than my own solution, however it still runs for 5-7 minutes on my 4 core mac to do the computation with 700.000 rows and across 16 columns. Maybe that's a fair run time. Thanks again for your help!


Giving permissions to user doesn't work in MySQL

Question: I executed this in phpMyAdmin.
I executed these lines:
CREATE USER root IDENTIFIED BY PASSWORD '';

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

I get this when trying to connect:

Connect failed: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

$dsn = 'mysql:dbname=one';
$user = 'root';
$password = '';
$pdo = "Not set";
try{
    $pdo=new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch(Exception $ex){
    echo "Connect failed: " . $ex->getMessage();
}

Note that the connection above used to work..now it doesn't (since I switched to XAMPP).
Comment: I tested it again and i got this:host=127.0.0.1 . it works with number but doesnt work with localhost. However, when i get to the localhost i get to it like this: localhost:82 . could that be the reason that it didnt work..cause i didnt include the port number..and when i approach it with an ip it works?
Comment: Why are you creating the user `root`? It should always exist anyway, so there's no need to create it.
Answer: Are you sure that the root user doesn't have a password? Do you have  PhpMyAdmin installed to check this?
If the problem isn't the privileges, then it's probably the port. The default port of MySQL is 3306, so if your port for MySQL is now 82 that you have to add the port in the connection.
Answer: Please, check create user specification, seems you should use another syntax for account name

Syntax for account names is 'user_name'@'host_name'.

So, something like  CREATE USER 'root'@'localhost' IDENTIFIED BY PASSWORD '';.
In your case CREATE USER 'root'@'%'; but I really did not recommend use '%' for root user.
Comment: I think it is something to do do with the port ..i think I should connect with localhost:82, instead of localhost
Comment: localhost and 127.0.0.1 are similar, so, if your connection work with 127.0.0.1 it's enough.
Comment: also, if it not help, please, check http://stackoverflow.com/questions/1435445/error-on-creating-connection-to-pdo-in-php approved answer. Those answer has useful information of different DSN which used while we try to connect to DB via PDO
Answer: Are you flushing privileges after altering permissions?
You should execute FLUSH PRIVILEGES; to tell the server to reload the grant tables.
Answer: The host % does not apply to localhost. You need to grand permissions for localhost separately.

Giving permissions to user doesn’t work in MySQL


$\iint f(x)g(y)dxdy =\int f(x)dx \int g(y)dy $ Why?

Question: $\iint f(x)g(y)dxdy =\int f(x)dx \int g(y)dy $ . How could this be proven I tried this with Fubini, so on the LHS we can think of $g(y)$ as constant and take it out of the integral and in the following step we can think ok $f(x)$ as a constant such. In other word $\int g(y) \big[\int f(x)dx\big]dy=\big[\int f(x)dx\big]\int g(y)dy$.
But I do not know how to come from $\int f(x)dx \int g(y)dy \Rightarrow\iint f(x)g(y)dxdy $ pls help
Comment: I really do not understand why i do get a downvote, if it is so trivial why does the person not answer ??
Comment: I downvoted because I found the question confusing. The question itself, trivial or not, is interesting.
Comment: If the question is interesting so why a downvote ?
Comment: As I said, I found it confusing. Maybe it's because I'm in mobile, but the equations seemed "strange". It's better now after Masacroso's edit, so I will remove the downvote.
Comment: ah ok could be the case sometimes mobile sucks on desktop everything seems legite
Answer: Both expressions are the same. Note that
$$\iint f(x) g(y)\, dx\, dy=\int g(y)\left(\int f(x)\, dx\right)\, dy$$
because $g(y)$ is a constant for each $y$ in the inner integral. Now call $A:=\int f(x)\, dx$, then $A$ is a constant, assuming that the integral converges, and from above we knows that
$$\int g(y)A\, dy=A\int g(y)\, dy=\left(\int f(x)\, dx\right)\left(\int g(y)\, dy\right)$$
Revert the steps for the other direction of the proof (start by naming $A:=\int f(x)\, dx$ and put it inside of the other integral).
Comment: so my explanation was correct ? But would you agree that showing RHS is equal to LHS is more difficult then showing LHS is equal to RHS meaning that $\left(\int g(y)\, dy\right)\left(\int f(x)\, dx\right)=...=\int\int f(x) g(y)\, dy\, dx$
Comment: meaing that $\int g(y)\left(\int f(x)\, dx\right)\, dy = \int (g(y)\left(\int f(x)\, dx\right)\,) dy=\int \left(\int f(x) g(y) dx\right)\, dy$
Comment: But how are the breakets rules within an integral ? is $\int c(f(x))dx=\int cf(x)dx==\int (cf(x))dx$
Comment: ok, I think that what confuse you is the notation $\iint f(x) g(y) dx dy$. The notation is **defined** as $$\iint f(x)g(y)\,dx\, dy:=\int\left(\int f(x)g(y)\, dx\right)\, dy$$ Then, because $g$ is constant in the inner integral, then you can move out of the integral and also out of the bracket
Comment: yes, it holds that $$\int c(f(x))dx=\int cf(x)dx=\int (cf(x))dx$$ Here brackets (parenthesis) doesn't do something. If you are asking this kind of thing you really need a course in analysis, start by the integral of Riemann, and after take a look at the definition of the integral of Lebesgue as a limit of simple functions
Comment: yeah i know i was just asking for wheather it is ok genereally to put breackets such that $\int c(f(x))dx=\int (cf(x))dx$ do have the same meaning otherwise im ok with all the stuff. At first glance this did not seem trivial to me but after checking it was ok. But I think in general you have to be care full as $\int f(x)+g(x)dx $ is linear but same does not work for $\iint f(x)+g(y)dxdy \ne \int f(x)dx+\int g(y)dy$


Suppose $f(x)$ is differentiable in $[0,2]$.$f(0)=1,f(2)=3$.It is given that $|f'(x)| \le 1$ for all $x \in [0,2]$.Find $f(x)$ in $[0,2]$.

Question: Suppose $f(x)$ is differentiable in $[0,2]$.$f(0)=1,f(2)=3$.It is given that $|f'(x)| \le 1$ for all $x \in [0,2]$.Find $f(x)$ in $[0,2]$.
If I assume $f(x)$ to be linear, then, I get $f(x)=x+1$ which satisfies the conditions.
Are there more functions?
Comment: I think you should take $f(x)=2x+1$.
Comment: sorry edited the question
Answer: There is no other function.
Hint. Consider $g(x) = f(x)-x-1$. If $g(c)> 0$ for some $c\in (0,2)$, then the mean value theorem would imply there is some $0<d<c$ such that $g'(d)> 0$.  What can we say about $f'(d)$? What happens if $g(c)<0$ for some $c$?
Answer: Here is another proof by contradiction:
For each $x \in (0,2)$ you have
$$f(x) - 1 = f(x) -f(0)=f'(\xi_x)(x-0) = f'(\xi_x)x \mbox{ with } \xi_x \in (0,x)\stackrel{|f'(x)|\leq 1}{\Rightarrow} |f(x) - 1| \leq x$$
Now, assume there is $c\in(0,2)$ with
$$f(c) -1 < c \Rightarrow f(c) < c+1$$
Then, there should be a $d \in (c,2)$ such that
$$\color{blue}{f'(d)} =\frac{f(2) - f(c)}{2-c} \color{blue}{>} \frac{f(2) - c -f(0)}{2-c} = \frac{3 - c - 1}{2-c} = \color{blue}{1}$$
This is a contradiction to $|f'(x)|\leq 1$ on $(0,2)$. It follows
$$f(x) = x+1$$


Diablo II Resurrected - Battle.net connection problem

Question: Today I downloaded the beta of Diablo II Resurrected on the PS4 platform. On PSStore it was available for free to download.
Finally, the game was downloaded in my console, but if I try to run it, I get a warning about Battle.net connection problems. It's surprising, because I have connected the PSN account with Battle.net.
Is it any bug with the beta version of the game or it has to be purchase and this is the reason of connection's fail?
Answer: That is because D2: Ressurected is not released yet.
It releases on the 23rd of September. The servers will not be available before then.
But why is it on the store and can be booted? There is a Beta coming this weekend, starting on the 20th.

Following the Early Access weekend, on August 20 at 10:00 a.m. PDT, the Open Beta weekend will be open to everyone on a supported platform.

https://news.blizzard.com/en-us/diablo2/23688836/play-diablo-ii-resurrected-during-the-early-access-and-open-beta
Comment: That is very probable. Since its not the official release I guess PSN didn't bother to do a block to prevent booting since, well, you won't get far if the servers don't respond.
Comment: Ahh, so it is unable to play, because beta will begin on 20 August, but the client was published to download some days before that, right? It makes sense for me, so I am glad that you helped me with solving this mystery :)
Comment: This was the right solution - beta was not launched then :)


Using breakpoints in Xcode

Question: I'm using the debugger to pause execution of my program at any time and view the state of the running code, so I set breakpoints before running my executable so that I can stop at known points and view the values of variables in my source code.

After I viewed my code, it comes to one new screen. Here I press "step over" button means it come to view the next line, if I press "Continue program execution" button means then it skipped the step by step execution and comes to execution part. Image shown below.

My doubt is, why the compiler come here after viewed my code? How to analyse this assembly language coding and what is the purpose of this code?
Answer: If you pause execution or a breakpoint is triggered, the debug area opens, displaying the values of variables and registers plus the debug console. You can use the buttons at the right end of the debug area toolbar to display both the variables and console panes or to hide either one.
The variables pane displays variables and registers. You specify which items to display using the pop-up menu in the top-left corner of the variables pane:

Auto displays only the variables you're most likely to be interested
in, given the current context.
Local displays local variables.
All displays all variables and registers.

Use the search field to filter the items displayed in the variables pane.
The console pane displays program output and lets you enter commands to the debugger tool. You specify the type of output the console displays with the pop-up menu in the top-left corner of the console pane:

All Output displays target and debugger output.
Debugger Output displays debugger output only.
Target Output displays target output only.

Use these to understand what is happening at break points.
Answer: Maybe your code casted exception and goes back to [UIViewController loadViewIfRequired] method . This method is in the compiled program and it is binary now so you won't see the source code and the assembly language is presented instead.
It is possible that [UIViewController loadViewIfRequired] has exception handling code.

Using breakpoints in Xcode


Persist collection in object with MyBatis

Question: I have POJO classes:
class Ticket {
    private int id;
    private double cost;
    private Date time;
    private List<Place> places;

    // Getters and setters here
}

class Place {
    private int row;
    private int place;

    // Getters and setters here
}

Then I create one ticket and some places:
Ticket ticket = new Ticket();
ticket.setCost(58.7);
ticket.setTime(new Date());

Place place1 = new Place();
place1.setRow(1);
place1.setPlace(2);
ticket.addPlace(place1);

Place place2 = new Place();
place2.setRow(3);
place2.setPlace(4);
ticket.addPlace(place2);

And now I want to save it to DB:
session.insert("insertTicket", ticket);
session.commit();

In MapperConfig.xml I write this lines:
<insert id="insertTicket" parameterType="Ticket">
    INSERT INTO tickets (cost, time) VALUES (#{cost}, #{time})
</insert>

How I can save List places in automatic mode?
Does MyBatis can save it for me?
Or I need to iterate manually with foreach and insert every Place by hand?
Thanks for any help.
Answer: Even though MyBatis is able to support the reverse direction (i.e. filling the list during a query with a nested select or from a join), there is no automatic mode that inserts the containing list into the database.
According to this Google Groups discussion you have to insert the list elements manually.
Comment: MyBatis actually _is_ smart. But it is not intended to be a ORM. It's only meant as a thin wrapper around JDBC. If this functionality is a requirement then you can look for a ORM like Hibernate http://www.hibernate.org/ or EclipseLink http://www.eclipse.org/eclipselink/ .
Comment: Hm. Not good... I think MyBatis smarter. Is exist ORM for Java that can do this operation for me?


Can "ubuntu-12.04.3-server-amd64" be installed on a work station with Intel Xeon CPU?

Question: everyone!I want to install 64-bit ubuntu on our work station, but the downloaded iso file have an extension of "AMD64", and our work station has a CPU of "intel Xeon(E5540 2.53GHz*4)". Can I install the downloaded "ubuntu-12.04.3-server-amd64" on our work station?
Any answer would be appreciated.
Thanks.
Comment: Don't see why not. AMD64 is part of the name, and is a convention, rather then extension.
Answer: According to http://ark.intel.com/products/37104/, your workstation is 64-bit, and AMD64 refers to the file being for a 64-bit machine. So, most likely your installation will work. If there are problems with the installation, it won't be because of "AMD64".
The extension of your file should be .iso if you are burning it to a disc or USB drive.
Comment: Just as your prediction, I have installed 64-bit ubuntu on our work station. Thank you very much!
Comment: If this answered your question, please accept my answer to mark your question as answered.


Positioning Canvas in relation to the title bar of the window

Question: I have a graphic context:
gc.strokeText(String.format("%d",test), 0, 0);

I add this to the stage like this:
p.getChildren().addAll(canvas);

I get this result:

What can i do, or is there a way to prevent the canvas to start behind title bar?
(I can do this by setting the start position x,y, but that seems a oncomfortabel solution)
Is there a way to set the canvas just below the title bar, no matter how high this title bar is.
Thanks
Comment: [mcve] please - demonstrating what _exactly_ you want to achieve and how it doesn't work.
Comment: James_D anwsered it correctly, thus my question was clear enough.
Answer: The scene and the canvas it contains are positioned immediately below the title bar. The problem is the way you have positioned the text in the canvas.
The text is positioned in the canvas according to the coordinates provided and the current values of the GraphicsContext's textAlign property (which determines how the x coordinate is used) and textBaseline property (which determines how the y coordinate is used). See the "Text Attributes" section of the attributes table in the documentation.
The default textBaseline property is VPos.BASELINE, which means the baseline of the text will be positioned with the provided y-coordinate, which is 0 in your case. Thus the text baseline will be at 0 (the top of the canvas), and most of the text (everything except any descenders) will be above the top of the canvas and not be visible.
To position the top of the text at the y-coordinate 0, set the textBaseline to TOP:
gc.setTextBaseline(VPos.TOP);
gc.strokeText(String.format("%d",test), 0, 0);

Comment: Thanks @James_D, it works like a glove!


RMI server java.security.AccessControlException: access denied

Question: I'm building a RMI application and I have the following server class. However, when I run it in eclipse I get the following exception. What is wrong and how can I fix it? I've spent the last 2 days reading about similar problems online but I couldn't find the solution. I suspect it has something to do with a policy file, but I have no idea how to use one. Also if the problem is with the way I run it can you please give me directions for doing so in eclipse.
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

public class MyServer extends UnicastRemoteObject implements Interface {

    private static final int PORT = 2019;

    public MyServer() throws Exception {
        super(PORT, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());
    }

    public static void main(String args[]) {

        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        try {

            Registry registry = LocateRegistry.createRegistry(PORT, new SslRMIClientSocketFactory(), new SslRMIServerSocketFactory());

            MyServer obj = new MyServer();

            registry.bind("HelloServer", obj);

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void sayHello() throws RemoteException {
        System.out.println("Hello");
    }
}

--
access denied ("java.net.SocketPermission" "localhost:2019" "listen,resolve")
java.security.AccessControlException: access denied ("java.net.SocketPermission" "localhost:2019" "listen,resolve")
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkListen(Unknown Source)
    at java.net.ServerSocket.bind(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at java.net.ServerSocket.<init>(Unknown Source)
    at javax.rmi.ssl.SslRMIServerSocketFactory$1.<init>(Unknown Source)
    at javax.rmi.ssl.SslRMIServerSocketFactory.createServerSocket(Unknown Source)
    at sun.rmi.transport.tcp.TCPEndpoint.newServerSocket(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport.listen(Unknown Source)
    at sun.rmi.transport.tcp.TCPTransport.exportObject(Unknown Source)
    at sun.rmi.transport.tcp.TCPEndpoint.exportObject(Unknown Source)
    at sun.rmi.transport.LiveRef.exportObject(Unknown Source)
    at sun.rmi.server.UnicastServerRef.exportObject(Unknown Source)
    at sun.rmi.registry.RegistryImpl.setup(Unknown Source)
    at sun.rmi.registry.RegistryImpl.<init>(Unknown Source)
    at sun.rmi.registry.RegistryImpl.<init>(Unknown Source)
    at java.rmi.registry.LocateRegistry.createRegistry(Unknown Source)
    at MyServer.main(MyServer.java:27)

Answer: It's very simple.
access denied ("java.net.SocketPermission" "localhost:2019" "listen,resolve")

means that the policy file has to grant the permission
java.net.SocketPermission "localhost:2019", "listen,resolve"

or whatever the correct syntax is. Use the policytool to get it right. You may want to wildcard the port number. And you have to specify the location of the policy file via the java.security.policy system property. And when you get other access control exceptions, as you will in testing, you have to likewise add the corresponding permissions, until closure.
But I would rather ask why you're using a security manager at all. It isn't necessary unless you're going to use the codebase feature, which is fairly rare, and it isn't necessary in a server unless you're going to use the codebase feature to upload classes from the client, which is much rarer.


Driver installation stuck

Question: I am trying to install proprietary drivers for a printer (EPSON L355, driver: epson-inkjet-printer-201207w) on Ubuntu 14.04 by adding a new printer in Printers.
The installation is currently stuck and I have already hit the cancel button but nothing happens.
My question is, how to proceed when installation seems to be stuck? I do not wish to break anything but this has been stuck for hours. Should I kill the process? And how can I verify if everything is in order afterwards?
My question is similar to https://askubuntu.com/questions/309850/proprietary-drivers-installer-stuck-in-ubuntu-12-04 but I am trying to make it more general.
Comment: If it have been stuck for hours I would say there really isn't much to do but to kill it. Normally if something gets stuck I kill it within minutes and I have never personally experienced any issues afterwards in Ubuntu. I cannot say I have ever installed a printer in Ubuntu though, much less killed that program while it was running. Still, what are your options really, it's pretty much already dead if it has crashed.
Comment: possibly related: http://askubuntu.com/questions/415099/13-10-network-epson-printer-stuck-on-installing
Comment: Bug report: https://bugs.launchpad.net/ubuntu/+source/system-config-printer/+bug/1307917
Answer: For people who are getting this issue now, Seiko Epson Corp provides a free software printer driver package for Linux that supports a large number of Epson printers.
It's available to Ubuntu as printer-driver-escpr.
If you're currently stuck in the printer dialog, you can safely kill it.  Then you'll want to install a driver package manually, which should allow you to pick a local driver and avoid this issue.
Step 1: Clean up files so that we can install printer drivers without errors regarding debconf/config.dat being locked.
$ sudo rm /var/cache/debconf/*dat
Step 2: Install printer-driver-escpr.
$ sudo apt-get install printer-driver-escpr
Step 3: Start up your printer utility and select your printer.
Step 4: Choose to install a "Local Driver", select the model closest to your printer, and continue.
You should now be able to use your printer.  Verified on LXLE 14.04, derived from Lubuntu/Ubuntu 14.04 LTS.

Driver installation stuck


Gap between two Pythagorean triples

Question: Let $s$ and $t$ be two  positive integers. I am interested in the following Diophantine system :
$$\mathscr{S}(s,t) :
\left\{
\begin{array}{l}
x^2+y^2=a^2\\
(x-s)^2+(y-t)^2=b^2
\end{array}
\right.$$
where $x, y, a$ and $b$ are integers such that $x>s$ and $y>t$.
I would like to know for which couples $(s,t)$ the system $\mathscr{S}(s,t)$ has an infinity of solutions.
Have you encountered this question before? Do you have any references for me?
Thanks in advance.
► Edit : With the help of a computer program, I tested all the pairs $(s,t)$ with $s\leqslant20$ and $t\leqslant20$. In black, the only pairs $(s,t)$ such that $\mathscr{S}(s,t)$ does not seem to have a solution :
Comment: I recommend invoking the [parametrization of Pythagorean triples](https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple) to see if it helps. This gets rid of $a$ and $b$ and reduces the problem to a linear one in $x$ and $y$, at the cost of introducing some other variables.
Comment: The problem condition is not quite correct. In fact, these are two independent equations. $$x=p^2-k^2$$ $$y=2pk$$ $$t=p^2-k^2-r^2+q^2$$ $$s=2pk-2qr$$$ It is necessary to reduce the number of unknowns and write, for example, such a system. https://artofproblemsolving.com/community/c3046h1046682_1
Comment: https://artofproblemsolving.com/community/c3046h1047011__5
https://artofproblemsolving.com/community/c3046h1047131__7
https://artofproblemsolving.com/community/c3046h1048039__10
Comment: Sorry, my question is perhaps badly formulated. When $(s,t)$ is fixed, I would like to know when $\mathscr{S}(s,t)$ has an infinite number of solutions.
Comment: Rewrite the condition of the question in a different form. Most likely, the solutions will depend on the solutions of the Pell equation.
Comment: @uvdose I edited my answer adding what I hope is a workable solution to your problem.
Comment: The answer should be "NO".  The "even" case is proved in my answer.
Answer: I propose a full solution. I claim that all pairs $(s,t)$ allow for infinitely many solutions to the set of equations, except for those blacked out in the table attached to the question.
Suppose without loss of generality that $s \geq t$. I am going to make a case distinction based on the parity of $s$.
FIRST CASE: Suppose first that $s$ is even and write $s = 2k$. I will investigate under which conditions I can find infinitely many solutions with the explicit choice $b = a - t - 2$. Then, the system becomes
$$
x^2+y^2 = a^2 \quad \text{and} \quad (x - s)^2 + (y-t)^2 = (a-t-2)^2.
$$
This has the somewhat obvious solution
$$
(x,y,a,b) = ( 2k, k^2-1, k^2+1, k^2 - t - 1),
$$
that does not quite count as $x = s$ in this case. However, I will use it to generate infinitely many more solutions that do count. Expanding the second equation and substituting the first, we obtain
$$
x^2+y^2 = a^2 \quad \text{and} \quad 2a(t+2) + s^2 = 2xs + 2yt + 4t + 4.
$$
We now use the general solution to the Pythagorean equation to write
$$
x = 2uv, \quad y = u^2 - v^2 \quad \text{and} \quad a = u^2+v^2.
$$
With this, we have reduced to a single equation reading
$$
2(u^2+v^2)(t+2) + s^2 = 4uvs + 2(u^2-v^2)t + 4t + 4,
$$
or equivalently,
$$
4u^2 - 4suv + (4t+4)v^2 = 4t + 4 - s^2.
$$
One can rewrite this in the slightly more friendly form
$$
[ 2u - sv ]^2 + (4t + 4 - s^2)v^2 = 4t+4 - s^2.
$$
Writing $D = s^2 - 4t - 4$, this can be written very succinctly as
$$
\text{Nm}( (2u-sv) + v\sqrt{D} ) = -D.
$$
Using the solution to our original pair of equations, we can deduce the solution $(u,v) = (k,1)$ to the above equation. If $D$ would be a non-square and $D > 0$, then the group $\mathbb{Z}[\sqrt{D}]$ would have unit rank $1$, so multiplying our solution by any unit of norm $1$ would yield another solution. The infinitude of such units would then generate us our desired infinitude of solutions. One might worry that these solutions will correspond to $x < s$ or $y < t$, but in the limit, this does not happen. Indeed, when $u$ and $v$ grow, we see that $2u - sv$ must tend to $\sqrt{D}v$, which means that $u$ grows about as fast as $v \cdot (s + \sqrt{D})/2 \gg v$, implying that both $x$ and $y$ will grow as $u$ and $v$ do.
It remains to verify under which conditions my two claims are true. Firstly, since $s \geq t$, it holds that $D > 0$ as soon as $s^2 \geq 4s+4$, which certainly holds for $s \geq 6$. Secondly, suppose that $D$ is a square. Again since $s \geq t$, it holds that $D \geq s^2 - 4s - 4 = (s-2)^2 - 8$. Since also $D < s^2$, this only leaves the two possibilities $D = (s-1)^2$ and $D = (s-2)^2$. However, since $D$ is even, only the second case remains, which corresponds to the case that $t = s - 2$.
Suppose that $t = s - 2$ and apply the argument above with $t$ and $s$ swapped. As before, we are then done as soon as $D = (s-2)^2 - 4s - 4 = s^2 - 8s$ is positive and a non-square. It is positive as soon as $s \geq 10$. It is then also a non-square, as $D = (s - 4)^2 - 16$ and the only even squares with difference $16$ are $16$ itself and $0$.
Combining all the arguments above, we conclude that, if $s \geq t$ and $s$ is even, we can find infinitely many solutions as soon as $s \geq 10$, and if $s \in \{ 6, 8 \}$, we can find then for any $t \neq s - 2$.
SECOND CASE: Suppose now that $s \geq t$ and that $s$ is odd, so write $s = 2k+1$. This time, I investigate when I can find infinitely many solutions with the explicit choice $b = a - t - 1$. Indeed, I claim that the pair of equations
$$
x^2+y^2 = a^2 \quad \text{and} \quad (x - s)^2 + (y-t)^2 = (a-t-1)^2
$$
admits the again somewhat silly solution
$$
(x,y,a,b) = ( 2k+1, 2k(k+1), 2k^2+2k+1, 2k^2 + 2k - t).
$$
If we now use the substitutions the other way around,
$$
x = u^2-v^2, \quad y = 2uv \quad \text{and} \quad a = u^2+v^2,
$$
we can completely similarly deduce the equation
$$
[ (t+1-s)u - tv ]^2 + (2t + 1 - s^2)v^2 = (2t+1-s^2)(t+1-s)/2.
$$
to which the non-trivial solution $(u,v) = (k+1, k)$ exists. Again, this is a norm equation in the ring $\mathbb{Z}[\sqrt{D}]$, provided that $D = s^2 - 2t - 1$ is positive and a non-square. We again find infinitely many solutions and to ensure that $x$ and $y$ keep growing too, we must check the growth rate of $u$ with respect to $v$. If $t + 1 - s < 0$, we check that $u$ will grow at the same pace as $v \cdot (\sqrt{D} - t) / (s - t - 1) \gg v$, ensuring the correct growth as soon as $\sqrt{D} > s - 1$, or equivalently, $  t < s - 1 $, which is exactly what we assumed. It remains to check the cases that $s = t$ or $s = t + 1$. In the former case, we see that $u$ grows as $v \cdot (\sqrt{D}+t) \gg v$; we postpone the latter case momentarily, as it turns out we will use a different argument there.
Let us investigate when this happens. Firstly, since $s \geq t$, it holds that $D > 0$ as soon as $s^2 > 2s+1$, which happens as soon as $s \geq 3$. Secondly, suppose $D$ is a square. Again, since $s \geq t$, it holds that $D \geq s^2 - 2s - 1$. Since also $D < s^2$, this forces $D = (s-1)^2$ and as such, $t = s - 1$.
Suppose that we are in the case $t = s - 1$. Then we can use the strategy for even $t$ above, to conclude that we can still find infinitely many solutions as soon as $(s-1)^2 > 4s + 4$ and $D = (s-1)^2 - 4s - 4$ is a non-square. The first condition is satisfied as soon as $s \geq 7$ and for the second, we note that $D = (s - 3)^2 - 12$, and the only squares of difference $12$ are $16$ and $4$, which corresponds to $s = 7$.
Combining the above, we conclude that if $s \geq t$ and $s$ is odd, we can find infinitely many solutions as soon as $s \geq 7$, and if $s \in \{ 3, 5, 7 \}$, then we can do it too unless $t = s - 1$.
CONCLUSION: If one now carefully reads the two conclusions reached above, it follows that the only pairs $(s,t)$ with $s \geq t$ for which we could not possibly find infinitely many solutions are:
$$
(1,1), (2,1), (2,2), (3,2), (4,1), (4,2), (4,3), (4,4), (5,4), (6,4), (7,6),(8,6).
$$
Of these, it turns out that $(4,1)$, $(4,3)$ and $(8,6)$ do allow infinitely many solutions. Indeed, for the first, the discriminant $D = s^2 - 4t - 4$ is actually still positive. For the latter two, we employ the observation that $4^2 + 3^2 = 5^2$ and $8^2+6^2 = 10^2$. These generate the infinite families of solutions with $(x,y) = (4c, 3c)$ and $(x,y) = (8c,6c)$ respectively.
Finally, I claim that the remaining pairs,
$$
(1,1), (2,1), (2,2), (3,2), (4,2), (4,4), (5,4), (6,4), (7,6),
$$
really do not admit infinitely many solutions. The argument contains too many case distinctions for me to write it all out here, but let me give you the tools to verify this for yourself. Writing $b = a - n$, my arguments above generate bijections between solutions $(x,y,a,b)$ to the pair of equations in question and solutions $(u,v)$ to the norm equation
$$
[ (n-s)u - tv ]^2 + (n^2 - s^2 - t^2)v^2 = (n^2 - s^2 - t^2)(n-s)/2,
$$
or with $s$ and $t$ swapped when parametrising the Pythagorean triples differently. It is important to note here that in order to obtain infinitely many solutions from this equation, the quadratic form on the left hand side must be indefinite. Hence we need only consider $0 < n < \sqrt{s^2 + t^2}$. The right hand side must also be integral. These leave only finitely many choices for $n$. Explicitly, one deals with these cases as follows:
For $(1,1), (2,1), (2,2), (4,2)$, there aren't even any valid $n$ to consider because the inequalities are too strict to obtain an integral right hand side for any $n$, so we are immediately done. For $(3,2), (4,4), (7,6)$, there are various $n$ yielding a sensible equation, but none of these turn out to have a solution. Finally, most interestingly, there are the cases of $(5,4)$ and $(6,4)$. In these cases, there are actually infinitely many pairs of solutions $(u,v)$ for some values of $n$. However, if one would work out the growth rates of $u$, they all turn out to be $\ll 0.85v$ and as such, all these infinite solutions will yield negative $x$ or $y$, hence not contributing actual solutions to the problem at hand.
Comment: Thanks, I'll continue to think about it for a bit. Sharp observation; indeed, for this to work we need that $D$ is a non-square, for otherwise, the equation I'm trying to argue has infinitely many solutions is one describing a fixed number as the difference of two squares, which indeed can only be done in finitely many ways
Comment: In fact, I just realised that this obstruction explains some of the black squares in your grid that nonetheless have one of their entries even; for instance, $6^2 - 4 \cdot 7 - 4 = 4$ is a square, as well as $6^2 - 4 \cdot 4 - 4 = 16$. Some other black squares are taken care off by the inequality on $t$
Comment: Sorry, I deleted my initial comment by mistake... Here it is again :

Thank you for your interesting answer. For your method to work, don't we also have to assume that $D$  is not a square ?
Comment: @uvdose I expanded my argument to include odd numbers as well. The only obstruction to my completing the proof completely seems to be your pesky yet completely valid objection above, regarding the rare case that $D$ is a square... I'll think about a way to circumvent that
Comment: @uvdose I think I have managed to completely solve your question! Let me know if everything makes sense. Nonetheless, a really wonderful problem, thanks a lot for posting! I've enjoyed thinking about it a lot this week
Comment: @MD Well done !
Answer: Comment: $t$ can be fixed but if $s$ is a number in an arithmetic progression then the system can have infinitely many solutions.For example:
$a=2i+1=3, 5, 7, 9 . . .$, where $t=2$
$b=2i(i+1)= 4, 12, 24, 40, . . .$ where $s=8, 12, 16, 20, 24, . . .$
$c=2i(i+1)+1=5, 13, 25, 41, . . .$
Another example:
$a=4i=4, 8, 12, 16, . . .$ where $t=4$
$b=4i^2-1=3, 15, 35, 63, . . .$ where $s=12, 20, 28, 36, . . .$
$c=4i^2+1=5, 17, 37, 65, . . .$
Update: We use quadratic residue; suppose we have"
$x^2+y^2=a^2$
$x^2\equiv r_x \mod m=k m +r_x\Rightarrow (x+ s d)^2\equiv r_x\bmod m$
Let $d=u-1$ we may write:
$x+sd= x+su-s\rightarrow (x+su-s)^2\equiv r_x\bmod m$
we assume $x+su=X$ so we get:
$(X-s)^2\equiv r_x\bmod m=m k_1+r_x$
Similarly for y we may write:
$y^2\equiv r_y \mod n\Rightarrow (x+ t d_1)^2\equiv r_y\bmod n$
Let $d_1=v-1$ we may write:
$y+td_1= y+tv-t\rightarrow (y+tv-t)^2\equiv r_y\bmod n$
we assume $y+tv=Y$ so we get:
$(Y-t)^2\equiv r_y\bmod n=n k_2+r_y$
That is for fixed $s$ and $t$ we can have new x (X), and new y(Y) such that:
$(X-s)^2+(Y-t)^2=b_1^2$
provided that:
$mk_1+nk_2+r_x+r_y=b_1^2$
That is for fixed $s$ and $t$ we may have infinitely many solutions for x, y, and b.
Example: Take $5^2+12^2=13^2$
$(5+3p)^2=\equiv 2\bmod 3=3k+2$
$(12+5q)^2=2\bmod 5=5k_1+2$
Take $b^2=25$ , we can write:
$3k+5k_1+4=25\Rightarrow 3k+5k_1=21$
Which has infinite solutions in $\mathbb Z$. Take one solution, for example $k=2$, $k_1=3$, we have:
$(X-3)^2+(Y-5)^2=25=5^2$
$X-3=3\rightarrow X=6$; $Y-5=4\rightarrow Y=9$
such that:
$(6-3)^2+(9-5)^2=5^2$
Another example :
Take $b^2=61^2$ we have:
$3k+5k_1+4=61^2=3721\Rightarrow 3k+5k_1=3717$
Take one solution $k=239$, $k_1=600$ such that:
$3\times 239+ 5\times 600+4=3721=61^2$
Compare with:
$11^2+60^2=61^2$
and get $X=14$ and $Y=65$ such that:
$(14-3)^2+(65-5)^2=61^2$
Comment: If $(s,t,u)$ is a Pythagorean triple, it is clear that $\mathscr{S}(s,t)$ has infinitely many solutions. And it seems that when $(s,t)$ is not black, $\mathscr{S}(s,t)$ has many solutions. Here are for example some solutions $(x,y,a,b)$ of $\mathscr{S}(3,5)$ :

$(63,16, 65,61)$, $(360, 81, 369, 365)$, $(2091,460,2141, 2137)$, $(12180, 2669, 12469,12465)$,$(70983,15544, 72665,72661)$, $(413712, 90585, 423513,423509)$, $(2411283,527956,2468405,2468401)$, $(14053980, 3077141, 14386909,14386905)$, $( 81912591,17934880, 83853041,83853037)$.
Comment: To clarify : if $(s,t,u)$ is a Pythagorean triple, for any positive integer $k$, $(x,y,a,b)=(ks,kt,ku,(k-1)u)$ is solution of $\mathscr{S}(s,t)$.
Comment: Thank you for your answer but I don't understand what is your point ?
Answer: We can see a pattern for $\,(s,t)\,$ in the sets below.  The value of $\,s\,$ is fixed in any given row and the value of $\,t\,$ is fixed in any given column but both are never fixed at the same time.
\begin{align*}
&A=(2n-1)^2+2(2n-1)k\\
&B=\phantom{(2n-1)^2+{}} 2(2n-1)k+2k^2\\
&C=(2n-1)^2+2(2n-1)k+2k^2
\end{align*}
$$\begin{array}{c|c|c|c|c|c|c|}
n & k=1 & k=2 &k=3 & k=4 & k=5\\ \hline
Set_1&3,4,5 &5,12,13&7,24,25&9,40,41&11,60,6\\ \hline
Set_2&15,8,17&21,20,29 &27,36,45 &33,56,65&39,80,89\\ \hline
Set_3&35,12,37&45,28,5&55,48,73&65,72,97&75,100,125\\ \hline
Set_{4}&63,16,65&77,36,85&91,60,109&105,88,137&119,120,169\\ \hline
Set_{5}&99,20,101&117,44,125&135,72,153&153,104,185&171,140,221\\ \hline
\end{array}$$
However, if we consider only the first set, i.e. $\,n=1,\,$ then
$$A = 2 k + 1\qquad
B = 2 k^2 + 2 k\qquad
B = 2 k^2 + 2 k + 1$$
For any $Set_1$ triple,
$\, A = 2 k + 1\implies k=\dfrac{A-1}{2}$
and reducing $\,k\,$ by $1$ yields
$$A=2k-1\quad B=2 k^2 - 2 k\quad C=2 k^2 - 2 k + 1$$
So, for example, the triple
\begin{align*}
T_n&=(13,84,85)\\\implies
k&=\dfrac{13-1}{2}=6\\\implies
T_{n-1}&=(12-1,72-12,72-12+1\\
&=(11,60,61)
\end{align*}
and the algorithm works for any of the infinite members of $Set_1$ except
$(3,4,5)$
A similar algorithm can be found for any other given set.
Comment: Thank you for your answer. I didn't really understand how it answered my question. For example, can you explain how to find solutions of $\mathscr{S}(18,19)$?
Comment: @uvdose What do the values 18 and 19 mean? Are these the gaps or are they the values of x,y?
Comment: @uvdose The terms using $\,k\,$ in my first formula are the intervals between subsequent triple components. My (A,B,C) are what you are calling (x,y,a). My answer shows how, for any triple except $(3,4,5)$ in $Set_1$, you can find the $\,k$-value that generated it, and then use that $\,k$-value to generate another triple using my 2nd formula. The next triple can then generate another triple and so-on until you reach $(3,4,5)$. It can work the other way if you add to $\,k\,$ instead of subtracting.
Comment: I'm talking about $\mathscr{S}(s=18,t=19)$. Please reread the initial message.
Answer: Too big for a comment:
Ony one of (s,t) can be fixed at a time.
Per a previous OP comment question, there cannot be a function $\space\mathscr{S}(18,19)\space $ because $\,t\,$ must be a multiple of $\,4.\quad$ However,
$\space\mathscr{S}(18,4p)\space $ is possible (where
$p\in\mathbb{N}, p\ge5$) using $Set_5$ of the table below.
$$\begin{array}{c|c|c|c|c|c|c|}
n & k=1 & k=2 &k=3 & k=4 & k=5\\ \hline
Set_1&3,4,5 &5,12,13&7,24,25&9,40,41&11,60,6\\ \hline
Set_2&15,8,17&21,20,29 &27,36,45 &33,56,65&39,80,89\\ \hline
Set_3&35,12,37&45,28,5&55,48,73&65,72,97&75,100,125\\ \hline
Set_{4}&63,16,65&77,36,85&91,60,109&105,88,137&119,120,169\\ \hline
Set_{5}&99,20,101&117,44,125&135,72,153&153,104,185&171,140,221\\ \hline
\end{array}$$
To find a triple $\,T_{n-1}\,$ from any $\,T_n\,$ in this set except $(99,20.101)$, find the $\,k$-value of $\,T_{n-1}\,$  using $\,k = \dfrac{A_{n} - 81}{18}$ and generate the new triple using the following formula.
$$
A=9 (2 k + 7)\qquad
B=2 (k^2 + 7 k - 8)\qquad
C=2 k^2 + 14 k + 65$$
For example,
\begin{align*}(153,104,185)\implies
\,k_{n-1} = \dfrac{153 - 81}{18}=4\\
\end{align*}
\begin{align*}
A_{n-1}=9 (2 (4) + 7)=135\\
B_{n-1}=2 ((4)^2 + 7 (4) - 8)=72\\
C_{n-1}=2 (4)^2 + 14 (4) + 65=153
\end{align*}
Answer: Let us consider the possible solutions of the given system in the form of
$$\begin{cases}
x^2+y^2=a^2\\
(x-s)^2+(y-t)^2=b^2\\
x+iy=p^2-q^2+2ipq =(p+iq)^2\\
a=p^2+q^2=|x+iy|\\
\sigma+i\tau =(x-s)+i(y-t)=u^2-v^2+2iuv=(u+iv)^2\\
b=|\sigma+i\tau|=u^2+v^2=|u+iv|^2\ge5,
\end{cases}\tag1$$
which corresponds with the case of the even values of $\,s\,$ and $\,t\,.$
Taking in account $\,(1),\,$ one can get
$$s+it=x+iy -(\sigma+i\tau)=(p+iq)^2-(u+iv)^2= \big(p+u+i(q+v)\big)\big(p-u+i(q-v)\big),$$
$$s^2+t^2=|s+it|^2=\big((p+u)^2+(q+v)^2\big)\big((p-u)^2+(q-v)^2\big)$$
$$=(a+b+2pu+2qv)(a+b-2pu-2qv)=(a+b)^2-4(pu+qv)^2,$$
$$\begin{cases}
s^2+t^2=(a+b)^2-4(pu+qv)^2\\[4pt]
(p^2+q^2)^2=a^2=x^2+y^2\\[4pt]
(u^2+v^2)^2=b^2=x^2-2sx+s^2+y^2-2yt+t^2\\[4pt]
b^2=\big(a^2-2\left(sx+t\sqrt{a^2-x^2}\,\right)s^2+t^2\big).
\end{cases}\tag2$$
Applying $(2),$ one can get:
$$\left(sx+t\sqrt{a^2-x^2}\,\right)'=s-\dfrac{tx}{\sqrt{s^2+t^2}}=0,\quad
x=\dfrac{as}{\sqrt{s^2+t^2}},$$
$$b^2\ge \big(a^2-2\left(sx+t\sqrt{2a^2-x^2}\,\right)s^2+t^2\big)
\bigg|_{\large x =\frac{a s}{\sqrt{s^2+t^2}}}$$
$$=a^2-2a\sqrt{s^2+t^2}+s^2+t^2 = (a-\sqrt{s^2+t^2})^2.$$
Since
$$a-\sqrt{s^2+t^2} = \sqrt{x^2+y^2}-\sqrt{s^2+t^2\,}\ge0,$$
then
\begin{cases}
b\ge a-\sqrt{s^2+t^2}\\[4pt]
s^2+t^2=(a+b)^2-4(pu+qv)^2\\[4pt]
4(pu+qv)^2\ge(a+b)^2-(a-b)^2= 4ab = 4(p^2+q^2)(u^2+v^2).
\end{cases}
At the same time, from the CS inequality follows that
$$4(pu+qv)^2\le4(p^2+q^2)(u^2+v^2),$$
i.e. there is a strict equality, with the necessary condition
$$\dfrac pu = \dfrac qv = \dfrac mn,$$
$$p=m\alpha,\; q= n\alpha,$\quad u=m\beta,\;v=n\beta.$$
Therefore,
$$\begin{cases}
x+iy=(m^2-n^2+2imn)\,\alpha^2\\
a=(m^2+n^2)\alpha^2,\\
\sigma+i\tau= (m^2-n^2+2imn)\beta^2\\
b=(m^2+n^2)\beta^2\\
s+it=(m^2-n^2+2imn)(\alpha^2-\beta^2)\\
s^2+t^2=(m^2+n^2)^2(\alpha^2-\beta^2)^2
\end{cases}$$
which defines all possible solutions of the system $(1).$ wherein
$$\begin{cases}
x^2+y^2=a^2\\
(x-s)^2+(y-t)^2=b^2,
\end{cases}$$
However, our task is to point the fixed pair $\;(s,t),\;$ which provides infinity many solutions.
Chosen $\;\alpha\,$ and $\,\beta\,$ as hypotenuse and leg of the Pythagorean triangle, easily to eliminate the second factor in the expression for $\;s+it.\,$ At the same time, there are not possibilities to fix the first factor.
The similar fatal problem should not be fixed, when both $\,s,t\;$ are odd.
So, the final answer is NO.

Gap between two Pythagorean triples


How to fill custom shape/path using EaselJS

Question: I am exploring CreateJS. This question concerns EaselJS.
I have managed to draw 3 arcs and fill them with a color.

Although, I want the final result to look like this:

If I draw a triangle to fill the missing space, how can I remove the color inside the bottom arc?
If I set it to transparent it will display the triangle color.
I could set it to white to look like what I want in this case, but it would look bad on top of a colored background.
Is there any method in the API that I am missing in order to do something similar to a flood fill inside a shape drawn with multiple arcs/lines?
Answer: Instead of drawing three separate arcs, you should use arcTo to keep the path continuous.
Something like this (of course replacing the numbers with your points/control points):
new Graphics().beginStroke(STROKE_COLOR)
    .moveTo(0, 20)
    .arcTo(150, 20, 150, 70, 50)
    .arcTo(150, 20, 150, 70, 50)
    .arcTo(150, 20, 150, 70, 50)
    .endStroke();


UISearchController extra unexpected UIView in hierarchy

Question: I have problem with UISearchController. It is adding one extra View as direct child of its View. It has isAccessibilityElement = true and description "Double-tap to dismiss", this blocks all Appium automatic testing. I can't figure out why, where and how it is added.
Someone know when and why this view is added and how to remove it? I have tried to set its isAccessibilityElement = false form code but somehow it is set back to true in some cases.
Answer: For anyone else who has this issue. It's caused by the default behaviour Apple have given the UISearchController where the searchResultsController is initially hidden until the UISearchBar has text.
We had old code in the searchResultsController to unhide itself view.isHidden = false which fought this default logic.
The fix was to remove this and instead set searchController.showsSearchResultsController = true which shows the results always and doesn't add the double tap to dismiss view.


Convert LPSTR to BSTR using win32

Question: I see how to do this using MFC, but what is the best way to convert a LPSTR to a BSTR in C++ using only the win32 libraries.
Comment: MultiByteToWideChar + SysAllocString
Answer: #include <comutil.h>

LPSTR myLpstr = "Hello World!";
_bstr_t bstr = _bstr_T(myLpstr);

It also needs library comsupp.lib
Comment: "comsupp.lib" is for "COM support".  COM is part of Win32.
Comment: He said "only the win32 libraries".
Comment: Agreed, but you should probably be using comsuppw.lib (which uses wchar_t* instead of unsigned short* in APIs). It's actually not a Win32 library (not in PSDK, no matching DLL) but a Visual C++ static library. So, you don't need to distribute MFC, but it's still not portable to MingW
Answer: Use SysAllocString.
Note that SysAllocString takes an OLECHAR* argument, which is effectively a WCHAR*, not a CHAR*. This shouldn't be a problem unless you're compiling without UNICODE defined--but don't do that.
Comment: Whether or not UNICODE is defined is not going to have any effect on an LPSTR.  You need to show how to convert the string.
Comment: -1, agree  with Hans Passant here. The Unicode define affects `LPTSTR`, not `LPWSTR` or `LPSTR`. Hence this answer is missing the hard part.
Answer: Don't know the concrete solution but I think this is gonna help you (especially part II):
The Complete Guide to C++ Strings, Part I - Win32 Character Encodings
The Complete Guide to C++ Strings, Part II - String Wrapper Classes

Convert LPSTR to BSTR using win32


Doctrine - ManyToMany Self Referencing Association + nested toArray() on child elements

Question: I'm trying to perform a ManyToMany self referencing association in my Symfony 2.1 project by following the Doctrine docs: http://docs.doctrine-project.org/en/latest/reference/association-mapping.html#many-to-many-self-referencing
My use-case is that I'm working on a CMS and I'm adding the ability to have related items of content. For example: I could have a sidebar on a website which would say that this piece of content X is related to Y and Z. Similarly on pages where content Y appears it says that it is related to content item X.
In my tests using this to add a new relation between content items fails because it reaches PHP's maximum nesting level of 100 because it is running toArray() on the current content item and then again on the related content item and so on and so on.
I've seen many similar questions on SO about Many-to-Many Self referential Doctrine associations but none with enough complete code to be able to see how others have managed this. Can anybody help?
My Content entity:
<code>/**
 * @ORM\MappedSuperclass
 * @ORM\Table(name="content")
 * @ORM\Entity(repositoryClass="CMS\Bundle\Common\ContentBundle\Entity\ContentRepository")
 * @ORM\InheritanceType("JOINED")
 */
abstract class content implements ContentInterface
{
    /**
     * @var int $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $title
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $title;

    // Other class properties

    /**
     * @var array
     *
     * @ORM\ManyToMany(targetEntity="Content", cascade={"persist"})
     * @ORM\JoinTable(name="content_relation",
     *      joinColumns={@ORM\JoinColumn(name="relation_id", referencedColumnName="id")},
     *      inverseJoinColumns={
     *          @ORM\JoinColumn(name="related_content_id", referencedColumnName="id")
     *      })
     **/
    private $related;

    public function __construct()
    {
        $this->related = new ArrayCollection();
    }

    // Other getters & setters for class properties

    /**
     * @return array
     */
    public function getRelated()
    {
    return $this->related;
    }

    /**
     * @param Content $relation
     */
    public function addRelation(Content $relation)
    {
        $this->related->add($relation);
        $this->related->add($this);
    }

    /**
    * @return array
    */
    public function toArray()
    {
        $related = array();
        foreach($this->getRelated() as $relatedItem) {
        $related[] = $relatedItem->toArray();
    }

    return array(
        'type' => static::getType(),
        'id' => $this->id,
        'title' => $this->title,
        ....
        'related' => $related
    );
}
</code>
In my RelationsController for managing the related content data I use it like this:
<code>/**
 * Creates a new relation to a content item
 *
 * @Route("{_locale}/content/{id}/related", name="relation_add")
 * @Method("POST")
 */
public function addAction(Request $request, $id)
{
    // Validation and error checking
    // $entity is loaded by the repository manager doing a find on the passed $id
    $entity->addRelation($relation);

    $em = $this->getEntityManager();
    $em->persist($entity);
    $em->persist($relation);
    $em->flush();

    $response = $relation->toArray();

    return new JsonResponse($response, 201);
}
</code>
Comment: With my self one-to-one self relation (parent-children) i added thee validation rule that a child cannot have itself as parent. It works, maybe this will help you.
Comment: @Gremo Can you show me an example of that validation rule please?
Answer: The fix for this was to use the JMSSerializerBundle to encode the entity to JSON instead of using a toArray method and change the addRelation function to:
<code>/**
 * @param Content $relation
 */
public function addRelation(Content $relation)
{
    $this->related[] = $relation;

    if (! $relation->getRelated()->contains($this)) {
        $relation->addRelation($this);
    }
}
</code>


jQuery load txt file

Question: I use this script to refresh the data on div #puu. If .load() contains existing .php file everything works just fine. But if I use existing .txt file in .load() nothing happens, why is this?

Comment: did you try url_encoding the file name? The spaces are not good for `load` since it has parser for space which is used to get document fragments. Inspect request in browser console network tab for more troubleshooting info
Answer: I think this is due to that filename its taken as null file name check with your filename
     $('#puu').load('153.txt').fadeIn("slow");
Answer: You should change the spaces in the file name to use %20 for the space. Also your fadeIn is firing before load returns the data.
$('#puu').fadeOut("slow")
         .load('152%20and%20153.txt', function() {
             $(this).fadeIn("slow");
         });

jQuery load txt file


Why is the convergence only a.e.? ($L^p$ spaces)

Question: In this proposition for $L^p$ spaces:

Why is the convergence only a.e.? If I divide the function in real and imaginary parts, and then in positive and negative parts for both of these. I get that I can use the fact that for every non-negative measurable function, I can get a sequence of simple functions converging to that sequence pointwise. And here, the convergence is everywhere? So why is it written a.e.?
Answer: Because elements of $\mathcal L^p$ are not functions, but equivalence classes of functions up to measure $0$. Hence for any specific representavie of the same class we cannot say anything better than "almost everywhere".


Why is attribute being inherited across classes in Python?

Question: I'm apparently having some trouble learning how to use classes correctly. I expect the following code to loop through a set of files (it does), adding elements to a set as it goes (it does), and starting the set over when it moves to a new file (it does not). The way I've hacked at the code below, I would expect it to return an empty set each time for file.terminals, because I believe that each set is the unique attribute of a new instance of the class SrcFile. Apparently, I am mistaken. What actually happens is that the set of terminals created by the first file persists (and is added to) for all subsequent files in the list, although other attributes (e.g. file.name, file.seqlength()) change appropriately with the files. Can someone please explain why it works this way and how I can create the behavior that I'm expecting? Thanks in advance for your patience with a beginning programmer's ignorance.
class SrcFile:
   terminals = set([])
   def __init__(self, which):
      self.name = which
   def seqlength(self):
      with open(self.name) as file:
         linecounter = 0
         for line in file:
            linecounter += 1
            if linecounter == 3:
               return int(line.split()[0])
               break

class Record(SrcFile):
   def terminal(self):
      record = self.name
   def terminal(self):
      record = self.name
      return record.split()[0]

for f in files:
   file = SrcFile(f)
   print(file.name, file.seqlength(), file.terminals)

   with open(f) as f:
      recordline = re.compile(r"^([A-Z]{5})\s{3}")
      for line in f:
         if recordline.match(line):
            record = Record(line)
            if record.terminal() in file.terminals:
               pass
            else:
               file.terminals.add(record.terminal())

Answer: You are defining terminals within the class declaration, not within the __init__ function that's executed for every new instance of the class.
Basically, terminals is initialized for the whole class, not for each instance of the class:
>>> SrcFile.terminals
set([])

Notice I ran SrcFile.terminals, not SrcFile().terminals, which means that SrcFile is a reference to the class, not an instance of the class.
You put variables like that inside of the __init__ function to make them instance-specific:
class SrcFile(object):
  def __init__(self, which):
    self.name = which
    self.terminals = set([])

Answer: By defining terminals = set([]) in the class itself it is created once when the class is defined an not when an instance is created.
To avoid this, remove it and add the following to your __init__ method:
self.terminals = set()

Comment: Thanks! That fixed it. I really appreciate the patience of this forum with those of us who are just getting started.
Comment: Got it...so much to learn. Accepting first correct answer submitted and signing off.


How do I unlock new courses in Everybody's golf?

Question: Ok so I have been playing Everybodys Golf for maybe 20 hours or so, am rank 4, and have beaten several vs characters but still only have the first course available to me.  Am I missing something on how to unlock new courses?
Comment: Do you know how many VS characters you beat?
Comment: so I finally had unlocked a new course but I believe it was after the 5th vs character?
Answer: To unlock new courses, you need to both rank up and beat enough VS characters, as seems to explain this user:

The courses (and almost everything else (special shots, carts, swimming, fishing, etc)) unlock as you progress through the ranks (not golfer level) and beat the Vs character challenges. At the moment I'm Rank 6 and I have 4 of the 5 courses available (as well as all 3 tee boxes, normal, long and championship).

So the problem was probably coming from the fact you didn't beat enough VS characters to reach the second course. As for the minimal rank required to be able to unlock each course:

Rank 3 unlocks the Alpine Mountains course.
Rank 4 unlocks the Kanaloa Beaxh course.
Rank 5 unlocks the Vortex Valley course.
Rank 7 unlocks the Imperial Gardens course.


Payment Gateways with the best API?

Question: Our company will soon need to integrate a payment gateway with our PHP web application for our users to be able to pay a "conference registration fee" using a credit card. Before defaulting to using Authorize.net, I want to find out from other developers which payment gateways you have used, and can recommend, that has an easy to use/integrate API.
FYI: Our company is in the U.S.A.
Comment: You should specify your country - there is many gateways which have no global range - ie. there is payline.com, quite good and nice to integrate (comes with ready to use SOAP library), but it's french and I don't think that is accessible yet in US.
Answer: Authorize.net is pretty much the standard for real merchant accounts. Most other providers even have an authorize.net emulation mode. The API is fairly standard - there isn't much room for creativity here.
I've worked with Amazon SimplePay which was relatively painless as well. Google Checkout is also fairly flexible. Neither of these is a real merchant account system of course.
Comment: +1 Authnet's API is about as easy and straight forward as it gets.
Comment: How does Paypal Website Payment Pro compare? We implemented a payment procedure using Website Payments Pro. It was quite straight forward. Paypal is not happy with our business model and thus we are looking for some one else.
Comment: @Ryan atconway just posted an answer which refers to PayPal's PayFlow Payment Gateway. I'm assuming PayPal Website Payment Pro is a different service, so you might want to check out this answer.
Answer: I recently came across a company called Stripe. They are a developer focused payment processing company. They handle the payment gateway stuff so you don't have to. They also have extensive documentation and easy to use APIs.
Update: Another company similar to Stripe is Braintree. Their product offering (and pricing model) is very similar.
Comment: I had heard of these guys before when they where US only. Good to see they now support UK :)
Answer: I work for IP Commerce, we have payment APIs that you can use to connect to multiple service providers (Chase Paymentech, Vantiv, First Data, etc.). You can checkout some of our sample code on GitHub: https://github.com/ipcommerce
The real benefit of using us would be if you want to do payment acceptance for a multi-channel type of thing, like point-of-sale and ecommerce, as we can easily link online-to-onsite transactions-- e.g. buy a 'daily deal' on your smartphone and redeem it at the point-of-sale using the credit card you bought the deal with or a QR Code.
Answer: I recommend PayPal's PayFlow Payment Gateway. One thing to note - it is a 'PayPal' service but does not require any use of PayPal as payment by the consumer. When I had used it in the past, I had built my own 'credit card' payment page accepting the different major credit cards but didn't even use PayPal as one of the accepted types.
The nice thing was you package up all the information, send it off to the gateway API via HTTPS, and get essentially a response including the charge/decline information from the bank.
There is some setup that has to be done on the backend after deciding on a payment gateway for where the money goes and which payment types you can accept. There are also decision to be made around fraud protection filter levels, and PCI security questions if you so much as store any of the charge data.
There are other payment gateway APIs but I liked PayPal because of their developer focus on the products. That had an entire forum (it's on SO now), documentation, developers site, and multiple programming examples.

Payment Gateways with the best API?


How to send email with table via Outlook through Delphi 7

Question: I would like my Delphi program to send email message via Outlook which will contain table (like the ones in Excel). I know how to send emails using Outlook through Delphi, but do not know how to include tables in it. I guess this should be something related to html code inside email body, but do not know exactly. Can anybody help?
Answer: An Outlook email object has a property htmlbody. You can set the value of this property to the html code of the message. To create the correct html code, have a look at www.w3schools.com. They have a lot of information about creating tables in html.