text:
Q: Function parameters and cartesian curves Given
$$x = \cos t + \cos 2t \,,\;  y = \sin t + \sin 2t ,$$
find the tangent line for the parameter at point $(-1, 1),$ and draw a  graph of the curve.
To find the point you could simply do $\dfrac{dx}{dt}$ and $\dfrac{dy}{dt}$ and find $\dfrac{dy}{dx}$ by taking the quotient, so you get $$ \dfrac{dy}{dx} =\dfrac{\cos t+2 \cos 2t}{-\sin t-2 \sin 2t}$$
How exactly would you define parameter $t$ in this case as a value to find the equation of the tangent? And when trying to draw the graph, you would need the Cartesian curve, which can be fetched by eliminating the parameter by solving for $t$. Is there a trigonometric identity that would make it possible to solve for $t$ using $X$ and $Y$ equations?

A: Firstly, you forgot to use the chain rule. Remember that $\frac d{dt}\sin 2t=2\cos 2t$, etc. So instead we have $$\frac {dy}{dx}=\frac{\cos t+2\cos t}{-\sin t-2\sin 2t}.$$
As you can see this is a functino of $t$. So to find the tangent line at $(-1,1)$, we need to know for what value of $t$ our parametric curve passes through $(-1,1)$. So we solve $$\begin{cases}\cos t+\cos 2t=-1\\ \sin t+\sin 2t =1.\end{cases}$$
Now \begin{gather}
\cos t+\cos 2t = -1\\
\cos t+\cos^2t-\sin^2 t=-\sin^2 t-\cos^2t\\
\cos t+2\cos^2t=0\\
\cos t(1+2\cos t)=0\\
\cos t=0\vee 2\cos t=-1\\
t=\frac \pi2+k\pi\vee t=\frac{\pm2\pi}3+2k\pi
\end{gather}
Now take $\tilde t_k=\frac{\pm2\pi}3+2k\pi$. We can simply calculate that $\sin \tilde t_k +\sin 2\tilde t_k=0$, so non of these is a solution to our system of equations.
Now we check the other possibilities for $t$ and see that $$\sin \left(\frac\pi2+k\pi\right)+\sin (\pi+2k\pi)=\begin{cases}1&\text{for $k$ odd}\\ -1& \text{for $k$ even}\end{cases}. $$
So we find that our curve passes through $(-1,1)$ whenever $t=\frac\pi2 +(2m+1)\pi$, for some integer  $m$.
Now just substitute this $t$ into the expression we found for $\frac {dy}{dx}$ and you'll be able to find the tangent line at $(-1,1)$.

A: You are on the parametric form, it is not necessary to know the geometric significance of $t$,
$$x = \cos t + \cos 2t \,,\;  y = \sin t + \sin 2t ,$$
The given point is generated for parameter $t = \pi/2 .$ Using standard form and slope computed, evaluate for this point and it is done.
$$ \dfrac{y-(\sin t + \sin 2t)}{x-(\cos t + \cos 2t) } = \dfrac{\cos t+2 \cos 2t}{-\sin t-2 \sin 2t}. $$

A: Another way by finding implicit equation
\begin{align*}
  x^{2} &= \cos^{2} t+2\cos t \cos 2t+ \cos^{2} 2t \\
  y^{2} &= \sin^{2} t+2\sin t \sin 2t+ \sin^{2} 2t \\
  x^{2}+y^{2} &= 2+2(\cos t \cos 2t+\sin t \sin 2t) \\
  &= 2+2\cos t \\
  \cos t &= \frac{x^{2}+y^{2}}{2}-1 \\
  x &= \cos t+2\cos^{2} t-1 \\
  &=(\cos t+1)(2\cos t-1) \\
  &= \frac{(x^{2}+y^{2})}{2} (x^{2}+y^{2}-3) \\
  0 &= (x^{2}+y^{2})(x^{2}+y^{2}-3)-2x \\
  0 &= x^{4}+2x^{2}y^{2}+y^{4}-3x^{2}-3y^{2}-2x \\
\end{align*}
In principle, the tangent can be found by implicit differentiation and plug in the point $(-1,1)$.
The rest of work is left as an exercise, but showing the graph instead:

P.S.: The curve is actually a shifted limaçon of Pascal,
$r=2\cos \theta+1$.


text:
Q: Programmatically identify django many-to-many links I'd like to automatically generate a list of an objects many-to-many links.
Let's say I have 5 Models:
Model 1 has a M2M link to Model 2
Model 2 has a M2M link to Models 3 and 4
Model 4 has a M2M link to Model 5

If the user adds an object to Model 1, I want to give them the option to add another Model 1 or add Model 2
If the user adds an object to Model 2, I want to give them the option to add another Model 2, or add a Model 1, 3, or 4.
If the user adds an object to Model 4, I want to give them the option to add another Model 4 or a Model 5/2.
etc.
Is there a way to detect these relationships (forward and backward) automatically?

A: You can access to m2m relation fields via Model1()._meta.many_to_many which will return all m2m relations, including GenericRelations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Must exposed pad (EP) for thermal dissipation be connected to ground for testing on breadboard I am testing a MCP8063, 8-lead 4 mm x 4 mm DFN package with exposed pad.
I have it deadbug to fit onto a breadboard. I have yet to get it to run a motor. Must the EP be grounded in order to test the IC chip and if so, how much surface area of the pad must be grounded to be sufficient? Also, as inferred, this particular chip is not mounted on its own pcb for testing, hence EP not grounded, how should I go about grounding the EP as it is now just hovering over the breadboard?

A: It depends on the internal design of the part. I have seen parts where the exposed pad MUST be connected to ground and others where it isn't necessary for proper operation. (Though ground is a convenient thermal sink.)
In this case the data sheet specifies that it should be connected to ground, so I would go with that.  If you want to breadboard without a PCB (which isn't really advisable) you could solder a heavy gauge wire to the pad and ground it.  That should help with thermals too, but you will have a thermal problem if you want to run the part anywhere near its limits.


text:
Q: Class inside a Class not recognised issue When I try to compile my following code , I receive an error that Test does not name a type. How is this possible as I seem to have included the header files correctly? Thanks in advance.
//Test.h
#include "Test2.h"

class Test
{
    Test2 t2;
};

//Test2.h
#include "Test.h"

class Test2
{
    Test t;
};

//main.cpp
#include "Test.h"

int main()
{
}


text:
Q: white in view controller before UIWebView apears I have two view controllers with two UIWebViews. The first one has a grey background and the second one a black background. When I try to access the second one a white background appears for miliseconds.
I've setted the UIWebView background color to black in the Attribute Inspector.


text:
Q: Moving some of systems folder to another drive in windows Situation:

*

*System on: Windows 10 20H2

*I've two physical drives:

*

*SSD 128 GiB (avail: 118 GiB, free: 15 GiB);

*HDD 1 TiB (avail: ??, free: 490 GiB)

*Partitioning structure:

*

*C: (SSD)

*other "drives" (HDD)

*I've two users: one with admin privilages, other without

*There're several folders like:

*

*Progfiles: "Program Files" (21 GiB) , "Program Files (x86)" (~4 GiB)

*UserDocs: "Users/USER/{Downloads, Pictures, Desktop, ...}" (~4 GiB)

*AppData: "Users/USER/AppData" (20 GiB)

*?? : for the apps via MS Store (?? B)

*Total of above: ~49 GiB

Problem:

*

*I am maxed out on C drive, and its structure has gone all messy

I want to:

*

*reinstall the windows (10), and repartition so that only the default stuff stays in C drive

*and move the ProgFiles & AppData in a separate drive

*and move the UserData in another separate drive

Research & other options

*

*Some articles i stumbled upon: but felt a bit twisty: a b c

*Reading several other answers here: 1 2 3

*... seems it's not possible

*so, any other advices?

*

*should i install the OS on a HDD?

*does linux support doing this? i have read that it doesnt contain drives, but partitions - which are shown like different folders - regardless, can the corresponding folders to above mentioned in linux be set to some partition on HDD, while the main system stays on SSD

A: You can use a symbolic link.

*

*Create the folder where you want it

*Create a Symbolic Link to it on Drive C.

For example
mklink /d e:\MyFolder c:\Users\User1\Documents

mklink Documentation
I have only used this to shift my Thunderbird folder for emails.  It should work for any folder, but it is always possible that it may not work for some system folders.

A:
reinstall the windows (10), and repartition so that only the default
stuff stays in C drive

Default stuff is Windows, Program Files and stuff in USERS like AppData.

and move the ProgFiles & AppData in a separate drive

No - do not move these files to a different drive.

and move the UserData in another separate drive

You can easily relocate My Documents, My Pictures, My Videos and so on to another drive.
Best solution here since you are going to reinstall Windows is to get a much larger drive.
Organizing bits of Windows into different drives is normally not a good idea.
A very good rule of thumb to follow:  Don't move what you do not understand really well.


text:
Q: scanf %u negative number? I have tried scanf("%u",&number) and I have entered negative number the problem is when I printf("%d",number) I get the negative number. I thought this will prevent me from reading negative number.
Are scanf("%d",&number) and scanf("%u",&number) the same thing really ?
or is it only for readibility.
Am I doing something called undefined behavior so ?
EDIT:
From Wikipedia I read this:

%u : Scan for decimal unsigned int (Note that in the C99 standard the
input value minus sign is optional, so if a minus sign is read, no
errors will arise and the result will be the two's complement of a
negative number, likely a very large value.

It is a little bit confusing reading SO answers and above. Can someone make it more clear ?

A: Yes, it's undefined behavior, either way.
Considering variable number is of type unsigned, %d in printf() expects an argument of signed int type, passing an unsigned type is UB.
OTOH, if number is signed type, using %u for scanning is UB in first place.
As you might have expected

[...] prevent me from reading negative number

format specifiers are not there to prevent improper input. If the format specifier does not match the supplied argument, it  invokes undefined behavior.
Quoting C11, annex J.2, scenarios invoking UB,

The result of a conversion by one of the formatted input functions cannot be
  represented in the corresponding object, or the receiving object does not have an
  appropriate type

A: As explained in detail by Sourav Ghosh, using formats that are inconsistent with the actual types passed is a potential problem.  Yet for this particular case, on current PC architectures, this is not really a problem, as neither int nor unsigned int have trap representations.
You can scan a negative number with scanf("%u", &number);.  It will be negated in the destination type, namely unsigned int, with the same bitwise representation as the negative number in a signed int, for two's complement representation which is almost universal on current architectures.

scanf converts %u by matching an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 10 for the base argument. The corresponding argument shall be a pointer to unsigned integer.
The strtol, strtoll, strtoul, and strtoull functions convert the initial portion of the string pointed to by nptr to long int, long long int, unsigned long int, and unsigned long long int representation, respectively. First, they decompose the input string into three parts: an initial, possibly empty, sequence of white-space characters (as specified by the isspace function), a subject sequence resembling an integer represented in some radix determined by the value of base, and a final string of one or more unrecognized characters, including the terminating null character of the input string. Then, they attempt to convert the subject sequence to an integer, and return the result.
If the value of base is between 2 and 36 (inclusive), the expected form of the subject sequence is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a plus or minus sign, but not including an integer suffix.
... If the subject sequence has the expected form and the value of base is between 2 and 36, it is used as the base for conversion, ascribing to each letter its value as given above. If the subject sequence begins with a minus sign, the value resulting from the conversion is negated (in the return type).

If the type of number is unsigned int, behavior is defined and the negative value is parsed and stored into number using the unsigned negation semantics.  Printing this value with printf("%d", number); is at best implementation defined, but again, on current PC architectures, will print the negative number that was originally parsed by scanf("%u", &number);
Conclusion: although it seems harmless, it is very sloppy to use int and unsigned int interchangeably and to use the wrong formats in printf and scanf.  As a matter of fact, mixing signed and unsigned types in expressions, esp. in comparisons is very error prone as the C semantics for such constructions are sometimes counter-intuitive.


text:
Q: Python 3.x: Transform string I need to transform source string into extended string, e.g:
A1f4h3L2 => AffffhhhLL
My code:
source = []
answer = ''
s1 = 'S15Y16r13g11b8X8J15Q9V2i18p5e10'
source += s1
i = 0
while i <= (len(source)-1):
    if source[i].isalpha:
        if source[i+1].isdigit:
            if source[i+2].isdigit:
                answer += (str(source[i]) * int(source[i+1] + source[i+2]))
                i += 2
            else:
                answer += (str(source[i]) * int(source[i+1]))
                i += 1
            i+=1

It works till "8X". Exception with: ValueError: invalid literal for int() with base 10: '8X'
Link to pytontutor.com visualisation
I can't understand why code works till i == 12

A: you can do it in pythonic way:
>>> a="A1f4h3L2"
>>> "".join(map(lambda x,y:x*int(y),a[::2],a[1::2]))
'AffffhhhLL'

how it works:
>>> a[::2]            # give me all alpahbhet
'AfhL'
>>> a[1::2]           # gives me all integer
'1432'

you can use zip also:
>>> "".join(x*int(y) for x,y in zip(a[::2],a[1::2]))
'AffffhhhLL'

above works for digit less then 10
if digit is greater than 10:
>>> import re
>>> s1 = 'S15Y16r13g11b8X8J15Q9V2i18p5e10'
>>> "".join(x*int(y) for x,y in zip(re.findall('[a-zA-Z]',s1),re.findall('\d+',s1)))
'SSSSSSSSSSSSSSSYYYYYYYYYYYYYYYYrrrrrrrrrrrrrgggggggggggbbbbbbbbXXXXXXXXJJJJJJJJJJJJJJJQQQQQQQQQVViiiiiiiiiiiiiiiiiipppppeeeeeeeeee'

using lambda and map:
>>> "".join(map(lambda x,y:x*int(y),re.findall('[a-zA-Z]',s1),re.findall('\d+',s1)))
'SSSSSSSSSSSSSSSYYYYYYYYYYYYYYYYrrrrrrrrrrrrrgggggggggggbbbbbbbbXXXXXXXXJJJJJJJJJJJJJJJQQQQQQQQQVViiiiiiiiiiiiiiiiiipppppeeeeeeeeee'

check this if you dont want to use re:
>>> s1 = 'S15Y16r13g11b8X8J15Q9V2i18p5e10'
>>> my_list =[]
>>> my_digit =''
>>> for x in s1:
...     if x.isalpha():
...         if my_digit != '':
...             my_list.append(my_digit)
...             my_digit=''
...         my_list.append(x)
...     else:
...         my_digit += x
...
>>> my_list
['S', '15', 'Y', '16', 'r', '13', 'g', '11', 'b', '8', 'X', '8', 'J', '15', 'Q', '9', 'V', '2', 'i', '18', 'p', '5', 'e']

now you can apply any methods from above like this:
>>> "".join(x*int(y) for x,y in zip(my_list[::2],my_list[1::2]))

A: I'd first convert this string:
A = 'S15Y16r13g11b8X8J15Q9V2i18p5e10'

to this list:
B = ['S', '15', 'Y', '16', 'r', '13', 'g', '11', 'b', '8', 'X', '8', 'J', '15', 'Q', '9', 'V', '2', 'i', '18', 'p', '5', 'e', '10']

Converting from A to B can be done by cutting the string in pieces:
A = 'S15Y16r13g11b8X8J15Q9V2i18p5e10'
B = []
start = 0
while start < len(A):
  i = start
  while A[i].isalpha():
    i = i + 1
  k = i
  while k < len(A) and A[k].isdigit():
    k = k + 1
  B.append(A[start:i])
  B.append(A[i:k])
  start = k

Now is way easier to produce your desired string:
>>> ''.join([(B[i] * int(B[i+1])) for i in range(0, len(B), 2)])
'SSSSSSSSSSSSSSSYYYYYYYYYYYYYYYYrrrrrrrrrrrrrgggggggggggbbbbbbbbXXXXXXXXJJJJJJJJJJJJJJJQQQQQQQQQVViiiiiiiiiiiiiiiiiipppppeeeeeeeeee'

A: Your specification was not overly detailed, but you can easily change the regexps to match your exact requirements
>>> def expand(s):
...     from re import findall
...     return "".join([c*int(n) for c, n in zip( findall(r'[A-Za-z]+',s),
...                                               findall(r'[0-9]+',   s))])
...
>>> print(expand(('S15Y16r13g11b8X8J15Q9V2i18p5e10'))
SSSSSSSSSSSSSSSYYYYYYYYYYYYYYYYrrrrrrrrrrrrrgggggggggggbbbbbbbbXXXXXXXXJJJJJJJJJJJJJJJQQQQQQQQQVViiiiiiiiiiiiiiiiiipppppeeeeeeeeee
>>>

A: No re
def expand(s):

    non_d = [] ; d = [] ; current_digit = ""
    for c in s:
        if c.isdigit(): current_digit = current_digit+c
        else:
            non_d.append(c)
            if current_digit: d.append(current_digit)
            current_digit = ""
    d.append(current_digit)
    return("".join(c*int(n) for c,n in zip(non_d, d)))

s = 'S15Y16r13g11b8X8J15Q9V2i18p5e10'
print expand(s)

Output
SSSSSSSSSSSSSSSYYYYYYYYYYYYYYYYrrrrrrrrrrrrrgggggggggggbbbbbbbbXXXXXXXXJJJJJJJJJJJJJJJQQQQQQQQQVViiiiiiiiiiiiiiiiiipppppeeeeeeeeee


text:
Q: d3.hsl fails on Safari I put together a simple HTML page:

$(document).ready(function() {
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  canvas.width  = window.innerWidth;
  canvas.height = window.innerHeight;

  //ctx.fillStyle = "gray";
  ctx.fillStyle = d3.hsl(120, 0.5, 0.5);

  ctx.fillRect(0,0, canvas.width, canvas.height);
});
html, body {
  width:  100%;
  height: 100%;
  margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>

<canvas id="myCanvas"> </canvas>

On Chrome it correctly gives a green background.
On Safari (8.0.6 -- current at time of writing) however it gives a black background.
What's going wrong?

A: Looks like the issue has to do with String coercion. Basically, the proper way to get d3.hsl to return a color string ("#40bf40" in your case) is to call .toString() on the HSL object (see here). So in your case, it would be
ctx.fillStyle = d3.hsl(120, 0.5, 0.5).toString()

which will fix the Safari issue.
The reason it worked in Chrome without the .toString() is because Chrome's JS engine chose to convert it to a String for you - much like JS converts a number to a string in something like this: 5 + "2" // "52". Internally it's actually calling (5).toString() + "2". Safari happened to not decide to .toString() it, which is why it didn't work.


text:
Q: Using a ConcurrentBag vs a simple Array in a Parallel for This is a hypothetical question/use-case based on the benefits of using (in this case) a ConcurrentBag over a simple array from within a Parallel for loop for this particular use-case.
The scenario is based on using a common Pipeline pattern to analyse numbers from 1 to total results, storing the result based on the output from one of the Pipeline operations not being null.
The actual order of the resultant list is important, thus using a simple list(of type string).add would result in oddness based on when each thread decides to return a result.
I have the following working code:
    public IList<string> Execute(int total)
    {
        var items = new ConcurrentBag<AnalyzerResult>();

        Parallel.ForEach(Iterate(1, (total + 1)), d =>
        {
            foreach (IOperation<T> operation in operations)
            {
                var result = operation.Execute(d);
                if (result != null)
                {
                    items.Add(new AnalyzerResult(d, result));
                    break;
                }
            }
        });

        return items.OrderBy(o=>o.SortOrder).Select(d => d.Result).ToList();
    }

AnalyzerResult is a simple immutable class, and the code only ever pushes new items to the bag (so no danger of something in the items list being changed, in theory).
Based on this, would a simple Array be sufficient (and contain less code noise)? or would the use of a concurrent type be considered better practice/more performant? For example:
    public IList<string> Execute(int total)
    {
        var items = new string[total];

        Parallel.ForEach(Iterate(1, (total + 1)), d =>
        {
            foreach (IOperation<T> operation in operations)
            {
                var result = operation.Execute(d);
                if (result != null)
                {
                    items[(d - 1)] = result;
                    break;
                }
            }
        });

        return items.ToList();
    }

Note: This is not a concurrency issue, both methods are legal and produce the desired result without issue.

A: I initially went with a "you need concurrency protection" answer, but then reread the second part of your question.
This looks like it should work since you're not going to attempt to write to the same location in memory from two different threads.  So, eliminating locks and thread affinity (which the ConcurrentBag gives) should provide a significant performance increase.
Really the question is - how much of an increase is it and is it a needed increase (need to profile), and will you ever change this setup in the future such that you would then need concurrency protection.
As is, it should be fine, and quite readable.  You would probably want to comment this code as to why you did it this way to make sure someone doesn't casually skim it and think "concurrency issue" (like I just did) and "fix" it.


text:
Q: Conditional transition in MassTransit Automatonymous saga I have some state in the saga and trying to implement status check retries until I get some satisfactory value in a message I receved.
Say, I have something like this:
.During(Pending,
    When(StatusChecked)
        .TransitionTo(somethingThatDependsOnStatusCheckedData)

I can only feed a specific state to TransitionTo but I want it to transition depending on the received message content, is it possible?

A: For received message content, you can use the conditional expression on the When clause.
During(Pending,
    When(StatusChecked, context => context.Data.IsMessageCondition)
        .Then(...));


text:
Q: Empty GameObject reset to 0,0,0 but now I can't move it with the childs of it since the arrows are far away at 0,0,0 anyway to change it? When I make double click on the empty GameObject as it should be it's zooming to the children group :

I grouped all the npcs under emprt GameObject name Npcs but first I was reseting Npcs to 0,0,0
Now the arrows of the axis to drag and change the Npcs positions are far away.
The idea was to easy move the npcs all the same time.
When I zoom out in the scene window this is where the Npcs is so if I will drag it and change it's positions I will not see where the npcs are moving to they are too far.

A: The Header Menu has a Toolbar where you can switch between two modes (briefly mentioned here)

*

*Pivot Use the pivot position of the first selected GameObject

*Center Use Geometrical Center of all selected and nested Meshes or center of all GameObject pivots if no meshes found


text:
Q: building monodoc for mono-addins for monodevelop missing Mono.GetOptions I am trying to build monodevelop so that I can use F#. Monodevelop apparently requires mono-addins which requires monodoc which requires Mono.GetOptions which no longer exists.
I see a post saying that mono-2.2 had monodoc included. But, I need to build mono-3.2.3 or a version 3 mono and I think there is no monodoc included.
How can I get around this?

A: Ack. I misunderstood an error message. monodoc is included in mono-3.2.3...


text:
Q: Swift: array references as object properties? I have a UITableViewController that can display content from any of three different arrays. In Objective-C, what I would typically do is set a property on the TableVC that is a reference to the array to be displayed. Then the TableVC would not only be able to show the contents of that array, but also handle user-directed editing of the array, say, if they deleted or re-ordered elements.
The way it seems to work in Swift when I set a property on my TableVC to an array is that it is a copy of my model's array, not a reference. And while this is fine in certain contexts, in my application it seems bad for two reasons: 1) my arrays are enormous, thousands of elements, and copying  huge arrays over and over again seems wasteful; 2) small edits are tougher to handle: I have to communicate back to the model about element deletion or re-ordering and make sure my view and model arrays stay in sync.
Setting a property that's a reference to an array is what I want to do, but there's no such thing as an inout object property in Swift.
What is the correct way for me to handle this?
Thanks.

A: Swift Arrays are not actually copied every time you assign them; instead, they are copy-on-write. What this means is that the array is only copied when something mutates it; until that point, you only copy a reference, like with Objective-C.
With that said, if you need reference semantics, the NSArray class from Objective-C is still available in Swift. You can also create your own class type that wraps an Array if you prefer not to use the Objective-C bridge.


text:
Q: How to Efficiently Calculate Nearest 2D points in JavaScript? I have a set of locations that I want to display to a user in proximity order - closest to farthest - based on their current coordinates. Assume we have ~100 data points of locations which includes each one's latitude and longitude (in some kind of object or array), and we know the user's lat and long. The goal is to display an ordered list of locations -- and it is beneficial if we can get and display to the user the nearest 8-10 locations while we calculate then display the remaining distances.
I know the brute-force solution is to loop through all locations, calculate the distance from the user, put them in order, then display them all to the user. But this is too slow.
A better solution is this one: https://stackoverflow.com/a/2466908/1766230 where you check within a bounded box first, expanding if necessary, then do the rest.
I've also seen there are other algorithms out there - like FLANN and other methods - but I haven't seen any examples written in JavaScript.
So the question: What is the fastest way to calculate (and display in order) nearest points in JavaScript?

A: So, if you are starting out with that list of points, drawing a small bounding box won't cut down very much, because you still do an O(n) check against all points for their location.
I would advise using a max-length heap or some other form of partial sort while iterating through all of the points. This lets you keep track of a small subset of approximately maximum/minimal points (as described by the length), so you can render those quickly before dealing with the rest. If you need more explanation about what I'm saying precisely, let me know.
Also what are you making this for that has such stringent performance issues? Typically computation like this shouldn't be a stress point, barring that you have 100k+ points. DOM manipulation is usually the most expensive spot
var points = [];
for (i = 0; i < 100; i++) {
    var point = [getRandomInt(0, 999), getRandomInt(0, 999)];
    point.len = distanceBetweenPoints(point, [499,499]);
    points.push(point);
}

console.log(Heap.nsmallest(points, 10, function (a, b) {
  return a.len < b.len;
}));

Here is the performance for it compared to bruteforce
Heap Code
js fiddle
Using the method I described, and a prebuilt heap another person wrote, I compared our methods. I think you will be happy! It performed 8,586 ops/sec compared to the 566 in the brute force technique!

A: Well this is my attempt at sorting an array of points by distance to a given point. This is brute-force as far as I understand. Then I slice the array to give you the 10 closest points.
Javascript
function distanceBetweenPoints(p1, p2) {
    return Math.abs(Math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])));
}

function sortByDistance(location, arrayOfPoints) {
    arrayOfPoints.sort(function (a, b) {
        a.distance = distanceBetweenPoints(location, a);
        b.distance = distanceBetweenPoints(location, b);

        return a.distance - b.distance;
    });

    return arrayOfPoints;
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var points = [];

for (i = 0; i < 100; i += 1) {
    points.push([getRandomInt(-90, 90), getRandomInt(-180, 180)]);
}

console.log(sortByDistance([0, 0], points).slice(0, 10));

On jsFiddle
This will at least give you something to test algorithms against. And here is a jsPerf for the above, so you can add other routines to it and do some real performance comparisons.
Note: This does not take into consideration that the Earth is a sphere! This is calculating Euclidean distance and not Geodesic distance. This is fine if the points, are for example, in the same town (or close proximity) but not if they are in different countries/continents. It also assumes that you have converted your longitude and latitude to a decimal representation.
Otherwise you will need to look at things like Great-circle distance and Haversine formula
In fact, the earth is very slightly ellipsoidal; using a spherical model gives errors typically up to 0.3%
Javascript
function toRadians(degrees) {
    return (degrees * Math.PI) / 180;
}

// Haversine formula
function distanceBetweenPoints(p1, p2) {
    var R = 6371, // mean earth radius in km
        lat1 = toRadians(p1[0]),
        lon1 = toRadians(p1[1]),
        lat2 = toRadians(p2[0]),
        lon2 = toRadians(p2[1]),
        dLat = lat2 - lat1,
        dLon = lon2 - lon1,
        a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2),
        c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)),
        d = R * c;

    return d;
}

function sortByDistance(location, arrayOfPoints) {
    arrayOfPoints.sort(function (a, b) {
        a.distance = distanceBetweenPoints(location, a);
        b.distance = distanceBetweenPoints(location, b);

        return a.distance - b.distance;
    });

    return arrayOfPoints;
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var points = [];

for (i = 0; i < 100; i += 1) {
    points.push([getRandomInt(-90, 90), getRandomInt(-180, 180)]);
}

console.log(sortByDistance([0, 0], points).slice(0, 10));

On jsFiddle


text:
Q: How can you learn advanced math if you don't have books or a teacher to consult? Everyone says to read book "xyz", but I have never found books to helpful for several reasons.

*

*You can't ask a book a deep question to do with understanding.

*No book is perfect.

*I can't afford them.

*I have ADHD (although I have no difficulty sitting and thinking about math for hours because it really interests me).

*This might be different with areas of math I'm not used to, but I've always ended up learning things in the past by finding a missing piece in my understanding at which point I can derive most of everything I need, and end up skipping chapters of the book altogether.

Furthermore, I am not connected to anyone I can ask questions to, although I wish I was. Whenever I meet a mathematician, I try to do everything to make the best of the situation. I have tried using Math Stack Exchange, but it just isn't enough to fully teach yourself a subject (and additionally, I don't always feel safe asking questions here). You can visit my profile to see the kinds of questions I've been asking.
I love math. However, after going through all the regular calculus stuff, as well as multivariable and vector calculus as well as a conceptual understanding of linear algebra, I'm pretty much stuck. I've been putting more time than ever into learning math of a wide variety with almost no results.
What I do have is the internet.
What is general advice for learning math from the internet?

A: What has worked for me is instead of searching for a "$xyz$" textbook, search for an online free class with an available syllabus. Preferably a class where you have lectures recorded, exercise lists available and a textbook which can be accessed online via a pdf file. This way you won't be intimidated by the volume of the textbook and things that you need to study will already be pinpointed and highlighted by a professor. I know that MIT and Harvard have a nice open course wares.
Good luck !

A: I have also struggled with mathematics a lot while self-studying. I couldn't understand most the books at starting, and the whole process was quite irreverent. To organise my learning, instead of searching for new books, I looked for the different university curriculums and the books they recommend for courses. It can help you determine which subject would be best suitable for you to study given your present knowledge. You can also follow online lecture notes like from MIT OCW, Paul's online math notes, etc. if you feel the book to be complicated.
Another critical point is that try to make friends with some mathematics students if you know any. You can also try various social media handles to find. Start asking doubts from them and eventually you will get acquainted with them. It helps a lot as you will get new ways of thinking about concepts.
At last, if nothing works, you can always email professors about your various doubts. I am sure nobody will turn you down. You can also contact any maths professor in you nearby university and take appointments from them to clear your doubts personally.
At last, never give up hope. Keep trying to make contacts, and eventually, everything will get sorted. I am telling you this from my personal experience.
Good luck!


text:
Q: Details regarding the delete-a-group jackknife I was reading a paper by Phillip S. Kott on DAGJK:
The delete-a-group jackknife. Journal of Official Statistics, 17 (4):521-526. (full text is freely available)
I don't have much of a survey/sampling background so I'm having a bit of trouble understanding some of the paper.

*

*What exactly is a primary sample unit (PSU)? An example would be incredibly helpful.

*In the second section, Kott assumes that $t=\sum_{h=1}^{H}\sum_{j=1}^{n_h}t_{hj}$ and he defines $q_{hj}=t_{hj}-t_{h+}$, where $t_{h+}=\sum t_{hg}/n_h$ with the summation going over all PSUs in $h$. How did he arrive at the variance formula, $\textrm{Var}(t_{h+})=\frac{n_h}{n_h-1}\sum_{j=1}^{n_h}q_{hj}^2$?

A: *

*PSU, or the primary sampling unit, is the object or a group of objects what you sample in the first stage of a multi-stage sample. Typically in large scale national studies, this could be a county or a census tract. Then you go down to the level of city blocks (secondary sampling units), dwellings, households, and individuals. So when you sampled Autauga County, Alabama (one of 3K+ counties in the US, the first that comes on the standard lists), you have to think of the 50,000 people that live in it as a single unit for variance estimation purposes. Of course, you would likely subsample this county, and end up interviewing may be 10 people. However, most of the contribution to the variance comes from the first stage, especially when observations with the PSU are similar to one another.

*This is the standard formula for the variance of a clustered sample; a common knowledge, if you like. There is no simple explanation for it sans the derivation from the first principles. You would have to look at a standard survey statistics book, such as Lohr 2009, Korn & Graubard 1999 or Thompson 1997 (in an increasing order of complexity and mathematical rigor).
The first principles of finite population sampling are really orthogonal to anything you've learned in statistics (be it mainstream or Bayesian or machine learning). What you measure on the sample elements is considered fixed (someone's weight or height or color of their eyes; and that make sense, except for some measurement error: your height tomorrow should not differ from your height today, so how can it be random?). What is random, however, are the indicators of the finite population elements being taken into the sample. In other words, if you talk about sampling 1000 people from US population, you are talking about a 300-million dimensional vector that has zeroes for most people who did not make it to the sample, and ones for the 1000 people who were sampled. Thus, the probability spaces that you would encounter in the world of sample survey are discrete (although combinatorially huge), and so are the sampling distributions of the sample statistics, although the latter would sometimes be well approximated by the normal distributions. The CLT-type justifications, however, are way more complicated in survey statistics, as appropriate CLTs have only been proven in limited contexts of specific sampling designs. You would need to get used to thinking in terms of the totals (because they are the only linear statistics of the random elements); to the weighted mean being a biased estimator of the population mean (as it is a ratio estimator, i.e., a non-linear statistic); and to variance estimation being an order of magnitude more complex than point estimation.
While Phil Kott is a very wise guy who writes quite well, I doubt that this paper is a good starting point on survey statistics. You must have been thrown into this quite harshly, I gather, to have to read this out of blue sky.


text:
Q: Extract value from list of xml elements with jaxb I have an XML doc structured like
<thing>
  <attr name="one">first</attr>
  <attr name="two">second</attr>
  <attr name="three">third</attr>
</thing>

I have JAXB classes that are set up like so:
public class Thing {
    List<Attribute> attr = new ArrayList<Attribute>();
    @XmlElement(name="attr")
    public List<Attribute> getAttr() { return this.attr; }
    public void setAttr(List<Attribute> attr) { this.attr = attr; }
}

public class Attribute {
    String value;
    String name;

    @XmlAttribute
    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }

    @XmlElement
    public String getValue() { return this.value;}
    public void setValue(String value) { this.value = value; }
}

When I unmarshal the document, if I loop over for (Attribute a : thing.getAttr()) doing a.getName() it prints the "one", "two", "three" but the a.getValue() is just null.
Am I annotating it incorrectly? Even if I set the annotation to @XmlElement(name="attr") it appears to do the same thing.

A: This will solve your problem:
@XmlValue
public String getValue() { return this.value;}

That's not a child element but the current element value you are looking for.
EDIT: and BTW you should add an @XmlRootElement annotation on Thing class in case if it's missing.


text:
Q: My while loop is not working on JavaScript my teacher sent me an excercise and I need help to solve it. It's about making a shopping list. When you press the button cancel, the elements you add should be displayed on the website but it doesn't happen. Please, I need help.

SHOPPING EVERYWHERE!

A: The variable lista will never change in the loop because you never change the variable lista. I think your issue was that you wrote l in the loop and not lista, so may write:

SHOPPING EVERYWHERE!


text:
Q: Automation Error - The Object Invoked has Disconnected from It Clients during autofilter Ok, I know there are many posts about this but so far none of them have a solution that seems to work for me.
I ran across this for the first time a week ago and have created a very simple program to try and figure out what is going on. I have resorted to hand typing all this (I usually start with an old macro and modify it or copy and past code pieces); I have made my own data file just in case there was something weird with the file I am planning to use as the input; and it still errors out.
I have other macros that are doing the exact same processes and they still work fine. This is driving me insane. The code below crashes on the Autofilter line.
Sub Fred()
Dim strFileToOpen As String
Dim wbHL7 As Workbook
    strFileToOpen = Application.GetOpenFilename(Title:="Please select the Invoice file.", FileFilter:="Excel Files *.xls* (*.xls*),")
    If strFileToOpen = "False" Then
        MsgBox "No file selected.", vbExclamation, "Sorry!"
        Exit Sub
    Else
        Set wbHL7 = Workbooks.Open(Filename:=strFileToOpen)
    End If
    rCnt = Cells(Rows.Count, 1).End(xlUp).Row
    ActiveSheet.Range("A1:K" & rCnt).AutoFilter Field:=11, Criteria1:=0, Operator:=xlFilterValues
    ActiveSheet.Range("A1:K" & rCnt).Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    ActiveSheet.AutoFilterMode = False
End Sub

Many of the other posts hint that there might be an issue with my actual system such as compatibility things, but then why are the other macros still working? By the way, once it does this, it basically locks up everything to do with Excel and I have to open the Task Manager to kill the process. I am using Windows 7 and Office 2013.
Edit:
I just want to add that if I record an autofilter macro in the same book as the data, it works fine.

A: You have an error in your code. The criteria needs to be a string. If you look carefully at the recorded macro you'll see that it too uses a string.
Change your autofilter line to the following and it should work:
ActiveSheet.Range("A1:K" & rCnt).AutoFilter Field:=11, Criteria1:="=0", Operator:=xlFilterValues


text:
Q: Magento Transaction E-Mails Not Working (admin) I'd like to receive e-mails when someone buys something on my Magento website. I've added my e-mail to be 'BCC' in the sales e-mail section but nothing is received. Customers however do receive e-mails after making a purchase. Can anyone point me towards a troubleshoot process for this? I don't understand why customers are receiving the e-mails but as the store admin I am not.
Thank you very much

A: The cron heartbeat was the issue as it was not automated. I added the automation at server level under 'Scheduled Task' in Plesk Control Panel by providing the path to cron.php in the Magento directory and setting this to be run every 10 minutes.


text:
Q: vscode: Multi File Template I'm wondering if there's a way to specify a template (for the lack of a better word) in vscode that would create multiple files.
In my concrete scenario I want to create an angular component which would contain:

*

*[mycomp].component.ts

*[mycomp].component.scss

*[mycomp].component.html

Is there a way to do this or am I out of luck?


text:
Q: Change attributes order in woocommerce cart using jQuery I'm using woocommerce to create an online custom cabinet door store for my company. We've had to use a couple of plugins to help calculate the many specifications needed to customize a cabinet door. But because multiple plugins are being used, the order in which the attributes are displayed are not how we would like it to appear on the cart. The product section of the cart table displays a description list  of  all of the product attributes in this order:

*

*Wood Type:

*Thickness of Door:

*Boring ($7.50):

*Unit:

*Specs - Distance 1:

*Specs - Distance 2:

*Width (in):

*Height (in):

*Total Area (sq. ft.):

HTML as it is displayed in the cart:

Wood Type:

Mahogany

Thickness of Door:

3/4"

Boring ($7.50):

Yes

Unit:

Inches

Specs - Distance 1:

1

Specs - Distance 2:

2

Width (in):

13

Height (in):

18

Total Area (sq. ft.):

1.63

And if "Boring" is not selected the cart will appear like this:

*

*Wood Type:

*Thickness of Door:

*Width (in):

*Height (in):

*Total Area (sq. ft.):

HTML:

Wood Type:

Poplar

Thickness of Door:

3/4"

Width (in):

22

Height (in):

22

Total Area (sq. ft.):

3.36

We want the 4 attributes associated with Boring (Boring, Unit, Specs-Distance 1:, Specs - Distance 2:) to be displayed underneath the Width, Height and Total Area.Like this:

*

*Wood Type:

*Thickness of Door:

*Width (in):

*Height (in):

*Total Area (sq. ft.):

*Boring ($7.50):

*Unit:

*Specs - Distance 1:

*Specs - Distance 2:

It seems a lot simpler to use jQuery rather than change the priority that each attribute is given to be displayed in the cart. I've used both the append() and the before() function to rearrange the list items for the  and  elements but the problem is if there is more than one item in the cart it puts elements from the other cart item into the first list. Here is my jQuery code to simply move the "Width" attribute before the "Unit" attribute as a test.
(function ($) {

   $('.variation dt.variation-Unit').before($('.variation dt.variation-Widthin'));
   $('.variation dd.variation-Unit').before($('.variation dd.variation-Widthin'));
}
})(jQuery);

This code takes all of the  and  elements with the class variation-Widthin and puts it before the first time 'variation-Unit' is shown on the cart. I've tried the each() and the result puts all the elements in each class twice so it appears doubled. If anyone could tell me what my code is missing so that only the elements are moved inside each cart item that it belongs to that would help a lot. Also if there's a better way to go about this I would love to hear you out.

A: If these are prefilled on the page and since they all have a unique class i.e. variation-WoodType, you could order the elements with flex in CSS.
If you are focusing on using jQuery as your comment says, I'd advise being more specific when declaring what elements to move. So do a $.each around each of the tr and then arrange the children contained. Something like the following, renaming TABLE_ROW_CLASS to the class of the row.
$('tr.TABLE_ROW_CLASS').each(function() {
  $(this).find('dt.variation-Unit').before($(this).find('dt.variation-Widthin'));
});

Edit: to find as per OP comment above.

A: Use insert before or insert after. For example.

1

2

3

4

5

$(".paragraph5").each(function() {
    $(this).insertBefore($(this).closest(".variation").find(".paragraph1").first());
})


text:
Q: Microsoft SMSS - Joining tables on t2.primary key = t1.foreign_key I need to join two tables together to create a table with columns for employee id, employee name and their boss' name.
The 'hier' table

The 'employees' table

The query I wrote is almost working, putting an employee name in the right spot, but not the right employee:
SELECT em.emp_id, em.emp_name, em.emp_name AS boss_name
FROM employees em
LEFT JOIN hier h ON (h.boss_id = em.emp_name)

Which outputs:

I need to have each person's boss to have the right name, and in the case of Big Boss, 'N/A'. Like so:

A: You need a self join with Employee table
SELECT em.emp_id, em.emp_name, e1.emp_name AS boss_name
FROM employees em
LEFT JOIN employees em1 ON em.boss_id = em1.emp_id


text:
Q: How to set custom error in strong-error-handler when debug mode is false I'm using Loopback v3.x, and strong-error-handler for handling my project errors. The error response was fine in the development mode but when in production mode, it throws a different error back to the client.
I realised that it was the "debug": false" that makes it throw an { error: { statusCode: 500, message: 'Internal Server Error' } } (based from the Loopback documentation about strong-error-handler)
But I wanted to show my error in the production when I throw new Error('Error Messages') with "debug": false (to keep the sensitive data such as file paths, URLs, and stack traces out from exposure)
Below are my config files:
config.json
{
  ...
  "remoting": {
    "rest": {
      "normalizeHttpPath": false,
      "xml": false,
      "handleErrors": false
    }
  }
}

middleware.development.json
{
  "final:after": {
    "strong-error-handler": {
      "params": {
        "debug": true,
        "log": true,
        "safeFields": [
          "code"
        ]
      }
    }
  }
}

middleware.json
{
  "final:after": {
    "strong-error-handler": {
      "params": {
        "debug": false,
        "log": true,
        "safeFields": [
          "code"
        ]
      }
    }
  }
}

I wanted the response to show the Error that I have thrown, like below:

Instead, now it receives:

I have went to strongloop-error-handler GitHub library but couldn't find any documentation about throwing the original error. Is it possible to do so?

A: So I went digging around the strong-error-handler library and found out that it is technically possible to do so if we set a statusCode into the error manually, and has to be within 400 - 499.

in buildResponseData() function:

if (data.statusCode >= 400 && data.statusCode <= 499) {
  fillBadRequestError(data, err);
} else {
  fillInternalError(data, err);
}

https://github.com/strongloop/strong-error-handler/blob/master/lib/data-builder.js#L37

and the fillBadRequestError() will return the original error

function fillBadRequestError(data, err) {
  data.name = err.name;
  data.message = err.message;
  data.code = err.code;
  data.details = err.details;
}

https://github.com/strongloop/strong-error-handler/blob/master/lib/data-builder.js#L69
So, before throwing the error, we can set:
const error = new Error();
error.name = 'Custom Error';
error.message = 'Error Message';
error.statusCode = 404;
throw error;

Then it will return the error even with "debug": false mode


text:
Q: Safari rendering page fonts thinner with jQuery slider on page I'm pulling my hair out on this one. I'm using the FlexSlider on a page with great results; however when running this, Safari (Mac version, not ios) renders the fonts on the page thinner. Firefox and Chrome both have no issues. Here is my basic code in case that helps at all:

<link href="css/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/flexslider.css" />
<title>Title</title>

Slogan At The Top

View These Slides

Element 1

Element 2

I actually assume that the code in this case won't help. I feel like it's more of an issue with Safari and something in FlexSlider. I thought I had narrowed the problem down to FlexSlider's use of translate3d but it didn't pan out.
Has anyone else experienced Safari changing the thickness of fonts based on jQuery elements or even something like a flash video (not used in this case)? Also, I'm not using any embedded fonts, fyi.

A: It's just a CSS fix. The following prevents the thinning of text in webkit (safari/chrome):
.flexslider {position:relative;z-index:1}

If your control nav is not positioned absolute above the slider, then that should be all, if yours is positioned above, like mine, then I did this:
.flex-control-nav {position: absolute; top: 0;left:0;overflow:hidden;z-index: 2;}

The overflow hidden was added on the .flex-control-nav because in certain layouts in firefox and chrome, on my Macbook, two fingers would not swipe the page, but move the page itself around causing shifting of at least 100% wide or more.

A: I don't think @Will Schmidt's answer is correct.
I found that on the stylesheet the line that reads
.flexslider .slides > li {display: none; -webkit-backface-visibility: hidden; }

should be
.flexslider .slides > li {display: none; }

This worked for me, whereas his answer didn't (like he started, it effects all text).

A: Sharing this as it solved the issue for me... I simply added the following into my CSS file
html { -webkit-font-smoothing: antialiased; }

This is an inverse fix, in that it changes the rest of the text on your page to appear as it does in the slider.  Doing it the other way round will require you modifying the flexslider javascript code.
Got this from here: https://github.com/desandro/isotope/issues/209#issuecomment-7377938

A: I've struggled with this too. In my case the fonts seemed to fade. Having looked at this and other discussions I fixed it by disabling the webkit transforms in Flexslider. I believe this may remove hardware acceleration for Safari browsers, but at least it worked. I'm using Flexslider version 1.8.
In the Flexslider javascript file (not minified), look for the following code near the top:
//Test for webbkit CSS3 Animations
slider.transitions = "webkitTransition" in document.body.style;

Change the second line to:
slider.transitions = false;

I hope this works it for you. (I'm also open to better solutions :-)

A: Adding:
position: relative; z-index: 1;

To the line:
.flex-viewport {max-height: 2000px; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; transition: all 1s ease; }

Fixed it for me:
.flex-viewport {max-height: 2000px; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; transition: all 1s ease; position: relative; z-index: 1; }


text:
Q: Excel VBA Compile Error Else without If I try to run a code when column "L" and column "V" stated "Completed" on both. Then column "W" will show "Completed" else it will show "incompleted" but it show compile error "Else withou if".
Below is my code
Sub OverallStatus()

Dim x As Long
Dim lastrow As Long

With Sheet1
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
         lastrow = .Cells.Find(What:="*", _
                     After:=.Range("A1"), _
                     Lookat:=xlPart, _
                     LookIn:=xlFormulas, _
                     SearchOrder:=xlByRows, _
                     SearchDirection:=xlPrevious, _
                     MatchCase:=False).Row
    Else
        lastrow = 1
    End If
    For x = 2 To lastrow
        If .Range("L" & x) = "Completed" And .Range("V" & x) = "Completed" Then
        .Range("W" & x) = "Completed"
        Else: .Range("W" & x) = "Incomplete"
        End If
    Next
End With
End Sub

A: Things to change on your code:

*

*New line character after Then, or move this back up at end of the If

*Insert End If before the Next

*Replace End If above the End Sub with End With


text:
Q: How can a set be bounded and countably infinite at the same time? There is a theorem in my textbook that states,

Let $E$ be a bounded measurable set of real numbers. Suppose there is a bounded countably infinite set of real numbers $\Lambda$ for which the collection of translates of $E$, $\{\lambda + E\}_{\lambda \in \Lambda}$, is disjoint. Then $m(E) = 0$.

I'm a little confused about this theorem, because it's saying that a set is bounded and countably infinite at the same time. But if a set is bounded, isn't it supposed to be finite?
Thanks in advance

A: The set $\{2^{-k}\ |\ k \in \mathbb{Z}^+\}$ is bounded and countably infinite.

A: Hint: Consider $\Bbb Q$ intersected with any bounded set, finite or infinite. Since $\Bbb Q$ is countable, the new set is at most countable, and clearly can be made infinite; for example, $[0,1]\cap\Bbb Q$ is bounded and countable.

A: No: $[0,1]$ is a bounded set that isn't even countable, let alone finite. An unbounded set of real numbers is necessarily infinite, but a bounded set can be of any size up to and including the cardinality of the entire set of real numbers.
To prove this, use the well-known fact, proved in several places on this site, that there is a bijection $\varphi:\Bbb R\to(0,1)$. Let $A$ be any subset of $\Bbb R$; then $\varphi[A]$ is a subset of $(0,1)$ of exactly the same cardinality, and every subset of $(0,1)$ is bounded.


text:
Q: tomcat server not functioning properly Today I completely worked with tomcat, creating HTML pages, and servlets, it worked and did not give me any trouble. but now suddenly when I wanted to open my pages using tomcat, the browser is showing the following error.

This localhost page can't be found
  No webpage was found for the web address: http://localhost:1996/cart.html
  Search Google for localhost 1996 cart HTTP ERROR 404

How can I fix the issue?


text:
Q: google.Maps.Circle repeats in every clone part of google map on small zoom option Does anyone know the way to prevent the repeating property of circle in every clone part of google map.
In google.Maps API I found the similar option of marker it's: optimized property set to false.
The parts of my code:
this.map = new google.maps.Map(this.el, {
        zoom: 4,
        center: new google.maps.LatLng(33.2169, -97.1336),
        disableDefaultUI: true,
        zoomControl: true,
        zoomControlOptions: {
            style: google.maps.ZoomControlStyle.LARGE,
            position: google.maps.ControlPosition.LEFT_CENTER
        },
        mapTypeControl: true,
        mapTypeControlOptions: {
            position: google.maps.ControlPosition.TOP_RIGHT
        }
    });
        this.circle = new google.maps.Circle({
            center: new google.maps.LatLng(33.2169, -97.1336),
            radius: 1609344,
            strokeWeight: 1,
            strokeColor: "#e64646",
            draggable: true,
            editable: true,
            visible: false,
            map: this.map
        });


text:
Q: Copying file into array but it won't print? I'm trying to read a file onto an array  in C and I believe I have done that part correctly. However, I keep getting a segmentation fault when I try and copy it to an output file. Can someone help me find the cause of it?
char* inputStr;

long inputSize;

FILE* input;
FILE* output;

fseek(input, 0, SEEK_END);
inputSize = ftell(input);
rewind(input);
inputStr = malloc((inputSize +1) * (sizeof(char)));
fread(inputStr, sizeof(char), inputSize, input);
fclose(input);

fprintf(output, "%s", inputStr);

fclose(output);

A: You didn't open the files! You need to open the files before doing an fseek(), ftell(), ...


text:
Q: What is the probability for a wood stick of real number length breaking in three piece that can forming precisely a triangle? What is the probability for a wood stick of any real number length breaking in three piece that can forming precisely a triangle without any extra segment extend  from the side of the triangle?
My friend told me it can be solve in a calculus way and a algebra-precalculus way, what is the calculus way?
I found a relevant of this problem, but it is not the same to me : Broken stick probability problem
Last but not least: happy puzzle solving!

A: Picking two numbers independently that are uniformly distributed in $[0,1]$ is the same as picking a uniformly distributed point in the unit square.  Call the smaller one $x$ and the bigger one $y$.  The graph of $0<x<y<1$ is a triangular region and we are choosing a point within it.  The lengths of the three sides will then be $x$, $y-x$, and $1-y$.  We need three instances of the triangle inequality:
\begin{align}
x + (y-x) & > 1-y, \\
x + (1-y) & > y-x, \\
(y-x)+(1-y) & > x.
\end{align}
Draw the graph of the set of inequalities above within the aforementioned triangular region and you'll see the answer.

A: In the comments you asked me by name for a calculus way. Personally I would not do it this way.
Let us assume that the stick is broken at two random points $X, Y$ where the two points are independently uniformly distributed on $[0,l]$, so pieces with lengths $\min(X,Y), \max(X,Y)-\min(X,Y), l-\max(X,Y)$ and a triangle cannot be constructed if any of the lengths is $l/2$ or more (almost certainly mutually exclusive events).
Then $\displaystyle \Pr(\min(X,Y) \ge l/2)=\int_{x=l/2}^{l} \int_{y=l/2}^{l} \frac1{l^2} \,dy \,dx = \frac14$
$\displaystyle \Pr\left(\max(X,Y)-\min(X,Y) \ge l/2\right)=\int_{x=l/2}^{l}  \int_{y=0}^{x-l/2} \frac1{l^2}  \,dy \,dx + \int_{x=0}^{l/2}  \int_{y=x+l/2}^{l} \frac1{l^2}  \,dy \,dx = \frac14$
$\displaystyle \Pr(l-\max(X,Y) \ge l/2)=\int_{x=0}^{l/2}  \int_{y=0}^{l/2} \frac1{l^2} \,dy \,dx = \frac14$.
The probability you want is $1-\dfrac14-\dfrac14-\dfrac14=\dfrac14$.


text:
Q: Download attachment (attachment not found) I've got a code from here and I'm tweaking it for my need. My need is quite simple: I need it to download if it has the name of the Daily Tracker I'm keeping track of (as it changes daily with the Format(Now)). The problem is that it is not finding the attachment.
The code can find the email if I substitute the ElseIf to Next part for oOlItm.Display, but won't download the attachment.
Sub AttachmentDownload()

Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\TEMP\TestExcel"

    Dim oOlAp As Object
    Dim oOlns As Object
    Dim oOlInb As Object
    Dim oOlItm As Object
    Dim oOlAtch As Object

    Dim NewFileName As String
    NewFileName = "Daily Tracker " & Format(Now, "dd/MM/yyyy")

    Set oOlAp = GetObject(, "Outlook.application")
    Set oOlns = oOlAp.GetNamespace("MAPI")
    Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)

    For Each oOlItm In oOlInb.Items
        If InStr(oOlItm.Subject, NewFilename)) <> 0 Then
            ElseIf oOlItm.Attachments.Count <> 0 Then
                For Each oOlAtch In oOlItm.Attachments
                    oOlAtch.SaveAsFile (AttachmentPath)
                    Exit For
                Next
            Else
                MsgBox "No attachments found"
            End If
            Exit For
        Next
End Sub

The email:

A: This should work for you:
   Sub AttachmentDownload()

Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\TEMP\TestExcel"

    Dim oOlAp As Object
    Dim oOlns As Object
    Dim oOlInb As Object
    Dim oOlItm As Object
    Dim oOlAtch As Object
    Dim oOlResults As Object

    Dim x As Long

    Dim NewFileName As String
    NewFileName = "Daily Tracker " & Format(Now, "dd-MM-yyyy")

    'You can only have a single instance of Outlook, so if it's already open
    'this will be the same as GetObject, otherwise it will open Outlook.
    Set oOlAp = CreateObject("Outlook.Application")
    Set oOlns = oOlAp.GetNamespace("MAPI")
    Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)

    'No point searching the whole Inbox - just since yesterday.
    Set oOlResults = oOlInb.Items.Restrict("[ReceivedTime]>'" & Format(Date - 1, "DDDDD HH:NN") & "'")

    'If you have more than a single attachment they'll all overwrite each other.
    'x will update the filename.
    x = 1
    For Each oOlItm In oOlResults
        If oOlItm.attachments.Count > 0 Then
            For Each oOlAtch In oOlItm.attachments
                If GetExt(oOlAtch.FileName) = "xlsx" Then
                    oOlAtch.SaveAsFile AttachmentPath & "\" & NewFileName & "-" & x & ".xlsx"
                End If
                x = x + 1
            Next oOlAtch
        End If
    Next oOlItm

End Sub

'----------------------------------------------------------------------
' GetExt
'
'   Returns the extension of a file.
'----------------------------------------------------------------------
Public Function GetExt(FileName As String) As String

    Dim mFSO As Object
    Set mFSO = CreateObject("Scripting.FileSystemObject")

    GetExt = mFSO.GetExtensionName(FileName)
End Function

Another way of doing it is from within Outlook:
Create a new folder in your Outlook Inbox and set a rule to move the email to this folder when it arrives.  You can then write code to watch this folder and save the file as soon as it arrives.
Place this code within the ThisOutlookSession module in Outlook.
Dim WithEvents TargetFolderItems As Items
Const FILE_PATH As String = "C:\TEMP\TestExcel\"

Private Sub Application_Startup()

    Dim ns As Outlook.NameSpace

    Set ns = Application.GetNamespace("MAPI")
    Set TargetFolderItems = ns.Folders.Item("Mailbox - Darren Bartrup-Cook") _
                              .Folders.Item("Inbox") _
                              .Folders.Item("My Email For Processing").Items

End Sub

Sub TargetFolderItems_ItemAdd(ByVal Item As Object)

     'when a new item is added to our "watched folder" we can process it
    Dim olAtt As Attachment
    Dim i As Integer

    Dim sTmpFileName As String

    Dim objFSO As Object
    Dim sExt As String

    If Item.Attachments.Count > 0 Then
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        For i = 1 To Item.Attachments.Count
            Set olAtt = Item.Attachments(i)

            sExt = objFSO.GetExtensionName(olAtt.FileName)

            If sExt = "xlsx" Then
                sTmpFileName = "Daily Tracker " & Format(Now, "dd-mm-yyyy") & ".xlsx"
            End If

            Item.UnRead = False
            olAtt.SaveAsFile FILE_PATH & sTmpFileName
            DoEvents

        Next
    End If
    Set olAtt = Nothing

    MsgPopup "A new attachment has been saved.", vbOKOnly, "New Daily Tracker"

End Sub

Private Sub Application_Quit()

    Dim ns As Outlook.NameSpace
    Set TargetFolderItems = Nothing
    Set ns = Nothing

End Sub

Create a new module in Outlook and put this code in there.  This will create a messagebox that won't stop whatever you're doing.
Public Function MsgPopup(Optional Prompt As String, _
                         Optional Buttons As VbMsgBoxStyle = vbOKOnly, _
                         Optional Title As String, _
                         Optional SecondsToWait As Long = 0) As VbMsgBoxResult
' Replicates the VBA MsgBox() function, with an added parameter
' to automatically dismiss the message box after n seconds
' If dismissed automatically, this will return -1: NOT 'cancel' or the default button choice.

' Nigel Heffernan, 2006. This code is in the public domain.

' Uses late-binding: bad for performance and stability, useful for code portability
' The correct declaration is: Dim objWshell As IWshRuntimeLibrary.WshShell

    Dim objWshell As Object
    Set objWshell = CreateObject("WScript.Shell")

    MsgPopup = objWshell.Popup(Prompt, SecondsToWait, Title, Buttons)

    Set objWshell = Nothing

End Function


text:
Q: Vue 3 compare references to same objects with proxy wrapper I have Parent/child component and bind arrays of object by proxy and without proxy:
const selectedTags = ref([]);
const tags = [
    {
        id: 'efrwe',
    },
    {
        id: 'dhjhe23',
    }];

<Child :tags="tags" :selectedTags="selectedTags">

In child component i add selected element from 'tags' to 'selectedTags', its reference to object from source array!
props.selectedTags.push(tags[0]);

But then i try compare this reference on same object i return false!
console.log(tags[0] == selectedTags[0]); // false

You say "okey you try compare proxy object and clear object" but i try comapare with target of proxy and return false again!
console.log(tags[0] == selectedTags[0].target); // false
console.log(tags[0] == selectedTags.target[0]); // false

i try also with 'value'
console.log(tags[0] == selectedTags[0].value); // false
console.log(tags[0] == selectedTags.value[0]); // false

how can i compare reference of same object in vue 3 ?
I think you understand that i want do, computed that return non selected items:
let nonSelected =  computed(() =>
     props.tags.filter(t => props.selectedTags.every(s => s != t))
);

A: The problem is that tags is regular non-reactive array, and selectedTags is deeply reactive, tags[0] is regular object, and selectedTags.value[0] is reactive object, i.e. Proxy instance.
In order to discard a proxy, initial object could be retrieved with toRaw:
toRaw(tags[0]) === toRaw(selectedTags.value[0]).id

ref is unnecessary here because it's not reassigned, it could be reactive array.
But the main problem is that the reactivity of tags and selectedTags is mismatched without a reason. They should either be defined as deeply reactive arrays, e.g. (readonly or reactive), or both as shallowly reactive arrays (shallowReactive, or a combination of reactive and markRaw).
Generally there wouldn't be such problem because this approach doesn't work well with immutable objects that can be expected to be used in such places. A way to do this is to discard object equality and compare the objects by a property that identifies them, i.e. id:
tags[0].id === selectedTags[0].id

Optional chaining can be used if necessary.
As it was said, it's a bad practice to mutate a prop; this makes data flow more complicated. Instead, a child needs to emit selectedTags or a list of id to a parent.


text:
Q: Pyalgotrade SMA Coding Clarification I've started learning and testing PyAlgoTrade and having a hard time understanding some of the logic behind the code of some of the technicals like SMA and RSI.
I understand the self.info() function prints out the dataframe feed it takes as a variable, however, what is the role of the [-1] after SMA and RSI on the last line of the code posted below ?
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import ma
from pyalgotrade.technical import rsi
class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        strategy.BacktestingStrategy.__init__(self, feed)
        self.__rsi = rsi.RSI(feed[instrument].getCloseDataSeries(), 14)
        self.__sma = ma.SMA(self.__rsi, 15)
        self.__instrument = instrument
    def onBars(self, bars):
        bar = bars[self.__instrument]
        self.info("%s %s %s" %(bar.getClose(), self.__rsi[-1], self.__sma[-1]))

A: A negative index simply means: you count from the "rear" end of your array.
In other words: [-1] refers to the last element in your array, [-2] to the "almost last", and so on.


text:
Q: rust-openssl: Could not find directory of OpenSSL installation I am attempting to compile a rust binary in docker but the compilation fails saying openssl is not found despite it being installed. Other answers suggest that having pkg-config and libssl-dev installed resolves the issue, but they already are installed. I believe this issue is related to cross compilation as I have been able to get this image built when the host and target are the same.
Dockerfile:
FROM rust:1.57.0 AS build
WORKDIR /usr/src

RUN rustup target add x86_64-unknown-linux-musl

RUN USER=root cargo new project
WORKDIR /usr/src/project
COPY Cargo.toml Cargo.lock ./
RUN apt-get update \
&& apt-get upgrade \
&& apt-get install -y cmake pkg-config libssl-dev
RUN cargo build --release

Error:
#18 14.01    Compiling openssl-sys v0.9.72
#18 14.17 error: failed to run custom build command for `openssl-sys v0.9.72`
#18 14.18
#18 14.18 Caused by:
#18 14.18   process didn't exit successfully: `/usr/src/project/target/release/build/openssl-sys-64e55e6c4223d7aa/build-script-main` (exit status: 101)
#18 14.18   --- stdout
#18 14.18   cargo:rustc-cfg=const_fn
#18 14.18   cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_MUSL_OPENSSL_LIB_DIR
#18 14.18   X86_64_UNKNOWN_LINUX_MUSL_OPENSSL_LIB_DIR unset
#18 14.18   cargo:rerun-if-env-changed=OPENSSL_LIB_DIR
#18 14.18   OPENSSL_LIB_DIR unset
#18 14.18   cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_MUSL_OPENSSL_INCLUDE_DIR
#18 14.18   X86_64_UNKNOWN_LINUX_MUSL_OPENSSL_INCLUDE_DIR unset
#18 14.18   cargo:rerun-if-env-changed=OPENSSL_INCLUDE_DIR
#18 14.18   OPENSSL_INCLUDE_DIR unset
#18 14.18   cargo:rerun-if-env-changed=X86_64_UNKNOWN_LINUX_MUSL_OPENSSL_DIR
#18 14.18   X86_64_UNKNOWN_LINUX_MUSL_OPENSSL_DIR unset
#18 14.18   cargo:rerun-if-env-changed=OPENSSL_DIR
#18 14.18   OPENSSL_DIR unset
#18 14.18   cargo:rerun-if-env-changed=OPENSSL_NO_PKG_CONFIG
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_ALLOW_CROSS_x86_64-unknown-linux-musl
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_ALLOW_CROSS_x86_64_unknown_linux_musl
#18 14.18   cargo:rerun-if-env-changed=TARGET_PKG_CONFIG_ALLOW_CROSS
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_ALLOW_CROSS
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_x86_64-unknown-linux-musl
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_x86_64_unknown_linux_musl
#18 14.18   cargo:rerun-if-env-changed=TARGET_PKG_CONFIG
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64-unknown-linux-musl
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64_unknown_linux_musl
#18 14.18   cargo:rerun-if-env-changed=TARGET_PKG_CONFIG_SYSROOT_DIR
#18 14.18   cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR
#18 14.18   run pkg_config fail: "pkg-config has not been configured to support cross-compilation.\n\nInstall a sysroot for the target platform and configure it via\nPKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a\ncross-compiling wrapper for pkg-config and set it via\nPKG_CONFIG environment variable."
#18 14.18
#18 14.18   --- stderr
#18 14.18   thread 'main' panicked at '
#18 14.18
#18 14.18   Could not find directory of OpenSSL installation, and this `-sys` crate cannot
#18 14.18   proceed without this knowledge. If OpenSSL is installed and this crate had
#18 14.18   trouble finding it,  you can set the `OPENSSL_DIR` environment variable for the
#18 14.18   compilation process.
#18 14.18
#18 14.18   Make sure you also have the development packages of openssl installed.
#18 14.18   For example, `libssl-dev` on Ubuntu or `openssl-devel` on Fedora.
#18 14.18
#18 14.18   If you're in a situation where you think the directory *should* be found
#18 14.18   automatically, please open a bug at https://github.com/sfackler/rust-openssl
#18 14.18   and include information about your system as well as this message.
#18 14.18
#18 14.18   $HOST = aarch64-unknown-linux-gnu
#18 14.18   $TARGET = x86_64-unknown-linux-musl
#18 14.18   openssl-sys = 0.9.72
#18 14.18
#18 14.18   ', /usr/local/cargo/registry/src/github.com-1ecc6299db9ec823/openssl-sys-0.9.72/build/find_normal.rs:180:5


text:
Q: Assembly increment counter I am trying to make a counter that increments by 1, starting at 0, and uses LED's to show the value in binary from 0-15 then resets itself. I keep running into error A51 in KEIL software on lines 106, 108, 110, and 112. Any help in solving these errors would be great. Thank you in advance!
Here is the code:
#include <reg932.inc>

cseg at 0           ;tells assembler to place 1st instruction in address 0

    MOV 0xA4, #0    ; set port 2 to bi-directional
    MOV 0x91, # 0   ; set port 1 to bi-directional
    MOV 0x84, #0    ; set port 0 to bi-directional
    clr c
    mov A, # 00     ; set accumulator to 0

;lights in a circle
MOV R4, #01         ; set R4 to 0 for 1 loop
MOV R5, #01         ; set R5 to 0 for 1 loop
MOV R6, #15     ; set R6 to 0 for 15 loop

LightsLoop:         ; will light up leds in a circle one at a time

    CPL P2.4
    ACALL LightsDelay
    CPL p2.4
    CPL p0.5
    ACALL LightsDelay
    CPL p0.5
    CPL p2.7
    ACALL LightsDelay
    CPL p2.7
    CPL p0.4
    ACALL LightsDelay
    CPL p0.4
    CPL p2.6
    ACALL LightsDelay
    CPL p2.6
    CPL p0.7
    ACALL LightsDelay
    CPL p0.7
    CPL p2.5
    ACALL LightsDelay
    CPL p2.5
    CPL p0.6
    ACALL LightsDelay
    CPL p0.6
    CPL p2.4
    ACALL LightsDelay
    CPL p2.4

    DJNZ R4, LightsLoop

LightsOnLoop:       ; will light up leds in a circle with them staying on

    CPL p2.4
    ACALL LightsDelay
    CPL p0.5
    ACALL LightsDelay
    CPL p2.7
    ACALL LightsDelay
    CPL p0.4
    ACALL LightsDelay
    CPL p2.6
    ACALL LightsDelay
    CPL p0.7
    ACALL LightsDelay
    CPL p2.5
    ACALL LightsDelay
    CPL p0.6
    ACALL LightsDelay
    CPL p0.6
    ACALL LightsDelay
    CPL p2.4
    DJNZ R5, LightsOnLoop
    SJMP START

LightsDelay:
    MOV R7, #30
    LOOP7:
        MOV R0, #250
        LOOP0:
            MOV R1, #250
                LOOP1:
                    DJNZ R1, LOOP1
    DJNZ R7, LOOP7
    RET

START:                      ;*****find out where this belongs*****
    MOV A, #00010000B
    ACALL Loop

Loop:
    CJNE A, #00000000B ,Next
    ;mAKE A SOUND
    MOV A, #00010000B
    SJMP Loop

Next:
    DEC A
        JB P0.3, 1        ;ERROR LINE
            ACALL AmberPin
        JB P0.2, 1        ;ERROR LINE
            ACALL GreenPin
        JB P0.1, 1        ;ERROR LINE
            ACALL YellowPin
        JB P0.0, 1        ;ERROR LINE
            ACALL RedPin
    SJMP Loop

RedPin:
    CPL P2.4
    ACALL LightsDelay
    CPL p2.4
    SJMP Loop

AmberPin:
    CPL P0.6
    ACALL LightsDelay
    CPL p0.6
    SJMP Loop

GreenPin:
    CPL P2.7
    ACALL LightsDelay
    CPL p2.7
    SJMP Loop

YellowPin:
    CPL P0.5
    ACALL LightsDelay
    CPL p0.5
    SJMP Loop
END

A: You did not specify what error you're getting.
JB x, 1 will jump into the middle of a command.  In any case, it's easier to specify a label here.
        JB P0.3, NotAmber
            ACALL AmberPin
NotAmber:
        JB P0.2, NotGreen

etc.


text:
Q: Expressjs session only persists on localhost I've got a simple web-page created in node/express which has a simple login system. The way i'm testing if a user has logged in, is basically a check to see if req.session.user exist, which is created at login, and the session is destroyed on logout.
This works great as long as the client connects to http://localhost:8000, however, if i connect to http://10.0.1.6:8000 a new session object is created on every request, which means i can never check if the user actually has logged in.
Why is this? I need to connect to http://10.0.1.6:8000 as I'm testing my client from android (where localhost is the android device, not my server/computer).

A: Silly me, gotta stop programming when tired. I was running the index.html file locally, instead of from the server (cross-domain cookies? i laugh in your face!)

A: You can try to set up a session with your app.
var app = express.createServer();
app.use(express.cookieParser(...));
app.use(express.session(...));

According to the docs you also have to use cookieParser() before you set up your session.
http://expressjs.com/guide.html
http://www.senchalabs.org/connect/middleware-session.html


text:
Q: PHP call function/method between class file I need to call a function from a separate class file, let says:
class Functions {

    public function seoUrl($string)
    {
       $string = strtolower($string);
       $string = preg_replace("~[^\p{L}\p{N}\n]+~u", "-", $string);
       $string = preg_replace("/[\s-]+/", " ", $string);
       $string = preg_replace("/[\s_]/", "-", $string);
       return $string;
    }

}

I want Functions::seoUrl() to be call in another class file:
class Product {

    public function goto_url($url)
    {
       return Functions::seoUrl($url);
    }

}

I get error:

Fatal error: Class 'Functions' not found in C:\xampp\htdocs...

A: Functions::seoUrl() is the way to call static method. You need to declare your method seoUrl(string) as static, or create an object for your Functions class
$functions = new Functions();
$functions->seoUrl(string);

A: Here you getting fatal just because your PHP is not able to locate class Functions For this you have two options either you require that file or add some autoloading for this.
<?php

require_once 'Functions.php'// where your Class functions resides.

class Product
{

    public function goto_url($url)
    {
        return Functions::seoUrl($url);
    }

}


text:
Q: Why is this jQuery function failing when called on multiple times? I've created a dialog box and a jQuery function to open / close this. My problem is that after I click 'open' button a second time, something happens and it will not remove the show class.
I'm guessing it's because after being called the first time, "it's still there" when I call it a second time. I have me JS fiddle here to test.
What am I doing wrong for this to not work?
// JS code
$.fn.sl_dialog = function(params){
    var self = this;

    self.after('

')
    $('.dialog').toggleClass('show');

    $('.dialog .close, .dialog .button.no').on('click', function(){
        $('.dialog-background').remove();
        $('.dialog').toggleClass('show');
    });

    return false;
}

$('.clickme').on('click', function(){
    $('.dialog').sl_dialog();
});

A: Move the onclick to outside the function
$.fn.sl_dialog = function(params){
    var self = this;
    self.after('

')
    $('.dialog').toggleClass('show');
    return false;
}
$('.dialog .close, .dialog .button.no').on('click', function(){
    $('.dialog-background').remove();
    $('.dialog').toggleClass('show');
});

Here is the updated Fiddle

A: The problem is that your initialization function (sl_dialog) is binding the close handler every time the dialog is initialized, so when you re-open the dialog the event is bound once again.
When closing the dialog the handler is running twice and the toggleClass('show') is reverting itself.
Either unbind the handler before applying it:
$('.dialog .close, .dialog .button.no').off().on('click', function(){ ...

Or use one():
$('.dialog .close, .dialog .button.no').one('click', function(){ ...

See one() and off() documentation.

A: I was able to fix the issue by changing the toggleClass to specify addClass removeClass
http://jsfiddle.net/b877sc20/6/
I am not 100% as to why this matters, but it seems to
$.fn.sl_dialog = function(params){
    var self = this;

    self.after('

')
    $('.dialog').addClass('show');

    $('.dialog .close, .dialog .button.no').on('click', function(){
        $('.dialog-background').remove();
        $('.dialog').removeClass('show');
    });

    return false;
}

$('.clickme').on('click', function(){
    $('.dialog').sl_dialog();
});

A: The problem is that you're registering the click event multiple times as already other people said.
Try adding a flag to detect if you are calling the method for first time so you avoid adding the same event handler more than once.
$.fn.sl_dialog = function(params){
    var self = this;

    self.after('

')
    $('.dialog').toggleClass('show');

    if (!self.data('initialized')) {
        $('.dialog .close, .dialog .button.no').on('click', function(){
            $('.dialog-background').remove();
            $('.dialog').toggleClass('show');
        });

        // Add the flag to avoid registering again
        self.data('initialized', true);
    }

    return false;
}

DEMO

A: If you need  all code in function area you have to unbind click event as it is bind every time you click on. Try this
http://jsfiddle.net/ycsqequf/
$.fn.sl_dialog = function(params){
var self = this;

self.after('

')
$('.dialog').toggleClass('show');

 $( ".dialog .close, .dialog .button.no" ).off( "click" );
$('.dialog .close, .dialog .button.no').on('click', function(){
    $('.dialog-background').remove();
    $('.dialog').toggleClass('show');
})

return false;
}

$('.clickme').on('click', function(){
$('.dialog').sl_dialog();
});


text:
Q: Vue js how to use props values to v-model I have two component namely App.vue and hello.vue
In App component I import the hello component and use props to pass relevant data to the hello component.
there I bind data which are took from the App component.
In my hello component I have a input box bind to the passed value.
My final goal is pass values as props to the hello component and change it and finally
pass that edited values to the backend using the save method.
How do I achive this?
This is what I have done up to now.
App.vue
<template>

    <hello-world :msg="'hello good morning'"></hello-world>

</template>

hello.vue
<template>

    <input type="text" :value="msg">

</template>

In my hello component's input field v-model is not possible. I want something similar to the v-model.

A: You cannot use prop to bind to v-model. Child component is not supposed to modify prop passed by the parent component.
You will have to create a copy of prop in your child component if you wish to use prop with v-model and then watch prop like this:
<template>

        <input type="text" @input="onInput" v-model="msgCopy">

</template>

Also, notice the use of event handler @input to pass changed prop back to the parent component via event. As a syntax sugar, you can make your Hello component work as a custom form input control by adopting to v-model lifecycle.


text:
Q: md5 possibility value unreasonable? I want to ask about data encryption MD5 could really be 32 characters ..
I take the example of binary to decimal conversion
the way, the number of possible 3-digit binary was equal to 23. The second was in the can because there are only binary 0 and 1.
3 examples of possible binary digit:
000 001 010 011
100 101 110 111 -> 8 possible

and the possible outcome of binary TSB 3 is 0 s / d 7 -> 8 possible
from there can I conclude, how to find a lot of possibilities for the value of the hash is to calculate your own chances of hash TSB like the example above.
My last question on MD5, we know that 32-digit MD5, well then we can count the number of possibilities,
32 digits it in every one digit has the possibility of small letters az and 0-9, it means there are 26 + 10 = 36 chances per one digit
then if the 32 digits then,
3632
= 63340286662973277706162286946811886609896461828096
 means we know that the 32-digit md5 it has the possibility that much, let us round it off just so easy
6300000000000000000000000000000000000000000000000000
Surprisingly, I really encrypt md5 in website
http://md5encryption.com/
and
http://www.md5online.org/md5-encrypt.html
with numbers
9999999999999999999999999999999999999999999999999999
and after I encrypt md5 be like this
bf743ebd7f422b7fd5e4c5f0a90a3303
I thought why not make sense yes ..
Let us count the number of possibilities from the above figures
9999999999999999999999999999999999999999999999999999
aka "9 No 52"
means the number of chances
1052 <<
whereas we know that it is only the number of possible md5
6300000000000000000000000000000000000000000000000000 (circle result) his alias 63 and 0. No 50,
The value of CLEAR "is smaller than the possibility of the number" 9 No 52 "which is 1052
I can be like that?
Indeed every possible results of md5 decrypt it there value2 are equally so?

A: *

*MD5 algorithm
MD5 processes a variable-length message into a fixed-length output of 128 bits. The input message is broken up into chunks of 512-bit blocks (sixteen 32-bit words); the message is padded so that its length is divisible by 512.

*Big number
The big number such as 99999...999 [aka 9 No 52] that you mentioned will be stored with only a few bytes of memory space. Specifically, If it is stored as ascii(0x39 is ascii value for '9'), it only needs 52 bytes--{0x39,0x39,...0x39}. If it is stored as binary value, it will need less than 16 bytes -- because 16 bytes(128 bits) can hold a big number value no more than (2 No 128). That is to say, the big number can be stored/expressed with only tens of bytes. It is not a big deal for MD5 , which has been applied to verify those large download files(millions of bytes).

*MD5 Collision
It seems what you were worried about is some behaviour similar to hash collision. But that's another thing. For MD5,
It is now well-known that the cryptographic hash function MD5 has been broken(Not really,just the Collision). In March 2005, Xiaoyun Wang and Hongbo Yu of Shandong University in China published an article in which they describe an algorithm that can find two different sequences of 128 bytes with the same MD5 hash. One famous such pair is the following:
d131dd02c5e6eec4693d9a0698aff95c 2fcab58712467eab4004583eb8fb7f89
55ad340609f4b30283e488832571415a 085125e8f7cdc99fd91dbdf280373c5b
d8823e3156348f5bae6dacd436c919c6 dd53e2b487da03fd02396306d248cda0
e99f33420f577ee8ce54b67080a80d1e c69821bcb6a8839396f9652b6ff72a70

and
d131dd02c5e6eec4693d9a0698aff95c 2fcab50712467eab4004583eb8fb7f89
55ad340609f4b30283e4888325f1415a 085125e8f7cdc99fd91dbd7280373c5b
d8823e3156348f5bae6dacd436c919c6 dd53e23487da03fd02396306d248cda0
e99f33420f577ee8ce54b67080280d1e c69821bcb6a8839396f965ab6ff72a70

Each of these blocks has MD5 hash
79054025255fb1a26e4bc422aef54eb4


text:
Q: Which protocol should be used to send video stream to a media server for live streaming? I am working on an iOS application to stream live video from iPhone to  a media server and then make it available to a larger audience using RTSP.
Which protocol or method I should use to send the video stream to a server.
Thanks.

A: HTTP Live streaming is not designed for you needs, it's for server->clients + I won't comment about huge delay it implies
You better check RTSP or RTMP protocol and LivU blog

A: For Celluar
Apple seems to make a distinction between apps that are used for just streaming content from servers and those that are used for some type of conferencing.
I think VOIP types are safe, and it seems like gocoder presenter types apps don't have issues either. There's no official page detailing this, but there is some mention under what apples considers VOIP app.
No app has issues if its over wifi only.


text:
Q: Why Apache Beam's Spark runner giving error Error: Failed to load org/apache/beam/sdk/options/PipelineOptions? I tried to run a working Apache Beam code with Spark-Runner using command
spark-submit --class org.apache.beam.examples.WordCount --master spark://localhost:4040 target\word-count-beam-0.1.jar
--runner=SparkRunner

but it throws error
Error: Failed to load org.apache.beam.examples.WordCount: org/apache/beam/sdk/options/PipelineOptions
22/04/29 12:59:54 INFO ShutdownHookManager: Shutdown hook called
22/04/29 12:59:54 INFO ShutdownHookManager: Deleting directory C:\Users\Mohit\AppData\Local\Temp\spark-8f8164aa-816e-4d96-96d0-f1ec7441d4a8

This first line in above error this is the problem.
I am just trying to run normal example of WordCount that Apache Beam gives. Do anybody have an idea?


text:
Q: Mat constructor from user allocated data in OpenCV I am trying to create a Mat object from some data I have allocated in memory using this constructor.
C++: Mat::Mat(Size size, int type, void* data, size_t step=AUTO_STEP)

I am fairly new to C++ so bear that in mind if I am making a rudimentary error somewhere. Basically what I am trying to do is display an image from a raw video file. To do this, I read  the data from the file and allocated it in memory.
struct videoFrame{
    float frameTime;
    unsigned short int year, day, msec;
    unsigned char hour, min, sec;
    unsigned short int mFrame[SIZE];
};

...
//seek to first frame
vfs.seekg(2560, ios_base::beg);
int pos;
for(pos=0; pos<SIZE;pos++){
    vfs.read( (char*) &mVideoFrame1->mFrame[pos], sizeof(short));
}
Mat mImage1( Size(WIDTH, HEIGHT), CV_16UC1, mVideoFrame1->mFrame, HEIGHT * 2);
namedWindow("Frame 1", CV_WINDOW_AUTOSIZE);
imshow("Frame 1", mImage1);
waitKey(0);

I have been able to read data from the file... such as frame and video headerers. I think I may not be clear on how the constructor works. If someone could offer some insight that would be great. When I show the frame in the namedWindow it is all black.
By the way...
const int HEIGHT = 512;
const int WIDTH = 640;
const int SIZE = HEIGHT * WIDTH * 2;

the raw data in the first frame is 512x640 16bit unsigned little Endian byte order black and white.

A: step is the size of the image stride which is equal to or larger than sizeof(_PIXELTYPE) * Width. You don't specify your problem, but I note you wrongly have put step equal to 2*HEIGHT. Otherwise your constructor usage seems ok.
EDIT: of course just use auto step which calculates the default stride for you.

A: Found what was wrong... The data in the file is 16 bit unsigned, but the range for each pixel is only 12 bit. So that was the whole reason the window was showing up black.
OpenCV I suppose does not offer support for displaying 12bit unsigned data, so I had to convert it to 8bit unsigned for it to be displayed. And yes its much more efficient to read all pixel data in block, rather than a loop.
vfs.read( (char*) &mVideoFrame1->mFrame, sizeof(mVideoFrame1->mFrame));

Mat mImage1(HEIGHT, WIDTH, CV_16UC1, mVideoFrame1->mFrame, Mat::AUTO_STEP);
Mat mine(Size(640,512), CV_8UC1);
mImage1.convertTo(mine, CV_8UC1, 255.0/4095.0);
namedWindow("Frame 1", CV_WINDOW_AUTOSIZE);
imshow("Frame 1", mine);
waitKey(0);

So yeah, wasn't to hard lol


text:
Q: Formatting & Comparing ISO String dates in Angular I am developing an advanced Angular To-Do App, which can be viewed here: https://personal-organizer.herokuapp.com/
The App is almost finished, I am just working on displaying the tasks in the "Overdue", "Due Today" and "Due Later" sections within the List state.
To achieve that, I am generating Today's date in the controller, and then I am comparing it to the Task date - placing the task in the appropriate section according to the result of the date comparison.
This is my controller, where I am creating today's date:
function ListCtrl(library) {

var vm = this;

vm.tasks = [];    // array with all tasks

library.getTask(vm.tasks);   // filling the array with data from database
console.log(vm.tasks);

vm.today = new Date().toISOString();   // generating today's date
console.log(vm.today);

}

And this is my HTML file, where I make the date comparison to display the tasks on their appropriate sections on the page:

OVERDUE

        <task-content ng-repeat="task in ListVM.tasks"
                   task-data="task"
                   ng-if="task.completed === false && task.date < ListVM.today">
        </task-content>

DUE TODAY

        <task-content ng-repeat="task in ListVM.tasks"
                   task-data="task"
                   ng-if="task.completed === false && task.date === ListVM.today"">
        </task-content>

DUE LATER

        <task-content ng-repeat="task in ListVM.tasks"
                   task-data="task"
                   ng-if="task.completed === false && task.date > ListVM.today">
        </task-content>

By console logging today's date (vm.today), I am getting an ISO string:
    2017-10-31T17:31:23.770Z
And, by console logging my task array, which is stored in a mongo database, the result object is as follows:
0:{_id: "59f42085c4efd11d743dd739", todo: "Build another App", date: "2017-10-29T04:00:00.000Z", completed: true, __v: 0, …}
1:{_id: "59efa6440667b62c30028932", todo: "Update Portfolio", date: "2017-11-04T04:00:00.000Z", completed: true, __v: 0, …}
2:{_id: "59f8077a33e2680012bdb190", todo: "Mobile Design", date: "2017-11-10T05:00:00.000Z", completed: false, __v: 0, …}
3:{_id: "59f4cbc487bfab0012cb832b", todo: "Travel to Brazil", date: "2017-11-15T05:00:00.000Z", completed: false, __v: 0, …}

Now, this were the problem is. Every time I reload the page and generate a new Today date, the "TxxxZ" part of the string is different.
That makes it impossible to find a Today date that is equal to the Task date in the database. Even though the day, month and year are the same, the "TxxxZ" part of the string will be different.
Is there any way I can format the Today date and Task date strings, cutting out the "TxxxZ" part - so only the day, month and year are compared?
Or is there another more efficient way to compare these dates and achieve the desired result?
*** This question was flagged as a duplicate, but the suggested answer for the other question, the method setHours() does not work for dates as ISO Strings - and I need to compare both dates in that format.


text:
Q: pause an infiniteTransition animation in jetpack compose I need to create a button that can play/pause an animation. I was able to switch between two different modifiers. One that is animating and one that is still, but when you go from the pause modifier to the playing modifier it jumps forward because the float was still being animated. Any suggestions for what I need to do, to play/pause an animation?
var playing by remember {
    mutableStateOf(true)
}
val transition = rememberInfiniteTransition()
val coefficient by transition.animateFloat(initialValue = 0f, targetValue = 1f, animationSpec = infiniteRepeatable(tween()))
Column() {
    Button(onClick = {
        //need to play/pause the anitmation
        playing = !playing
    }) {
        if (playing) {
            Text("Pause")
        } else {
            Text("Play")
        }
    }
    Text("I am rotating!", modifier = Modifier.graphicsLayer {
        rotationZ = 360f * coefficient
    })
}

A: If you want text to be at initial position on pause then you need a small change in your code i.e., an if condition in rotationZ:
var playing by remember {
mutableStateOf(true)
}
val transition = rememberInfiniteTransition()
val coefficient by transition.animateFloat(initialValue = 0f, targetValue= 1f, animationSpec = infiniteRepeatable(tween()))
Column() {
    Button(onClick = {
        //need to play/pause the anitmation
        playing = !playing
    }) {
        if (playing) {
            Text("Pause")
        } else {
            Text("Play")
        }
    }
    Text("I am rotating!", modifier = Modifier.graphicsLayer {
        rotationZ = if(playing) 360f * coefficient else this.rotationZ
    })
}

And if you want to stop text rotation on last rotated place then you need to add an extra variable that will hold the last coefficient value on stop:
var playing by remember {
    mutableStateOf(true)
}

var lastRotation by remember {
    mutableStateOf(0f)
}

val transition = rememberInfiniteTransition()

val coefficient by transition.animateFloat(initialValue = 0f, targetValue = 1f, animationSpec = infiniteRepeatable(tween()))

Column() {
    Button(onClick = {
        //need to play/pause the anitmation
        playing = !playing
        lastRotation = coefficient
    }) {
        if (playing) {
            Text("Pause")
        } else {
            Text("Play")
        }
    }
    Text("I am rotating!", modifier = Modifier.graphicsLayer {
        rotationZ = if (playing) 360f * coefficient else 360f * lastRotation
    })
}

Hope this answer helps you!


text:
Q: Swift: set array as reference ClassA {
    let arrInt = [1,2,3]
}

ClassB {
    var arrInt: [Int]?

    func init(_ arrIntTmp: [Int]) {
        arrInt = arrIntTmp
    }

    func print() {

    }
}

let classA = ClassA()
let classB = ClassB(classA.arrInt)
classA.arrInt.append(4)
classB.print() // expects to print 1 2 3 4 but up to 3 only

I want the array of ClassB to get all the changes done to array in ClassA.
Is array always pass by value?

A: Array and Dictionary are intentially structs. Their value semantics might seem like a restriction, but it's an intentional design choice to limit unintentional data sharing. When you have an Array, you can be certain that its content will never change from any kind outside cause. This is really effective at preventing an entire class of tricky bugs, so I would definitely advise you to embrace it.
If you're certain that you have no other option, and that you need reference semantics, then you can use the reference counterpart to the struct (E.g. NS(Mutable)Array for Array). For other structs with no class counterpart, you can use a Box, like I demonstrate below.
class Box<T> {
    var contents: T

    init(_ contents: T) {
        self.contents = contents
    }
}

class ClassA {
    var arrInt = Box([1,2,3])
}

class ClassB {
    let arrInt: Box<[Int]>

    init(_ arrInt: Box<[Int]>) {
        self.arrInt = arrInt
    }
}

let objectA = ClassA()
let objectB = ClassB(objectA.arrInt)
objectA.arrInt.contents.append(4)
print(objectB.arrInt.contents)


text:
Q: Create a temp table show percentage of null value for all column in a given table I have an sql server loop exercise : Write code to create a table that shows percentage of null/ blank value for all the columns of table sql_practice . ( sql_practice table of my database have many columns so I need to use loop but I dont know how to code)

A: Not really sure what you are trying to accomplish but something like this will give you the percentage of rows for a single column that is not null. You could extend this to additional columns easily.
declare @Something table
(
    MyCol int null
)

insert @Something values
(0),(1),(2),(3),(4),(5),(null),(null)

select NotNullPercentage = count(MyCol) / (count(*) * 1.0) --need to multiply by 1.0 to avoid integer math
from @Something